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