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