48e27adf7e833193a158608b3813cefa412d1ec1
[flac.git] / src / libFLAC / encoder.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000,2001  Josh Coalson
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA  02111-1307, USA.
18  */
19
20 #include <assert.h>
21 #include <stdio.h>
22 #include <stdlib.h> /* for malloc() */
23 #include <string.h> /* for memcpy() */
24 #include "FLAC/encoder.h"
25 #include "FLAC/seek_table.h"
26 #include "private/bitbuffer.h"
27 #include "private/bitmath.h"
28 #include "private/crc.h"
29 #include "private/encoder_framing.h"
30 #include "private/fixed.h"
31 #include "private/lpc.h"
32 #include "private/md5.h"
33
34 #ifdef min
35 #undef min
36 #endif
37 #define min(x,y) ((x)<(y)?(x):(y))
38
39 #ifdef max
40 #undef max
41 #endif
42 #define max(x,y) ((x)>(y)?(x):(y))
43
44 typedef struct FLAC__EncoderPrivate {
45         unsigned input_capacity;                    /* current size (in samples) of the signal and residual buffers */
46         int32 *integer_signal[FLAC__MAX_CHANNELS];  /* the integer version of the input signal */
47         int32 *integer_signal_mid_side[2];          /* the integer version of the mid-side input signal (stereo only) */
48         real *real_signal[FLAC__MAX_CHANNELS];      /* the floating-point version of the input signal */
49         real *real_signal_mid_side[2];              /* the floating-point version of the mid-side input signal (stereo only) */
50         unsigned subframe_bps[FLAC__MAX_CHANNELS];  /* the effective bits per sample of the input signal (stream bps - wasted bits) */
51         unsigned subframe_bps_mid_side[2];          /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
52         int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
53         int32 *residual_workspace_mid_side[2][2];
54         FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
55         FLAC__Subframe subframe_workspace_mid_side[2][2];
56         FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
57         FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
58         unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index into the above workspaces */
59         unsigned best_subframe_mid_side[2];
60         unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
61         unsigned best_subframe_bits_mid_side[2];
62         uint32 *abs_residual;                       /* workspace where abs(candidate residual) is stored */
63         uint32 *abs_residual_partition_sums;        /* workspace where the sum of abs(candidate residual) for each partition is stored */
64         unsigned *raw_bits_per_partition;           /* workspace where the sum of silog2(candidate residual) for each partition is stored */
65         FLAC__BitBuffer frame;                      /* the current frame being worked on */
66         bool current_frame_can_do_mid_side;         /* encoder sets this false when any given sample of a frame's side channel exceeds 16 bits */
67         double loose_mid_side_stereo_frames_exact;  /* exact number of frames the encoder will use before trying both independent and mid/side frames again */
68         unsigned loose_mid_side_stereo_frames;      /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
69         unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
70         FLAC__ChannelAssignment last_channel_assignment;
71         FLAC__StreamMetaData metadata;
72         unsigned current_sample_number;
73         unsigned current_frame_number;
74         struct MD5Context md5context;
75         bool use_slow;                              /* use slow 64-bit versions of some functions */
76         FLAC__EncoderWriteStatus (*write_callback)(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
77         void (*metadata_callback)(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data);
78         void *client_data;
79 } FLAC__EncoderPrivate;
80
81 static bool encoder_resize_buffers_(FLAC__Encoder *encoder, unsigned new_size);
82 static bool encoder_process_frame_(FLAC__Encoder *encoder, bool is_last_frame);
83 static bool encoder_process_subframes_(FLAC__Encoder *encoder, bool is_last_frame);
84 static bool encoder_process_subframe_(FLAC__Encoder *encoder, unsigned max_partition_order, bool verbatim_only, const FLAC__FrameHeader *frame_header, unsigned subframe_bps, const int32 integer_signal[], const real real_signal[], FLAC__Subframe *subframe[2], int32 *residual[2], unsigned *best_subframe, unsigned *best_bits);
85 static bool encoder_add_subframe_(FLAC__Encoder *encoder, const FLAC__FrameHeader *frame_header, unsigned subframe_bps, const FLAC__Subframe *subframe, FLAC__BitBuffer *frame);
86 static unsigned encoder_evaluate_constant_subframe_(const int32 signal, unsigned subframe_bps, FLAC__Subframe *subframe);
87 static unsigned encoder_evaluate_fixed_subframe_(const int32 signal[], int32 residual[], uint32 abs_residual[], uint32 abs_residual_partition_sums[], unsigned raw_bits_per_partition[], unsigned blocksize, unsigned subframe_bps, unsigned order, unsigned rice_parameter, unsigned max_partition_order, FLAC__Subframe *subframe);
88 static unsigned encoder_evaluate_lpc_subframe_(const int32 signal[], int32 residual[], uint32 abs_residual[], uint32 abs_residual_partition_sums[], unsigned raw_bits_per_partition[], const real lp_coeff[], unsigned blocksize, unsigned subframe_bps, unsigned order, unsigned qlp_coeff_precision, unsigned rice_parameter, unsigned max_partition_order, FLAC__Subframe *subframe);
89 static unsigned encoder_evaluate_verbatim_subframe_(const int32 signal[], unsigned blocksize, unsigned subframe_bps, FLAC__Subframe *subframe);
90 static unsigned encoder_find_best_partition_order_(const int32 residual[], uint32 abs_residual[], uint32 abs_residual_partition_sums[], unsigned raw_bits_per_partition[], unsigned residual_samples, unsigned predictor_order, unsigned rice_parameter, unsigned max_partition_order, unsigned *best_partition_order, unsigned best_parameters[], unsigned best_raw_bits[]);
91 #if (defined PRECOMPUTE_PARTITION_SUMS) || (defined SEARCH_FOR_ESCAPES)
92 static unsigned encoder_precompute_partition_info_(const int32 residual[], uint32 abs_residual[], uint32 abs_residual_partition_sums[], unsigned raw_bits_per_partition[], unsigned residual_samples, unsigned predictor_order, unsigned max_partition_order);
93 #endif
94 static bool encoder_set_partitioned_rice_(const uint32 abs_residual[], const uint32 abs_residual_partition_sums[], const unsigned raw_bits_per_partition[], const unsigned residual_samples, const unsigned predictor_order, unsigned rice_parameter, const unsigned partition_order, unsigned parameters[], unsigned raw_bits[], unsigned *bits);
95 static unsigned encoder_get_wasted_bits_(int32 signal[], unsigned samples);
96
97 const char *FLAC__EncoderWriteStatusString[] = {
98         "FLAC__ENCODER_WRITE_OK",
99         "FLAC__ENCODER_WRITE_FATAL_ERROR"
100 };
101
102 const char *FLAC__EncoderStateString[] = {
103         "FLAC__ENCODER_OK",
104         "FLAC__ENCODER_UNINITIALIZED",
105         "FLAC__ENCODER_INVALID_NUMBER_OF_CHANNELS",
106         "FLAC__ENCODER_INVALID_BITS_PER_SAMPLE",
107         "FLAC__ENCODER_INVALID_SAMPLE_RATE",
108         "FLAC__ENCODER_INVALID_BLOCK_SIZE",
109         "FLAC__ENCODER_INVALID_QLP_COEFF_PRECISION",
110         "FLAC__ENCODER_MID_SIDE_CHANNELS_MISMATCH",
111         "FLAC__ENCODER_MID_SIDE_SAMPLE_SIZE_MISMATCH",
112         "FLAC__ENCODER_ILLEGAL_MID_SIDE_FORCE",
113         "FLAC__ENCODER_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
114         "FLAC__ENCODER_NOT_STREAMABLE",
115         "FLAC__ENCODER_FRAMING_ERROR",
116         "FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING",
117         "FLAC__ENCODER_FATAL_ERROR_WHILE_WRITING",
118         "FLAC__ENCODER_MEMORY_ALLOCATION_ERROR"
119 };
120
121
122 bool encoder_resize_buffers_(FLAC__Encoder *encoder, unsigned new_size)
123 {
124         bool ok;
125         unsigned i, channel;
126         int32 *previous_is, *current_is;
127         real *previous_rs, *current_rs;
128         int32 *residual;
129         uint32 *abs_residual;
130         unsigned *raw_bits_per_partition;
131
132         assert(new_size > 0);
133         assert(encoder->state == FLAC__ENCODER_OK);
134         assert(encoder->guts->current_sample_number == 0);
135
136         /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
137         if(new_size <= encoder->guts->input_capacity)
138                 return true;
139
140         ok = 1;
141         if(ok) {
142                 for(i = 0; ok && i < encoder->channels; i++) {
143                         /* integer version of the signal */
144                         previous_is = encoder->guts->integer_signal[i];
145                         current_is = (int32*)malloc(sizeof(int32) * new_size);
146                         if(0 == current_is) {
147                                 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
148                                 ok = 0;
149                         }
150                         else {
151                                 encoder->guts->integer_signal[i] = current_is;
152                                 if(previous_is != 0)
153                                         free(previous_is);
154                         }
155                         /* real version of the signal */
156                         previous_rs = encoder->guts->real_signal[i];
157                         current_rs = (real*)malloc(sizeof(real) * new_size);
158                         if(0 == current_rs) {
159                                 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
160                                 ok = 0;
161                         }
162                         else {
163                                 encoder->guts->real_signal[i] = current_rs;
164                                 if(previous_rs != 0)
165                                         free(previous_rs);
166                         }
167                 }
168         }
169         if(ok) {
170                 for(i = 0; ok && i < 2; i++) {
171                         /* integer version of the signal */
172                         previous_is = encoder->guts->integer_signal_mid_side[i];
173                         current_is = (int32*)malloc(sizeof(int32) * new_size);
174                         if(0 == current_is) {
175                                 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
176                                 ok = 0;
177                         }
178                         else {
179                                 encoder->guts->integer_signal_mid_side[i] = current_is;
180                                 if(previous_is != 0)
181                                         free(previous_is);
182                         }
183                         /* real version of the signal */
184                         previous_rs = encoder->guts->real_signal_mid_side[i];
185                         current_rs = (real*)malloc(sizeof(real) * new_size);
186                         if(0 == current_rs) {
187                                 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
188                                 ok = 0;
189                         }
190                         else {
191                                 encoder->guts->real_signal_mid_side[i] = current_rs;
192                                 if(previous_rs != 0)
193                                         free(previous_rs);
194                         }
195                 }
196         }
197         if(ok) {
198                 for(channel = 0; channel < encoder->channels; channel++) {
199                         for(i = 0; i < 2; i++) {
200                                 residual = (int32*)malloc(sizeof(int32) * new_size);
201                                 if(0 == residual) {
202                                         encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
203                                         ok = 0;
204                                 }
205                                 else {
206                                         if(encoder->guts->residual_workspace[channel][i] != 0)
207                                                 free(encoder->guts->residual_workspace[channel][i]);
208                                         encoder->guts->residual_workspace[channel][i] = residual;
209                                 }
210                         }
211                 }
212                 for(channel = 0; channel < 2; channel++) {
213                         for(i = 0; i < 2; i++) {
214                                 residual = (int32*)malloc(sizeof(int32) * new_size);
215                                 if(0 == residual) {
216                                         encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
217                                         ok = 0;
218                                 }
219                                 else {
220                                         if(encoder->guts->residual_workspace_mid_side[channel][i] != 0)
221                                                 free(encoder->guts->residual_workspace_mid_side[channel][i]);
222                                         encoder->guts->residual_workspace_mid_side[channel][i] = residual;
223                                 }
224                         }
225                 }
226                 abs_residual = (uint32*)malloc(sizeof(uint32) * new_size);
227                 if(0 == abs_residual) {
228                         encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
229                         ok = 0;
230                 }
231                 else {
232                         if(encoder->guts->abs_residual != 0)
233                                 free(encoder->guts->abs_residual);
234                         encoder->guts->abs_residual = abs_residual;
235                 }
236                 abs_residual = (uint32*)malloc(sizeof(uint32) * (new_size * 2));
237                 if(0 == abs_residual) {
238                         encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
239                         ok = 0;
240                 }
241                 else {
242                         if(encoder->guts->abs_residual_partition_sums != 0)
243                                 free(encoder->guts->abs_residual_partition_sums);
244                         encoder->guts->abs_residual_partition_sums = abs_residual;
245                 }
246                 raw_bits_per_partition = (unsigned*)malloc(sizeof(unsigned) * (new_size * 2));
247                 if(0 == raw_bits_per_partition) {
248                         encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
249                         ok = 0;
250                 }
251                 else {
252                         if(encoder->guts->raw_bits_per_partition != 0)
253                                 free(encoder->guts->raw_bits_per_partition);
254                         encoder->guts->raw_bits_per_partition = raw_bits_per_partition;
255                 }
256         }
257         if(ok)
258                 encoder->guts->input_capacity = new_size;
259
260         return ok;
261 }
262
263 FLAC__Encoder *FLAC__encoder_get_new_instance()
264 {
265         FLAC__Encoder *encoder = (FLAC__Encoder*)malloc(sizeof(FLAC__Encoder));
266         if(encoder != 0) {
267                 encoder->state = FLAC__ENCODER_UNINITIALIZED;
268                 encoder->guts = 0;
269         }
270         return encoder;
271 }
272
273 void FLAC__encoder_free_instance(FLAC__Encoder *encoder)
274 {
275         assert(encoder != 0);
276         free(encoder);
277 }
278
279 FLAC__EncoderState FLAC__encoder_init(FLAC__Encoder *encoder, FLAC__EncoderWriteStatus (*write_callback)(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data), void (*metadata_callback)(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data), void *client_data)
280 {
281         unsigned i;
282         FLAC__StreamMetaData padding;
283         FLAC__StreamMetaData seek_table;
284
285         assert(sizeof(int) >= 4); /* we want to die right away if this is not true */
286         assert(encoder != 0);
287         assert(write_callback != 0);
288         assert(metadata_callback != 0);
289         assert(encoder->state == FLAC__ENCODER_UNINITIALIZED);
290         assert(encoder->guts == 0);
291
292         encoder->state = FLAC__ENCODER_OK;
293
294         if(encoder->channels == 0 || encoder->channels > FLAC__MAX_CHANNELS)
295                 return encoder->state = FLAC__ENCODER_INVALID_NUMBER_OF_CHANNELS;
296
297         if(encoder->do_mid_side_stereo && encoder->channels != 2)
298                 return encoder->state = FLAC__ENCODER_MID_SIDE_CHANNELS_MISMATCH;
299
300         if(encoder->loose_mid_side_stereo && !encoder->do_mid_side_stereo)
301                 return encoder->state = FLAC__ENCODER_ILLEGAL_MID_SIDE_FORCE;
302
303         if(encoder->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->bits_per_sample > FLAC__MAX_BITS_PER_SAMPLE)
304                 return encoder->state = FLAC__ENCODER_INVALID_BITS_PER_SAMPLE;
305
306         if(encoder->sample_rate == 0 || encoder->sample_rate > FLAC__MAX_SAMPLE_RATE)
307                 return encoder->state = FLAC__ENCODER_INVALID_SAMPLE_RATE;
308
309         if(encoder->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->blocksize > FLAC__MAX_BLOCK_SIZE)
310                 return encoder->state = FLAC__ENCODER_INVALID_BLOCK_SIZE;
311
312         if(encoder->blocksize < encoder->max_lpc_order)
313                 return encoder->state = FLAC__ENCODER_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
314
315         if(encoder->qlp_coeff_precision == 0) {
316                 if(encoder->bits_per_sample < 16) {
317                         /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
318                         /* @@@ until then we'll make a guess */
319                         encoder->qlp_coeff_precision = max(5, 2 + encoder->bits_per_sample / 2);
320                 }
321                 else if(encoder->bits_per_sample == 16) {
322                         if(encoder->blocksize <= 192)
323                                 encoder->qlp_coeff_precision = 7;
324                         else if(encoder->blocksize <= 384)
325                                 encoder->qlp_coeff_precision = 8;
326                         else if(encoder->blocksize <= 576)
327                                 encoder->qlp_coeff_precision = 9;
328                         else if(encoder->blocksize <= 1152)
329                                 encoder->qlp_coeff_precision = 10;
330                         else if(encoder->blocksize <= 2304)
331                                 encoder->qlp_coeff_precision = 11;
332                         else if(encoder->blocksize <= 4608)
333                                 encoder->qlp_coeff_precision = 12;
334                         else
335                                 encoder->qlp_coeff_precision = 13;
336                 }
337                 else {
338                         encoder->qlp_coeff_precision = min(13, 8*sizeof(int32) - encoder->bits_per_sample - 1);
339                 }
340         }
341         else if(encoder->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->qlp_coeff_precision + encoder->bits_per_sample >= 8*sizeof(uint32) || encoder->qlp_coeff_precision >= (1u<<FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
342                 return encoder->state = FLAC__ENCODER_INVALID_QLP_COEFF_PRECISION;
343
344         if(encoder->streamable_subset) {
345                 //@@@ add check for blocksize here
346                 if(encoder->bits_per_sample != 8 && encoder->bits_per_sample != 12 && encoder->bits_per_sample != 16 && encoder->bits_per_sample != 20 && encoder->bits_per_sample != 24)
347                         return encoder->state = FLAC__ENCODER_NOT_STREAMABLE;
348                 if(encoder->sample_rate > 655350)
349                         return encoder->state = FLAC__ENCODER_NOT_STREAMABLE;
350         }
351
352         if(encoder->rice_optimization_level >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
353                 encoder->rice_optimization_level = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
354
355         encoder->guts = (FLAC__EncoderPrivate*)malloc(sizeof(FLAC__EncoderPrivate));
356         if(encoder->guts == 0)
357                 return encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
358
359         encoder->guts->input_capacity = 0;
360         for(i = 0; i < encoder->channels; i++) {
361                 encoder->guts->integer_signal[i] = 0;
362                 encoder->guts->real_signal[i] = 0;
363         }
364         for(i = 0; i < 2; i++) {
365                 encoder->guts->integer_signal_mid_side[i] = 0;
366                 encoder->guts->real_signal_mid_side[i] = 0;
367         }
368         for(i = 0; i < encoder->channels; i++) {
369                 encoder->guts->residual_workspace[i][0] = encoder->guts->residual_workspace[i][1] = 0;
370                 encoder->guts->best_subframe[i] = 0;
371         }
372         for(i = 0; i < 2; i++) {
373                 encoder->guts->residual_workspace_mid_side[i][0] = encoder->guts->residual_workspace_mid_side[i][1] = 0;
374                 encoder->guts->best_subframe_mid_side[i] = 0;
375         }
376         for(i = 0; i < encoder->channels; i++) {
377                 encoder->guts->subframe_workspace_ptr[i][0] = &encoder->guts->subframe_workspace[i][0];
378                 encoder->guts->subframe_workspace_ptr[i][1] = &encoder->guts->subframe_workspace[i][1];
379         }
380         for(i = 0; i < 2; i++) {
381                 encoder->guts->subframe_workspace_ptr_mid_side[i][0] = &encoder->guts->subframe_workspace_mid_side[i][0];
382                 encoder->guts->subframe_workspace_ptr_mid_side[i][1] = &encoder->guts->subframe_workspace_mid_side[i][1];
383         }
384         encoder->guts->abs_residual = 0;
385         encoder->guts->abs_residual_partition_sums = 0;
386         encoder->guts->raw_bits_per_partition = 0;
387         encoder->guts->current_frame_can_do_mid_side = true;
388         encoder->guts->loose_mid_side_stereo_frames_exact = (double)encoder->sample_rate * 0.4 / (double)encoder->blocksize;
389         encoder->guts->loose_mid_side_stereo_frames = (unsigned)(encoder->guts->loose_mid_side_stereo_frames_exact + 0.5);
390         if(encoder->guts->loose_mid_side_stereo_frames == 0)
391                 encoder->guts->loose_mid_side_stereo_frames = 1;
392         encoder->guts->loose_mid_side_stereo_frame_count = 0;
393         encoder->guts->current_sample_number = 0;
394         encoder->guts->current_frame_number = 0;
395
396         if(encoder->bits_per_sample + FLAC__bitmath_ilog2(encoder->blocksize)+1 > 30)
397                 encoder->guts->use_slow = true;
398         else
399                 encoder->guts->use_slow = false;
400
401         if(!encoder_resize_buffers_(encoder, encoder->blocksize)) {
402                 /* the above function sets the state for us in case of an error */
403                 return encoder->state;
404         }
405         FLAC__bitbuffer_init(&encoder->guts->frame);
406         encoder->guts->write_callback = write_callback;
407         encoder->guts->metadata_callback = metadata_callback;
408         encoder->guts->client_data = client_data;
409
410         /*
411          * write the stream header
412          */
413         if(!FLAC__bitbuffer_clear(&encoder->guts->frame))
414                 return encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
415
416         if(!FLAC__bitbuffer_write_raw_uint32(&encoder->guts->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN))
417                 return encoder->state = FLAC__ENCODER_FRAMING_ERROR;
418
419         encoder->guts->metadata.type = FLAC__METADATA_TYPE_STREAMINFO;
420         encoder->guts->metadata.is_last = (encoder->seek_table == 0 && encoder->padding == 0);
421         encoder->guts->metadata.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
422         encoder->guts->metadata.data.stream_info.min_blocksize = encoder->blocksize; /* this encoder uses the same blocksize for the whole stream */
423         encoder->guts->metadata.data.stream_info.max_blocksize = encoder->blocksize;
424         encoder->guts->metadata.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
425         encoder->guts->metadata.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
426         encoder->guts->metadata.data.stream_info.sample_rate = encoder->sample_rate;
427         encoder->guts->metadata.data.stream_info.channels = encoder->channels;
428         encoder->guts->metadata.data.stream_info.bits_per_sample = encoder->bits_per_sample;
429         encoder->guts->metadata.data.stream_info.total_samples = encoder->total_samples_estimate; /* we will replace this later with the real total */
430         memset(encoder->guts->metadata.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
431         MD5Init(&encoder->guts->md5context);
432         if(!FLAC__add_metadata_block(&encoder->guts->metadata, &encoder->guts->frame))
433                 return encoder->state = FLAC__ENCODER_FRAMING_ERROR;
434
435         if(0 != encoder->seek_table) {
436                 if(!FLAC__seek_table_is_valid(encoder->seek_table))
437                         return encoder->state = FLAC__ENCODER_INVALID_SEEK_TABLE;
438                 seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
439                 seek_table.is_last = (encoder->padding == 0);
440                 seek_table.length = encoder->seek_table->num_points * FLAC__STREAM_METADATA_SEEKPOINT_LEN;
441                 seek_table.data.seek_table = *encoder->seek_table;
442                 if(!FLAC__add_metadata_block(&seek_table, &encoder->guts->frame))
443                         return encoder->state = FLAC__ENCODER_FRAMING_ERROR;
444         }
445
446         /* add a PADDING block if requested */
447         if(encoder->padding > 0) {
448                 padding.type = FLAC__METADATA_TYPE_PADDING;
449                 padding.is_last = true;
450                 padding.length = encoder->padding;
451                 if(!FLAC__add_metadata_block(&padding, &encoder->guts->frame))
452                         return encoder->state = FLAC__ENCODER_FRAMING_ERROR;
453         }
454
455         assert(encoder->guts->frame.bits == 0); /* assert that we're byte-aligned before writing */
456         assert(encoder->guts->frame.total_consumed_bits == 0); /* assert that no reading of the buffer was done */
457         if(encoder->guts->write_callback(encoder, encoder->guts->frame.buffer, encoder->guts->frame.bytes, 0, encoder->guts->current_frame_number, encoder->guts->client_data) != FLAC__ENCODER_WRITE_OK)
458                 return encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_WRITING;
459
460         /* now that the metadata block is written, we can init this to an absurdly-high value... */
461         encoder->guts->metadata.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
462         /* ... and clear this to 0 */
463         encoder->guts->metadata.data.stream_info.total_samples = 0;
464
465         return encoder->state;
466 }
467
468 void FLAC__encoder_finish(FLAC__Encoder *encoder)
469 {
470         unsigned i, channel;
471
472         assert(encoder != 0);
473         if(encoder->state == FLAC__ENCODER_UNINITIALIZED)
474                 return;
475         if(encoder->guts->current_sample_number != 0) {
476                 encoder->blocksize = encoder->guts->current_sample_number;
477                 encoder_process_frame_(encoder, true); /* true => is last frame */
478         }
479         MD5Final(encoder->guts->metadata.data.stream_info.md5sum, &encoder->guts->md5context);
480         encoder->guts->metadata_callback(encoder, &encoder->guts->metadata, encoder->guts->client_data);
481         if(encoder->guts != 0) {
482                 for(i = 0; i < encoder->channels; i++) {
483                         if(encoder->guts->integer_signal[i] != 0) {
484                                 free(encoder->guts->integer_signal[i]);
485                                 encoder->guts->integer_signal[i] = 0;
486                         }
487                         if(encoder->guts->real_signal[i] != 0) {
488                                 free(encoder->guts->real_signal[i]);
489                                 encoder->guts->real_signal[i] = 0;
490                         }
491                 }
492                 for(i = 0; i < 2; i++) {
493                         if(encoder->guts->integer_signal_mid_side[i] != 0) {
494                                 free(encoder->guts->integer_signal_mid_side[i]);
495                                 encoder->guts->integer_signal_mid_side[i] = 0;
496                         }
497                         if(encoder->guts->real_signal_mid_side[i] != 0) {
498                                 free(encoder->guts->real_signal_mid_side[i]);
499                                 encoder->guts->real_signal_mid_side[i] = 0;
500                         }
501                 }
502                 for(channel = 0; channel < encoder->channels; channel++) {
503                         for(i = 0; i < 2; i++) {
504                                 if(encoder->guts->residual_workspace[channel][i] != 0) {
505                                         free(encoder->guts->residual_workspace[channel][i]);
506                                         encoder->guts->residual_workspace[channel][i] = 0;
507                                 }
508                         }
509                 }
510                 for(channel = 0; channel < 2; channel++) {
511                         for(i = 0; i < 2; i++) {
512                                 if(encoder->guts->residual_workspace_mid_side[channel][i] != 0) {
513                                         free(encoder->guts->residual_workspace_mid_side[channel][i]);
514                                         encoder->guts->residual_workspace_mid_side[channel][i] = 0;
515                                 }
516                         }
517                 }
518                 if(encoder->guts->abs_residual != 0) {
519                         free(encoder->guts->abs_residual);
520                         encoder->guts->abs_residual = 0;
521                 }
522                 if(encoder->guts->abs_residual_partition_sums != 0) {
523                         free(encoder->guts->abs_residual_partition_sums);
524                         encoder->guts->abs_residual_partition_sums = 0;
525                 }
526                 if(encoder->guts->raw_bits_per_partition != 0) {
527                         free(encoder->guts->raw_bits_per_partition);
528                         encoder->guts->raw_bits_per_partition = 0;
529                 }
530                 FLAC__bitbuffer_free(&encoder->guts->frame);
531                 free(encoder->guts);
532                 encoder->guts = 0;
533         }
534         encoder->state = FLAC__ENCODER_UNINITIALIZED;
535 }
536
537 bool FLAC__encoder_process(FLAC__Encoder *encoder, const int32 *buf[], unsigned samples)
538 {
539         unsigned i, j, channel;
540         int32 x, mid, side;
541         const bool ms = encoder->do_mid_side_stereo && encoder->channels == 2;
542         const int32 min_side = -((int64)1 << (encoder->bits_per_sample-1));
543         const int32 max_side =  ((int64)1 << (encoder->bits_per_sample-1)) - 1;
544
545         assert(encoder != 0);
546         assert(encoder->state == FLAC__ENCODER_OK);
547
548         j = 0;
549         do {
550                 for(i = encoder->guts->current_sample_number; i < encoder->blocksize && j < samples; i++, j++) {
551                         for(channel = 0; channel < encoder->channels; channel++) {
552                                 x = buf[channel][j];
553                                 encoder->guts->integer_signal[channel][i] = x;
554                                 encoder->guts->real_signal[channel][i] = (real)x;
555                         }
556                         if(ms && encoder->guts->current_frame_can_do_mid_side) {
557                                 side = buf[0][j] - buf[1][j];
558                                 if(side < min_side || side > max_side) {
559                                         encoder->guts->current_frame_can_do_mid_side = false;
560                                 }
561                                 else {
562                                         mid = (buf[0][j] + buf[1][j]) >> 1; /* NOTE: not the same as 'mid = (buf[0][j] + buf[1][j]) / 2' ! */
563                                         encoder->guts->integer_signal_mid_side[0][i] = mid;
564                                         encoder->guts->integer_signal_mid_side[1][i] = side;
565                                         encoder->guts->real_signal_mid_side[0][i] = (real)mid;
566                                         encoder->guts->real_signal_mid_side[1][i] = (real)side;
567                                 }
568                         }
569                         encoder->guts->current_sample_number++;
570                 }
571                 if(i == encoder->blocksize) {
572                         if(!encoder_process_frame_(encoder, false)) /* false => not last frame */
573                                 return false;
574                 }
575         } while(j < samples);
576
577         return true;
578 }
579
580 /* 'samples' is channel-wide samples, e.g. for 1 second at 44100Hz, 'samples' = 44100 regardless of the number of channels */
581 bool FLAC__encoder_process_interleaved(FLAC__Encoder *encoder, const int32 buf[], unsigned samples)
582 {
583         unsigned i, j, k, channel;
584         int32 x, left = 0, mid, side;
585         const bool ms = encoder->do_mid_side_stereo && encoder->channels == 2;
586         const int32 min_side = -((int64)1 << (encoder->bits_per_sample-1));
587         const int32 max_side =  ((int64)1 << (encoder->bits_per_sample-1)) - 1;
588
589         assert(encoder != 0);
590         assert(encoder->state == FLAC__ENCODER_OK);
591
592         j = k = 0;
593         do {
594                 for(i = encoder->guts->current_sample_number; i < encoder->blocksize && j < samples; i++, j++, k++) {
595                         for(channel = 0; channel < encoder->channels; channel++, k++) {
596                                 x = buf[k];
597                                 encoder->guts->integer_signal[channel][i] = x;
598                                 encoder->guts->real_signal[channel][i] = (real)x;
599                                 if(ms && encoder->guts->current_frame_can_do_mid_side) {
600                                         if(channel == 0) {
601                                                 left = x;
602                                         }
603                                         else {
604                                                 side = left - x;
605                                                 if(side < min_side || side > max_side) {
606                                                         encoder->guts->current_frame_can_do_mid_side = false;
607                                                 }
608                                                 else {
609                                                         mid = (left + x) >> 1; /* NOTE: not the same as 'mid = (left + x) / 2' ! */
610                                                         encoder->guts->integer_signal_mid_side[0][i] = mid;
611                                                         encoder->guts->integer_signal_mid_side[1][i] = side;
612                                                         encoder->guts->real_signal_mid_side[0][i] = (real)mid;
613                                                         encoder->guts->real_signal_mid_side[1][i] = (real)side;
614                                                 }
615                                         }
616                                 }
617                         }
618                         encoder->guts->current_sample_number++;
619                 }
620                 if(i == encoder->blocksize) {
621                         if(!encoder_process_frame_(encoder, false)) /* false => not last frame */
622                                 return false;
623                 }
624         } while(j < samples);
625
626         return true;
627 }
628
629 bool encoder_process_frame_(FLAC__Encoder *encoder, bool is_last_frame)
630 {
631         assert(encoder->state == FLAC__ENCODER_OK);
632
633         /*
634          * Accumulate raw signal to the MD5 signature
635          */
636         /* NOTE: some versions of GCC can't figure out const-ness right and will give you an 'incompatible pointer type' warning on arg 2 here: */
637         if(!FLAC__MD5Accumulate(&encoder->guts->md5context, encoder->guts->integer_signal, encoder->channels, encoder->blocksize, (encoder->bits_per_sample+7) / 8)) {
638                 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
639                 return false;
640         }
641
642         /*
643          * Process the frame header and subframes into the frame bitbuffer
644          */
645         if(!encoder_process_subframes_(encoder, is_last_frame)) {
646                 /* the above function sets the state for us in case of an error */
647                 return false;
648         }
649
650         /*
651          * Zero-pad the frame to a byte_boundary
652          */
653         if(!FLAC__bitbuffer_zero_pad_to_byte_boundary(&encoder->guts->frame)) {
654                 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
655                 return false;
656         }
657
658         /*
659          * CRC-16 the whole thing
660          */
661         assert(encoder->guts->frame.bits == 0); /* assert that we're byte-aligned */
662         assert(encoder->guts->frame.total_consumed_bits == 0); /* assert that no reading of the buffer was done */
663         FLAC__bitbuffer_write_raw_uint32(&encoder->guts->frame, FLAC__crc16(encoder->guts->frame.buffer, encoder->guts->frame.bytes), FLAC__FRAME_FOOTER_CRC_LEN);
664
665         /*
666          * Write it
667          */
668         if(encoder->guts->write_callback(encoder, encoder->guts->frame.buffer, encoder->guts->frame.bytes, encoder->blocksize, encoder->guts->current_frame_number, encoder->guts->client_data) != FLAC__ENCODER_WRITE_OK) {
669                 encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_WRITING;
670                 return false;
671         }
672
673         /*
674          * Get ready for the next frame
675          */
676         encoder->guts->current_frame_can_do_mid_side = true;
677         encoder->guts->current_sample_number = 0;
678         encoder->guts->current_frame_number++;
679         encoder->guts->metadata.data.stream_info.total_samples += (uint64)encoder->blocksize;
680         encoder->guts->metadata.data.stream_info.min_framesize = min(encoder->guts->frame.bytes, encoder->guts->metadata.data.stream_info.min_framesize);
681         encoder->guts->metadata.data.stream_info.max_framesize = max(encoder->guts->frame.bytes, encoder->guts->metadata.data.stream_info.max_framesize);
682
683         return true;
684 }
685
686 bool encoder_process_subframes_(FLAC__Encoder *encoder, bool is_last_frame)
687 {
688         FLAC__FrameHeader frame_header;
689         unsigned channel, max_partition_order;
690         bool do_independent, do_mid_side;
691
692         /*
693          * Calculate the max Rice partition order
694          */
695         if(is_last_frame) {
696                 max_partition_order = 0;
697         }
698         else {
699                 unsigned limit = 0, b = encoder->blocksize;
700                 while(!(b & 1)) {
701                         limit++;
702                         b >>= 1;
703                 }
704                 max_partition_order = min(encoder->rice_optimization_level, limit);
705         }
706
707         /*
708          * Setup the frame
709          */
710         if(!FLAC__bitbuffer_clear(&encoder->guts->frame)) {
711                 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
712                 return false;
713         }
714         frame_header.blocksize = encoder->blocksize;
715         frame_header.sample_rate = encoder->sample_rate;
716         frame_header.channels = encoder->channels;
717         frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
718         frame_header.bits_per_sample = encoder->bits_per_sample;
719         frame_header.number.frame_number = encoder->guts->current_frame_number;
720
721         /*
722          * Figure out what channel assignments to try
723          */
724         if(encoder->do_mid_side_stereo) {
725                 if(encoder->loose_mid_side_stereo) {
726                         if(encoder->guts->loose_mid_side_stereo_frame_count == 0) {
727                                 do_independent = true;
728                                 do_mid_side = true;
729                         }
730                         else {
731                                 do_independent = (encoder->guts->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
732                                 do_mid_side = !do_independent;
733                         }
734                 }
735                 else {
736                         do_independent = true;
737                         do_mid_side = true;
738                 }
739         }
740         else {
741                 do_independent = true;
742                 do_mid_side = false;
743         }
744         if(do_mid_side && !encoder->guts->current_frame_can_do_mid_side) {
745                 do_independent = true;
746                 do_mid_side = false;
747         }
748
749         assert(do_independent || do_mid_side);
750
751         /*
752          * Check for wasted bits; set effective bps for each subframe
753          */
754         if(do_independent) {
755                 unsigned w;
756                 for(channel = 0; channel < encoder->channels; channel++) {
757                         w = encoder_get_wasted_bits_(encoder->guts->integer_signal[channel], encoder->blocksize);
758                         encoder->guts->subframe_workspace[channel][0].wasted_bits = encoder->guts->subframe_workspace[channel][1].wasted_bits = w;
759                         encoder->guts->subframe_bps[channel] = encoder->bits_per_sample - w;
760                 }
761         }
762         if(do_mid_side) {
763                 unsigned w;
764                 assert(encoder->channels == 2);
765                 for(channel = 0; channel < 2; channel++) {
766                         w = encoder_get_wasted_bits_(encoder->guts->integer_signal_mid_side[channel], encoder->blocksize);
767                         encoder->guts->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->guts->subframe_workspace_mid_side[channel][1].wasted_bits = w;
768                         encoder->guts->subframe_bps_mid_side[channel] = encoder->bits_per_sample - w + (channel==0? 0:1);
769                 }
770         }
771
772         /*
773          * First do a normal encoding pass of each independent channel
774          */
775         if(do_independent) {
776                 for(channel = 0; channel < encoder->channels; channel++) {
777                         if(!encoder_process_subframe_(encoder, max_partition_order, false, &frame_header, encoder->guts->subframe_bps[channel], encoder->guts->integer_signal[channel], encoder->guts->real_signal[channel], encoder->guts->subframe_workspace_ptr[channel], encoder->guts->residual_workspace[channel], encoder->guts->best_subframe+channel, encoder->guts->best_subframe_bits+channel))
778                                 return false;
779                 }
780         }
781
782         /*
783          * Now do mid and side channels if requested
784          */
785         if(do_mid_side) {
786                 assert(encoder->channels == 2);
787
788                 for(channel = 0; channel < 2; channel++) {
789                         if(!encoder_process_subframe_(encoder, max_partition_order, false, &frame_header, encoder->guts->subframe_bps_mid_side[channel], encoder->guts->integer_signal_mid_side[channel], encoder->guts->real_signal_mid_side[channel], encoder->guts->subframe_workspace_ptr_mid_side[channel], encoder->guts->residual_workspace_mid_side[channel], encoder->guts->best_subframe_mid_side+channel, encoder->guts->best_subframe_bits_mid_side+channel))
790                                 return false;
791                 }
792         }
793
794         /*
795          * Compose the frame bitbuffer
796          */
797         if(do_mid_side) {
798                 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
799                 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
800                 FLAC__ChannelAssignment channel_assignment;
801
802                 assert(encoder->channels == 2);
803
804                 if(encoder->loose_mid_side_stereo && encoder->guts->loose_mid_side_stereo_frame_count > 0) {
805                         channel_assignment = (encoder->guts->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
806                 }
807                 else {
808                         unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
809                         unsigned min_bits;
810                         FLAC__ChannelAssignment ca;
811
812                         assert(do_independent && do_mid_side);
813
814                         /* We have to figure out which channel assignent results in the smallest frame */
815                         bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->guts->best_subframe_bits         [0] + encoder->guts->best_subframe_bits         [1];
816                         bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE  ] = encoder->guts->best_subframe_bits         [0] + encoder->guts->best_subframe_bits_mid_side[1];
817                         bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->guts->best_subframe_bits         [1] + encoder->guts->best_subframe_bits_mid_side[1];
818                         bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE   ] = encoder->guts->best_subframe_bits_mid_side[0] + encoder->guts->best_subframe_bits_mid_side[1];
819
820                         for(channel_assignment = 0, min_bits = bits[0], ca = 1; ca <= 3; ca++) {
821                                 if(bits[ca] < min_bits) {
822                                         min_bits = bits[ca];
823                                         channel_assignment = ca;
824                                 }
825                         }
826                 }
827
828                 frame_header.channel_assignment = channel_assignment;
829
830                 if(!FLAC__frame_add_header(&frame_header, encoder->streamable_subset, is_last_frame, &encoder->guts->frame)) {
831                         encoder->state = FLAC__ENCODER_FRAMING_ERROR;
832                         return false;
833                 }
834
835                 switch(channel_assignment) {
836                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
837                                 left_subframe  = &encoder->guts->subframe_workspace         [0][encoder->guts->best_subframe         [0]];
838                                 right_subframe = &encoder->guts->subframe_workspace         [1][encoder->guts->best_subframe         [1]];
839                                 break;
840                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
841                                 left_subframe  = &encoder->guts->subframe_workspace         [0][encoder->guts->best_subframe         [0]];
842                                 right_subframe = &encoder->guts->subframe_workspace_mid_side[1][encoder->guts->best_subframe_mid_side[1]];
843                                 break;
844                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
845                                 left_subframe  = &encoder->guts->subframe_workspace_mid_side[1][encoder->guts->best_subframe_mid_side[1]];
846                                 right_subframe = &encoder->guts->subframe_workspace         [1][encoder->guts->best_subframe         [1]];
847                                 break;
848                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
849                                 left_subframe  = &encoder->guts->subframe_workspace_mid_side[0][encoder->guts->best_subframe_mid_side[0]];
850                                 right_subframe = &encoder->guts->subframe_workspace_mid_side[1][encoder->guts->best_subframe_mid_side[1]];
851                                 break;
852                         default:
853                                 assert(0);
854                 }
855
856                 switch(channel_assignment) {
857                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
858                                 left_bps  = encoder->guts->subframe_bps         [0];
859                                 right_bps = encoder->guts->subframe_bps         [1];
860                                 break;
861                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
862                                 left_bps  = encoder->guts->subframe_bps         [0];
863                                 right_bps = encoder->guts->subframe_bps_mid_side[1];
864                                 break;
865                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
866                                 left_bps  = encoder->guts->subframe_bps_mid_side[1];
867                                 right_bps = encoder->guts->subframe_bps         [1];
868                                 break;
869                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
870                                 left_bps  = encoder->guts->subframe_bps_mid_side[0];
871                                 right_bps = encoder->guts->subframe_bps_mid_side[1];
872                                 break;
873                         default:
874                                 assert(0);
875                 }
876
877                 /* note that encoder_add_subframe_ sets the state for us in case of an error */
878                 if(!encoder_add_subframe_(encoder, &frame_header, left_bps , left_subframe , &encoder->guts->frame))
879                         return false;
880                 if(!encoder_add_subframe_(encoder, &frame_header, right_bps, right_subframe, &encoder->guts->frame))
881                         return false;
882         }
883         else {
884                 if(!FLAC__frame_add_header(&frame_header, encoder->streamable_subset, is_last_frame, &encoder->guts->frame)) {
885                         encoder->state = FLAC__ENCODER_FRAMING_ERROR;
886                         return false;
887                 }
888
889                 for(channel = 0; channel < encoder->channels; channel++) {
890                         if(!encoder_add_subframe_(encoder, &frame_header, encoder->guts->subframe_bps[channel], &encoder->guts->subframe_workspace[channel][encoder->guts->best_subframe[channel]], &encoder->guts->frame)) {
891                                 /* the above function sets the state for us in case of an error */
892                                 return false;
893                         }
894                 }
895         }
896
897         if(encoder->loose_mid_side_stereo) {
898                 encoder->guts->loose_mid_side_stereo_frame_count++;
899                 if(encoder->guts->loose_mid_side_stereo_frame_count >= encoder->guts->loose_mid_side_stereo_frames)
900                         encoder->guts->loose_mid_side_stereo_frame_count = 0;
901         }
902
903         encoder->guts->last_channel_assignment = frame_header.channel_assignment;
904
905         return true;
906 }
907
908 bool encoder_process_subframe_(FLAC__Encoder *encoder, unsigned max_partition_order, bool verbatim_only, const FLAC__FrameHeader *frame_header, unsigned subframe_bps, const int32 integer_signal[], const real real_signal[], FLAC__Subframe *subframe[2], int32 *residual[2], unsigned *best_subframe, unsigned *best_bits)
909 {
910         real fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
911         real lpc_residual_bits_per_sample;
912         real autoc[FLAC__MAX_LPC_ORDER+1];
913         real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER];
914         real lpc_error[FLAC__MAX_LPC_ORDER];
915         unsigned min_lpc_order, max_lpc_order, lpc_order;
916         unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
917         unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
918         unsigned rice_parameter;
919         unsigned _candidate_bits, _best_bits;
920         unsigned _best_subframe;
921
922         /* verbatim subframe is the baseline against which we measure other compressed subframes */
923         _best_subframe = 0;
924         _best_bits = encoder_evaluate_verbatim_subframe_(integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
925
926         if(!verbatim_only && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
927                 /* check for constant subframe */
928                 if(encoder->guts->use_slow)
929                         guess_fixed_order = FLAC__fixed_compute_best_predictor_slow(integer_signal+FLAC__MAX_FIXED_ORDER, frame_header->blocksize-FLAC__MAX_FIXED_ORDER, fixed_residual_bits_per_sample);
930                 else
931                         guess_fixed_order = FLAC__fixed_compute_best_predictor(integer_signal+FLAC__MAX_FIXED_ORDER, frame_header->blocksize-FLAC__MAX_FIXED_ORDER, fixed_residual_bits_per_sample);
932                 if(fixed_residual_bits_per_sample[1] == 0.0) {
933                         /* the above means integer_signal+FLAC__MAX_FIXED_ORDER is constant, now we just have to check the warmup samples */
934                         unsigned i, signal_is_constant = true;
935                         for(i = 1; i <= FLAC__MAX_FIXED_ORDER; i++) {
936                                 if(integer_signal[0] != integer_signal[i]) {
937                                         signal_is_constant = false;
938                                         break;
939                                 }
940                         }
941                         if(signal_is_constant) {
942                                 _candidate_bits = encoder_evaluate_constant_subframe_(integer_signal[0], subframe_bps, subframe[!_best_subframe]);
943                                 if(_candidate_bits < _best_bits) {
944                                         _best_subframe = !_best_subframe;
945                                         _best_bits = _candidate_bits;
946                                 }
947                         }
948                 }
949                 else {
950                         /* encode fixed */
951                         if(encoder->do_exhaustive_model_search) {
952                                 min_fixed_order = 0;
953                                 max_fixed_order = FLAC__MAX_FIXED_ORDER;
954                         }
955                         else {
956                                 min_fixed_order = max_fixed_order = guess_fixed_order;
957                         }
958                         for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
959                                 if(fixed_residual_bits_per_sample[fixed_order] >= (real)subframe_bps)
960                                         continue; /* don't even try */
961                                 rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > 0.0)? (unsigned)(fixed_residual_bits_per_sample[fixed_order]+0.5) : 0; /* 0.5 is for rounding */
962 #ifndef SYMMETRIC_RICE
963                                 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
964 #endif
965                                 if(rice_parameter >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN))
966                                         rice_parameter = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN) - 1;
967                                 _candidate_bits = encoder_evaluate_fixed_subframe_(integer_signal, residual[!_best_subframe], encoder->guts->abs_residual, encoder->guts->abs_residual_partition_sums, encoder->guts->raw_bits_per_partition, frame_header->blocksize, subframe_bps, fixed_order, rice_parameter, max_partition_order, subframe[!_best_subframe]);
968                                 if(_candidate_bits < _best_bits) {
969                                         _best_subframe = !_best_subframe;
970                                         _best_bits = _candidate_bits;
971                                 }
972                         }
973
974                         /* encode lpc */
975                         if(encoder->max_lpc_order > 0) {
976                                 if(encoder->max_lpc_order >= frame_header->blocksize)
977                                         max_lpc_order = frame_header->blocksize-1;
978                                 else
979                                         max_lpc_order = encoder->max_lpc_order;
980                                 if(max_lpc_order > 0) {
981                                         FLAC__lpc_compute_autocorrelation(real_signal, frame_header->blocksize, max_lpc_order+1, autoc);
982                                         /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
983                                         if(autoc[0] != 0.0) {
984                                                 FLAC__lpc_compute_lp_coefficients(autoc, max_lpc_order, lp_coeff, lpc_error);
985                                                 if(encoder->do_exhaustive_model_search) {
986                                                         min_lpc_order = 1;
987                                                 }
988                                                 else {
989                                                         unsigned guess_lpc_order = FLAC__lpc_compute_best_order(lpc_error, max_lpc_order, frame_header->blocksize, subframe_bps);
990                                                         min_lpc_order = max_lpc_order = guess_lpc_order;
991                                                 }
992                                                 if(encoder->do_qlp_coeff_prec_search) {
993                                                         min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
994                                                         max_qlp_coeff_precision = min(32 - subframe_bps - 1, (1u<<FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN)-1);
995                                                 }
996                                                 else {
997                                                         min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->qlp_coeff_precision;
998                                                 }
999                                                 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
1000                                                         lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
1001                                                         if(lpc_residual_bits_per_sample >= (real)subframe_bps)
1002                                                                 continue; /* don't even try */
1003                                                         rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
1004 #ifndef SYMMETRIC_RICE
1005                                                         rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
1006 #endif
1007                                                         if(rice_parameter >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN))
1008                                                                 rice_parameter = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN) - 1;
1009                                                         for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
1010                                                                 _candidate_bits = encoder_evaluate_lpc_subframe_(integer_signal, residual[!_best_subframe], encoder->guts->abs_residual, encoder->guts->abs_residual_partition_sums, encoder->guts->raw_bits_per_partition, lp_coeff[lpc_order-1], frame_header->blocksize, subframe_bps, lpc_order, qlp_coeff_precision, rice_parameter, max_partition_order, subframe[!_best_subframe]);
1011                                                                 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
1012                                                                         if(_candidate_bits < _best_bits) {
1013                                                                                 _best_subframe = !_best_subframe;
1014                                                                                 _best_bits = _candidate_bits;
1015                                                                         }
1016                                                                 }
1017                                                         }
1018                                                 }
1019                                         }
1020                                 }
1021                         }
1022                 }
1023         }
1024
1025         *best_subframe = _best_subframe;
1026         *best_bits = _best_bits;
1027
1028         return true;
1029 }
1030
1031 bool encoder_add_subframe_(FLAC__Encoder *encoder, const FLAC__FrameHeader *frame_header, unsigned subframe_bps, const FLAC__Subframe *subframe, FLAC__BitBuffer *frame)
1032 {
1033         switch(subframe->type) {
1034                 case FLAC__SUBFRAME_TYPE_CONSTANT:
1035                         if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
1036                                 encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING;
1037                                 return false;
1038                         }
1039                         break;
1040                 case FLAC__SUBFRAME_TYPE_FIXED:
1041                         if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), frame_header->blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
1042                                 encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING;
1043                                 return false;
1044                         }
1045                         break;
1046                 case FLAC__SUBFRAME_TYPE_LPC:
1047                         if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), frame_header->blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
1048                                 encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING;
1049                                 return false;
1050                         }
1051                         break;
1052                 case FLAC__SUBFRAME_TYPE_VERBATIM:
1053                         if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), frame_header->blocksize, subframe_bps, subframe->wasted_bits, frame)) {
1054                                 encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING;
1055                                 return false;
1056                         }
1057                         break;
1058                 default:
1059                         assert(0);
1060         }
1061
1062         return true;
1063 }
1064
1065 unsigned encoder_evaluate_constant_subframe_(const int32 signal, unsigned subframe_bps, FLAC__Subframe *subframe)
1066 {
1067         subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
1068         subframe->data.constant.value = signal;
1069
1070         return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe_bps;
1071 }
1072
1073 unsigned encoder_evaluate_fixed_subframe_(const int32 signal[], int32 residual[], uint32 abs_residual[], uint32 abs_residual_partition_sums[], unsigned raw_bits_per_partition[], unsigned blocksize, unsigned subframe_bps, unsigned order, unsigned rice_parameter, unsigned max_partition_order, FLAC__Subframe *subframe)
1074 {
1075         unsigned i, residual_bits;
1076         const unsigned residual_samples = blocksize - order;
1077
1078         FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
1079
1080         subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
1081
1082         subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
1083         subframe->data.fixed.residual = residual;
1084
1085         residual_bits = encoder_find_best_partition_order_(residual, abs_residual, abs_residual_partition_sums, raw_bits_per_partition, residual_samples, order, rice_parameter, max_partition_order, &subframe->data.fixed.entropy_coding_method.data.partitioned_rice.order, subframe->data.fixed.entropy_coding_method.data.partitioned_rice.parameters, subframe->data.fixed.entropy_coding_method.data.partitioned_rice.raw_bits);
1086
1087         subframe->data.fixed.order = order;
1088         for(i = 0; i < order; i++)
1089                 subframe->data.fixed.warmup[i] = signal[i];
1090
1091         return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (order * subframe_bps) + residual_bits;
1092 }
1093
1094 unsigned encoder_evaluate_lpc_subframe_(const int32 signal[], int32 residual[], uint32 abs_residual[], uint32 abs_residual_partition_sums[], unsigned raw_bits_per_partition[], const real lp_coeff[], unsigned blocksize, unsigned subframe_bps, unsigned order, unsigned qlp_coeff_precision, unsigned rice_parameter, unsigned max_partition_order, FLAC__Subframe *subframe)
1095 {
1096         int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
1097         unsigned i, residual_bits;
1098         int quantization, ret;
1099         const unsigned residual_samples = blocksize - order;
1100
1101         ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, subframe_bps, qlp_coeff, &quantization);
1102         if(ret != 0)
1103                 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
1104
1105         FLAC__lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
1106
1107         subframe->type = FLAC__SUBFRAME_TYPE_LPC;
1108
1109         subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
1110         subframe->data.lpc.residual = residual;
1111
1112         residual_bits = encoder_find_best_partition_order_(residual, abs_residual, abs_residual_partition_sums, raw_bits_per_partition, residual_samples, order, rice_parameter, max_partition_order, &subframe->data.lpc.entropy_coding_method.data.partitioned_rice.order, subframe->data.lpc.entropy_coding_method.data.partitioned_rice.parameters, subframe->data.lpc.entropy_coding_method.data.partitioned_rice.raw_bits);
1113
1114         subframe->data.lpc.order = order;
1115         subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
1116         subframe->data.lpc.quantization_level = quantization;
1117         memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(int32)*FLAC__MAX_LPC_ORDER);
1118         for(i = 0; i < order; i++)
1119                 subframe->data.lpc.warmup[i] = signal[i];
1120
1121         return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits;
1122 }
1123
1124 unsigned encoder_evaluate_verbatim_subframe_(const int32 signal[], unsigned blocksize, unsigned subframe_bps, FLAC__Subframe *subframe)
1125 {
1126         subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
1127
1128         subframe->data.verbatim.data = signal;
1129
1130         return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (blocksize * subframe_bps);
1131 }
1132
1133 unsigned encoder_find_best_partition_order_(const int32 residual[], uint32 abs_residual[], uint32 abs_residual_partition_sums[], unsigned raw_bits_per_partition[], unsigned residual_samples, unsigned predictor_order, unsigned rice_parameter, unsigned max_partition_order, unsigned *best_partition_order, unsigned best_parameters[], unsigned best_raw_bits[])
1134 {
1135         int32 r;
1136 #if (defined PRECOMPUTE_PARTITION_SUMS) || (defined SEARCH_FOR_ESCAPES)
1137         unsigned sum;
1138         int partition_order;
1139 #else
1140         unsigned partition_order;
1141 #endif
1142         unsigned residual_bits, best_residual_bits = 0;
1143         unsigned residual_sample;
1144         unsigned best_parameters_index = 0, parameters[2][1 << FLAC__MAX_RICE_PARTITION_ORDER], raw_bits[2][1 << FLAC__MAX_RICE_PARTITION_ORDER];
1145
1146         /* compute abs(residual) for use later */
1147         for(residual_sample = 0; residual_sample < residual_samples; residual_sample++) {
1148                 r = residual[residual_sample];
1149                 abs_residual[residual_sample] = (uint32)(r<0? -r : r);
1150         }
1151
1152 #if (defined PRECOMPUTE_PARTITION_SUMS) || (defined SEARCH_FOR_ESCAPES)
1153         max_partition_order = encoder_precompute_partition_info_(residual, abs_residual, abs_residual_partition_sums, raw_bits_per_partition, residual_samples, predictor_order, max_partition_order);
1154
1155         for(partition_order = (int)max_partition_order, sum = 0; partition_order >= 0; partition_order--) {
1156                 if(!encoder_set_partitioned_rice_(abs_residual, abs_residual_partition_sums+sum, raw_bits_per_partition+sum, residual_samples, predictor_order, rice_parameter, (unsigned)partition_order, parameters[!best_parameters_index], raw_bits[!best_parameters_index], &residual_bits)) {
1157                         assert(0); /* encoder_precompute_partition_info_ should keep this from ever happening */
1158                 }
1159                 sum += 1u << partition_order;
1160                 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
1161                         best_residual_bits = residual_bits;
1162                         *best_partition_order = partition_order;
1163                         best_parameters_index = !best_parameters_index;
1164                 }
1165         }
1166 #else
1167         for(partition_order = 0; partition_order <= max_partition_order; partition_order++) {
1168                 if(!encoder_set_partitioned_rice_(abs_residual, 0, 0, residual_samples, predictor_order, rice_parameter, partition_order, parameters[!best_parameters_index], raw_bits[!best_parameters_index], &residual_bits)) {
1169                         assert(best_residual_bits != 0);
1170                         break;
1171                 }
1172                 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
1173                         best_residual_bits = residual_bits;
1174                         *best_partition_order = partition_order;
1175                         best_parameters_index = !best_parameters_index;
1176                 }
1177         }
1178 #endif
1179         memcpy(best_parameters, parameters[best_parameters_index], sizeof(unsigned)*(1<<(*best_partition_order)));
1180         memcpy(best_raw_bits, raw_bits[best_parameters_index], sizeof(unsigned)*(1<<(*best_partition_order)));
1181
1182         return best_residual_bits;
1183 }
1184
1185 #if (defined PRECOMPUTE_PARTITION_SUMS) || (defined SEARCH_FOR_ESCAPES)
1186 unsigned encoder_precompute_partition_info_(const int32 residual[], uint32 abs_residual[], uint32 abs_residual_partition_sums[], unsigned raw_bits_per_partition[], unsigned residual_samples, unsigned predictor_order, unsigned max_partition_order)
1187 {
1188         int partition_order;
1189         unsigned from_partition, to_partition = 0;
1190         const unsigned blocksize = residual_samples + predictor_order;
1191
1192         /* first do max_partition_order */
1193         for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
1194 #ifdef PRECOMPUTE_PARTITION_SUMS
1195                 uint32 abs_residual_partition_sum;
1196 #endif
1197 #ifdef SEARCH_FOR_ESCAPES
1198                 uint32 abs_residual_partition_max;
1199                 unsigned abs_residual_partition_max_index = 0; /* initialized to silence superfluous compiler warning */
1200 #endif
1201                 uint32 abs_r;
1202                 unsigned partition, partition_sample, partition_samples, residual_sample;
1203                 const unsigned partitions = 1u << partition_order;
1204                 const unsigned default_partition_samples = blocksize >> partition_order;
1205
1206                 if(default_partition_samples <= predictor_order) {
1207                         assert(max_partition_order > 0);
1208                         max_partition_order--;
1209                 }
1210                 else {
1211                         for(partition = residual_sample = 0; partition < partitions; partition++) {
1212                                 partition_samples = default_partition_samples;
1213                                 if(partition == 0)
1214                                         partition_samples -= predictor_order;
1215 #ifdef PRECOMPUTE_PARTITION_SUMS
1216                                 abs_residual_partition_sum = 0;
1217 #endif
1218 #ifdef SEARCH_FOR_ESCAPES
1219                                 abs_residual_partition_max = 0;
1220 #endif
1221                                 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
1222                                         abs_r = abs_residual[residual_sample];
1223 #ifdef PRECOMPUTE_PARTITION_SUMS
1224                                         abs_residual_partition_sum += abs_r; /* @@@ this can overflow with small max_partition_order and (large blocksizes or bits-per-sample), FIX! */
1225 #endif
1226 #ifdef SEARCH_FOR_ESCAPES
1227                                         if(abs_r > abs_residual_partition_max) {
1228                                                 abs_residual_partition_max = abs_r;
1229                                                 abs_residual_partition_max_index = residual_sample;
1230                                         }
1231 #endif
1232                                         residual_sample++;
1233                                 }
1234 #ifdef PRECOMPUTE_PARTITION_SUMS
1235                                 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
1236 #endif
1237 #ifdef SEARCH_FOR_ESCAPES
1238                                 if(abs_residual_partition_max > 0)
1239                                         raw_bits_per_partition[partition] = FLAC__bitmath_silog2(residual[abs_residual_partition_max_index]);
1240                                 else
1241                                         raw_bits_per_partition[partition] = FLAC__bitmath_silog2(0);
1242 #endif
1243                         }
1244                         to_partition = partitions;
1245                         break;
1246                 }
1247         }
1248
1249         /* now merge for lower orders */
1250         for(from_partition = 0; partition_order >= 0; partition_order--) {
1251 #ifdef PRECOMPUTE_PARTITION_SUMS
1252                 uint32 s;
1253 #endif
1254 #ifdef SEARCH_FOR_ESCAPES
1255                 unsigned m;
1256 #endif
1257                 unsigned i;
1258                 const unsigned partitions = 1u << partition_order;
1259                 for(i = 0; i < partitions; i++) {
1260 #ifdef PRECOMPUTE_PARTITION_SUMS
1261                         s = abs_residual_partition_sums[from_partition];
1262 #endif
1263 #ifdef SEARCH_FOR_ESCAPES
1264                         m = raw_bits_per_partition[from_partition];
1265 #endif
1266                         from_partition++;
1267 #ifdef PRECOMPUTE_PARTITION_SUMS
1268                         abs_residual_partition_sums[to_partition] = s + abs_residual_partition_sums[from_partition];
1269 #endif
1270 #ifdef SEARCH_FOR_ESCAPES
1271                         raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
1272 #endif
1273                         from_partition++;
1274                         to_partition++;
1275                 }
1276         }
1277
1278         return max_partition_order;
1279 }
1280 #endif
1281
1282 #ifdef VARIABLE_RICE_BITS
1283 #undef VARIABLE_RICE_BITS
1284 #endif
1285 #define VARIABLE_RICE_BITS(value, parameter) ((value) >> (parameter))
1286
1287 bool encoder_set_partitioned_rice_(const uint32 abs_residual[], const uint32 abs_residual_partition_sums[], const unsigned raw_bits_per_partition[], const unsigned residual_samples, const unsigned predictor_order, unsigned rice_parameter, const unsigned partition_order, unsigned parameters[], unsigned raw_bits[], unsigned *bits)
1288 {
1289         unsigned partition_bits;
1290 #ifdef SEARCH_FOR_ESCAPES
1291         unsigned flat_bits;
1292 #endif
1293         unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
1294
1295         if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER)
1296                 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1297
1298         if(partition_order == 0) {
1299                 unsigned i;
1300
1301                 partition_bits = 0;
1302
1303                 {
1304 #ifdef VARIABLE_RICE_BITS
1305 #ifdef SYMMETRIC_RICE
1306                         partition_bits += (2+rice_parameter) * residual_samples;
1307 #else
1308                         const unsigned rice_parameter_estimate = rice_parameter-1;
1309                         partition_bits += (1+rice_parameter) * residual_samples;
1310 #endif
1311 #endif
1312                         parameters[0] = rice_parameter;
1313                         partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
1314                         for(i = 0; i < residual_samples; i++) {
1315 #ifdef VARIABLE_RICE_BITS
1316 #ifdef SYMMETRIC_RICE
1317                                 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter);
1318 #else
1319                                 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter_estimate);
1320 #endif
1321 #else
1322                                 partition_bits += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
1323 #endif
1324                         }
1325 #ifdef SEARCH_FOR_ESCAPES
1326                         flat_bits = raw_bits_per_partition[0] * residual_samples;
1327                         if(flat_bits < partition_bits) {
1328                                 parameters[0] = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
1329                                 raw_bits[0] = raw_bits_per_partition[0];
1330                                 partition_bits = flat_bits;
1331                         }
1332 #endif
1333                         bits_ += partition_bits;
1334                 }
1335         }
1336         else {
1337                 unsigned i, j, k;
1338                 unsigned mean, parameter, partition_samples;
1339                 const unsigned max_parameter = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN) - 1;
1340                 const unsigned partitions = 1u << partition_order;
1341                 for(i = j = 0; i < partitions; i++) {
1342                         partition_bits = 0;
1343                         partition_samples = (residual_samples+predictor_order) >> partition_order;
1344                         if(i == 0) {
1345                                 if(partition_samples <= predictor_order)
1346                                         return false;
1347                                 else
1348                                         partition_samples -= predictor_order;
1349                         }
1350                         mean = partition_samples >> 1;
1351 #ifdef PRECOMPUTE_PARTITION_SUMS
1352                         mean += abs_residual_partition_sums[i];
1353 #else
1354                         for(k = 0; k < partition_samples; j++, k++)
1355                                 mean += abs_residual[j];
1356                         j -= k;
1357 #endif
1358                         mean /= partition_samples;
1359 #ifdef SYMMETRIC_RICE
1360                         /* calc parameter = floor(log2(mean)) */
1361                         parameter = 0;
1362 mean>>=1;
1363                         while(mean) {
1364                                 parameter++;
1365                                 mean >>= 1;
1366                         }
1367 #else
1368                         /* calc parameter = floor(log2(mean)) + 1 */
1369                         parameter = 0;
1370                         while(mean) {
1371                                 parameter++;
1372                                 mean >>= 1;
1373                         }
1374 #endif
1375                         if(parameter > max_parameter)
1376                                 parameter = max_parameter;
1377                         if(parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER)
1378                                 parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1379                         parameters[i] = parameter;
1380                         partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
1381 #ifdef VARIABLE_RICE_BITS
1382 #ifdef SYMMETRIC_RICE
1383                         partition_bits += (2+parameter) * partition_samples;
1384 #else
1385                         partition_bits += (1+parameter) * partition_samples;
1386                         --parameter;
1387 #endif
1388 #endif
1389                         for(k = 0; k < partition_samples; j++, k++) {
1390 #ifdef VARIABLE_RICE_BITS
1391 #ifdef SYMMETRIC_RICE
1392                                 partition_bits += VARIABLE_RICE_BITS(abs_residual[j], parameter);
1393 #else
1394                                 partition_bits += VARIABLE_RICE_BITS(abs_residual[j], parameter);
1395 #endif
1396 #else
1397                                 partition_bits += FLAC__bitbuffer_rice_bits(residual[j], parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
1398 #endif
1399                         }
1400 #ifdef SEARCH_FOR_ESCAPES
1401                         flat_bits = raw_bits_per_partition[i] * partition_samples;
1402                         if(flat_bits < partition_bits) {
1403                                 parameters[i] = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
1404                                 raw_bits[i] = raw_bits_per_partition[i];
1405                                 partition_bits = flat_bits;
1406                         }
1407 #endif
1408                         bits_ += partition_bits;
1409                 }
1410         }
1411
1412         *bits = bits_;
1413         return true;
1414 }
1415
1416 static unsigned encoder_get_wasted_bits_(int32 signal[], unsigned samples)
1417 {
1418         unsigned i, shift;
1419         int32 x = 0;
1420
1421         for(i = 0; i < samples && !(x&1); i++)
1422                 x |= signal[i];
1423
1424         if(x == 0) {
1425                 shift = 0;
1426         }
1427         else {
1428                 for(shift = 0; !(x&1); shift++)
1429                         x >>= 1;
1430         }
1431
1432         if(shift > 0) {
1433                 for(i = 0; i < samples; i++)
1434                          signal[i] >>= shift;
1435         }
1436
1437         return shift;
1438 }