change to support new sign-folded rice coding
[flac.git] / src / libFLAC / encoder.c
1 /* libFLAC - Free Lossless Audio Coder library
2  * Copyright (C) 2000  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/encoder_framing.h"
27 #include "private/fixed.h"
28 #include "private/lpc.h"
29
30 #ifdef min
31 #undef min
32 #endif
33 #define min(x,y) ((x)<(y)?(x):(y))
34
35 #ifdef max
36 #undef max
37 #endif
38 #define max(x,y) ((x)>(y)?(x):(y))
39
40 typedef struct FLAC__EncoderPrivate {
41         unsigned input_capacity;                    /* current size (in samples) of the signal and residual buffers */
42         int32 *integer_signal[FLAC__MAX_CHANNELS];  /* the integer version of the input signal */
43         int32 *integer_signal_mid_side[2];          /* the integer version of the mid-side input signal (stereo only) */
44         real *real_signal[FLAC__MAX_CHANNELS];      /* the floating-point version of the input signal */
45         real *real_signal_mid_side[2];              /* the floating-point version of the mid-side input signal (stereo only) */
46         int32 *residual[2];                         /* where the candidate and best subframe residual signals will be stored */
47         unsigned best_residual;                     /* index into the above */
48         FLAC__BitBuffer frame;                      /* the current frame being worked on */
49         FLAC__BitBuffer frame_mid_side;             /* special parallel workspace for the mid-side coded version of the current frame */
50         FLAC__BitBuffer frame_left_side;            /* special parallel workspace for the left-side coded version of the current frame */
51         FLAC__BitBuffer frame_right_side;           /* special parallel workspace for the right-side coded version of the current frame */
52         FLAC__SubframeHeader best_subframe, candidate_subframe;
53         bool current_frame_can_do_mid_side;         /* encoder sets this false when any given sample of a frame's side channel exceeds 16 bits */
54         FLAC__StreamMetaData metadata;
55         unsigned current_sample_number;
56         unsigned current_frame_number;
57         FLAC__EncoderWriteStatus (*write_callback)(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
58         void (*metadata_callback)(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data);
59         void *client_data;
60 } FLAC__EncoderPrivate;
61
62 static bool encoder_resize_buffers_(FLAC__Encoder *encoder, unsigned new_size);
63 static bool encoder_process_frame_(FLAC__Encoder *encoder, bool is_last_frame);
64 static bool encoder_process_subframes_(FLAC__Encoder *encoder, bool is_last_frame, const FLAC__FrameHeader *frame_header, unsigned channels, const int32 *integer_signal[], const real *real_signal[], FLAC__BitBuffer *bitbuffer);
65 static unsigned encoder_evaluate_constant_subframe_(const int32 signal, unsigned bits_per_sample, FLAC__SubframeHeader *subframe);
66 static unsigned encoder_evaluate_fixed_subframe_(const int32 signal[], int32 residual[], unsigned blocksize, unsigned bits_per_sample, unsigned order, unsigned rice_parameter, unsigned max_partition_order, FLAC__SubframeHeader *subframe);
67 static unsigned encoder_evaluate_lpc_subframe_(const int32 signal[], int32 residual[], const real lp_coeff[], unsigned blocksize, unsigned bits_per_sample, unsigned order, unsigned qlp_coeff_precision, unsigned rice_parameter, unsigned max_partition_order, FLAC__SubframeHeader *subframe);
68 static unsigned encoder_evaluate_verbatim_subframe_(unsigned blocksize, unsigned bits_per_sample, FLAC__SubframeHeader *subframe);
69 static unsigned encoder_find_best_partition_order_(int32 residual[], unsigned residual_samples, unsigned predictor_order, unsigned rice_parameter, unsigned max_partition_order, unsigned *best_partition_order, unsigned best_parameters[]);
70 static bool encoder_generate_constant_subframe_(const FLAC__SubframeHeader *header, unsigned bits_per_sample, FLAC__BitBuffer *bitbuffer);
71 static bool encoder_generate_fixed_subframe_(const FLAC__SubframeHeader *header, int32 residual[], unsigned blocksize, unsigned bits_per_sample, FLAC__BitBuffer *bitbuffer);
72 static bool encoder_generate_lpc_subframe_(const FLAC__SubframeHeader *header, int32 residual[], unsigned blocksize, unsigned bits_per_sample, FLAC__BitBuffer *bitbuffer);
73 static bool encoder_generate_verbatim_subframe_(const FLAC__SubframeHeader *header, const int32 signal[], unsigned blocksize, unsigned bits_per_sample, FLAC__BitBuffer *bitbuffer);
74 static void encoder_promote_candidate_subframe_(FLAC__Encoder *encoder);
75 static bool encoder_set_partitioned_rice_(const int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameter, const unsigned partition_order, unsigned parameters[], unsigned *bits);
76
77 const char *FLAC__EncoderWriteStatusString[] = {
78         "FLAC__ENCODER_WRITE_OK",
79         "FLAC__ENCODER_WRITE_FATAL_ERROR"
80 };
81
82 const char *FLAC__EncoderStateString[] = {
83         "FLAC__ENCODER_OK",
84         "FLAC__ENCODER_UNINITIALIZED",
85         "FLAC__ENCODER_INVALID_NUMBER_OF_CHANNELS",
86         "FLAC__ENCODER_INVALID_BITS_PER_SAMPLE",
87         "FLAC__ENCODER_INVALID_SAMPLE_RATE",
88         "FLAC__ENCODER_INVALID_BLOCK_SIZE",
89         "FLAC__ENCODER_INVALID_QLP_COEFF_PRECISION",
90         "FLAC__ENCODER_MID_SIDE_CHANNELS_MISMATCH",
91         "FLAC__ENCODER_MID_SIDE_SAMPLE_SIZE_MISMATCH",
92         "FLAC__ENCODER_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
93         "FLAC__ENCODER_NOT_STREAMABLE",
94         "FLAC__ENCODER_FRAMING_ERROR",
95         "FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING",
96         "FLAC__ENCODER_FATAL_ERROR_WHILE_WRITING",
97         "FLAC__ENCODER_MEMORY_ALLOCATION_ERROR"
98 };
99
100
101 bool encoder_resize_buffers_(FLAC__Encoder *encoder, unsigned new_size)
102 {
103         bool ok;
104         unsigned i;
105         int32 *previous_is, *current_is;
106         real *previous_rs, *current_rs;
107         int32 *residual;
108
109         assert(new_size > 0);
110         assert(encoder->state == FLAC__ENCODER_OK);
111         assert(encoder->guts->current_sample_number == 0);
112
113         /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
114         if(new_size <= encoder->guts->input_capacity)
115                 return true;
116
117         ok = 1;
118         if(ok) {
119                 for(i = 0; ok && i < encoder->channels; i++) {
120                         /* integer version of the signal */
121                         previous_is = encoder->guts->integer_signal[i];
122                         current_is = (int32*)malloc(sizeof(int32) * new_size);
123                         if(0 == current_is) {
124                                 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
125                                 ok = 0;
126                         }
127                         else {
128                                 encoder->guts->integer_signal[i] = current_is;
129                                 if(previous_is != 0)
130                                         free(previous_is);
131                         }
132                         /* real version of the signal */
133                         previous_rs = encoder->guts->real_signal[i];
134                         current_rs = (real*)malloc(sizeof(real) * new_size);
135                         if(0 == current_rs) {
136                                 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
137                                 ok = 0;
138                         }
139                         else {
140                                 encoder->guts->real_signal[i] = current_rs;
141                                 if(previous_rs != 0)
142                                         free(previous_rs);
143                         }
144                 }
145         }
146         if(ok) {
147                 for(i = 0; ok && i < 2; i++) {
148                         /* integer version of the signal */
149                         previous_is = encoder->guts->integer_signal_mid_side[i];
150                         current_is = (int32*)malloc(sizeof(int32) * new_size);
151                         if(0 == current_is) {
152                                 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
153                                 ok = 0;
154                         }
155                         else {
156                                 encoder->guts->integer_signal_mid_side[i] = current_is;
157                                 if(previous_is != 0)
158                                         free(previous_is);
159                         }
160                         /* real version of the signal */
161                         previous_rs = encoder->guts->real_signal_mid_side[i];
162                         current_rs = (real*)malloc(sizeof(real) * new_size);
163                         if(0 == current_rs) {
164                                 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
165                                 ok = 0;
166                         }
167                         else {
168                                 encoder->guts->real_signal_mid_side[i] = current_rs;
169                                 if(previous_rs != 0)
170                                         free(previous_rs);
171                         }
172                 }
173         }
174         if(ok) {
175                 for(i = 0; i < 2; i++) {
176                         residual = (int32*)malloc(sizeof(int32) * new_size);
177                         if(0 == residual) {
178                                 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
179                                 ok = 0;
180                         }
181                         else {
182                                 if(encoder->guts->residual[i] != 0)
183                                         free(encoder->guts->residual[i]);
184                                 encoder->guts->residual[i] = residual;
185                         }
186                 }
187         }
188         if(ok)
189                 encoder->guts->input_capacity = new_size;
190
191         return ok;
192 }
193
194 FLAC__Encoder *FLAC__encoder_get_new_instance()
195 {
196         FLAC__Encoder *encoder = (FLAC__Encoder*)malloc(sizeof(FLAC__Encoder));
197         if(encoder != 0) {
198                 encoder->state = FLAC__ENCODER_UNINITIALIZED;
199                 encoder->guts = 0;
200         }
201         return encoder;
202 }
203
204 void FLAC__encoder_free_instance(FLAC__Encoder *encoder)
205 {
206         assert(encoder != 0);
207         free(encoder);
208 }
209
210 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)
211 {
212         unsigned i;
213
214         assert(sizeof(int) >= 4); /* we want to die right away if this is not true */
215         assert(encoder != 0);
216         assert(write_callback != 0);
217         assert(metadata_callback != 0);
218         assert(encoder->state == FLAC__ENCODER_UNINITIALIZED);
219         assert(encoder->guts == 0);
220
221         encoder->state = FLAC__ENCODER_OK;
222
223         if(encoder->channels == 0 || encoder->channels > FLAC__MAX_CHANNELS)
224                 return encoder->state = FLAC__ENCODER_INVALID_NUMBER_OF_CHANNELS;
225
226         if(encoder->do_mid_side_stereo && encoder->channels != 2)
227                 return encoder->state = FLAC__ENCODER_MID_SIDE_CHANNELS_MISMATCH;
228
229         if(encoder->do_mid_side_stereo && encoder->bits_per_sample > 16)
230                 return encoder->state = FLAC__ENCODER_MID_SIDE_SAMPLE_SIZE_MISMATCH;
231
232         if(encoder->bits_per_sample == 0 || encoder->bits_per_sample > FLAC__MAX_BITS_PER_SAMPLE)
233                 return encoder->state = FLAC__ENCODER_INVALID_BITS_PER_SAMPLE;
234
235         if(encoder->sample_rate == 0 || encoder->sample_rate > FLAC__MAX_SAMPLE_RATE)
236                 return encoder->state = FLAC__ENCODER_INVALID_SAMPLE_RATE;
237
238         if(encoder->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->blocksize > FLAC__MAX_BLOCK_SIZE)
239                 return encoder->state = FLAC__ENCODER_INVALID_BLOCK_SIZE;
240
241         if(encoder->blocksize < encoder->max_lpc_order)
242                 return encoder->state = FLAC__ENCODER_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
243
244         if(encoder->qlp_coeff_precision == 0) {
245                 if(encoder->bits_per_sample < 16) {
246                         /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
247                         /* @@@ until then we'll make a guess */
248                         encoder->qlp_coeff_precision = max(5, 2 + encoder->bits_per_sample / 2);
249                 }
250                 else if(encoder->bits_per_sample == 16) {
251                         if(encoder->blocksize <= 192)
252                                 encoder->qlp_coeff_precision = 7;
253                         else if(encoder->blocksize <= 384)
254                                 encoder->qlp_coeff_precision = 8;
255                         else if(encoder->blocksize <= 576)
256                                 encoder->qlp_coeff_precision = 9;
257                         else if(encoder->blocksize <= 1152)
258                                 encoder->qlp_coeff_precision = 10;
259                         else if(encoder->blocksize <= 2304)
260                                 encoder->qlp_coeff_precision = 11;
261                         else if(encoder->blocksize <= 4608)
262                                 encoder->qlp_coeff_precision = 12;
263                         else
264                                 encoder->qlp_coeff_precision = 13;
265                 }
266                 else {
267                         encoder->qlp_coeff_precision = min(13, 8*sizeof(int32) - encoder->bits_per_sample - 1);
268                 }
269         }
270         else if(encoder->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->qlp_coeff_precision + encoder->bits_per_sample >= 8*sizeof(uint32))
271                 return encoder->state = FLAC__ENCODER_INVALID_QLP_COEFF_PRECISION;
272
273         if(encoder->streamable_subset) {
274                 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)
275                         return encoder->state = FLAC__ENCODER_NOT_STREAMABLE;
276                 if(encoder->sample_rate > 655350)
277                         return encoder->state = FLAC__ENCODER_NOT_STREAMABLE;
278         }
279
280         if(encoder->rice_optimization_level >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
281                 encoder->rice_optimization_level = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
282
283         encoder->guts = (FLAC__EncoderPrivate*)malloc(sizeof(FLAC__EncoderPrivate));
284         if(encoder->guts == 0)
285                 return encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
286
287         encoder->guts->input_capacity = 0;
288         for(i = 0; i < encoder->channels; i++) {
289                 encoder->guts->integer_signal[i] = 0;
290                 encoder->guts->real_signal[i] = 0;
291         }
292         for(i = 0; i < 2; i++) {
293                 encoder->guts->integer_signal_mid_side[i] = 0;
294                 encoder->guts->real_signal_mid_side[i] = 0;
295         }
296         encoder->guts->residual[0] = 0;
297         encoder->guts->residual[1] = 0;
298         encoder->guts->best_residual = 0;
299         encoder->guts->current_frame_can_do_mid_side = true;
300         encoder->guts->current_sample_number = 0;
301         encoder->guts->current_frame_number = 0;
302
303         if(!encoder_resize_buffers_(encoder, encoder->blocksize)) {
304                 /* the above function sets the state for us in case of an error */
305                 return encoder->state;
306         }
307         FLAC__bitbuffer_init(&encoder->guts->frame);
308         encoder->guts->write_callback = write_callback;
309         encoder->guts->metadata_callback = metadata_callback;
310         encoder->guts->client_data = client_data;
311
312         /*
313          * write the stream header
314          */
315         if(!FLAC__bitbuffer_clear(&encoder->guts->frame))
316                 return encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
317
318         if(!FLAC__bitbuffer_write_raw_uint32(&encoder->guts->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN))
319                 return encoder->state = FLAC__ENCODER_FRAMING_ERROR;
320
321         encoder->guts->metadata.type = FLAC__METADATA_TYPE_ENCODING;
322         encoder->guts->metadata.is_last = true;
323         encoder->guts->metadata.length = FLAC__STREAM_METADATA_ENCODING_LENGTH;
324         encoder->guts->metadata.data.encoding.min_blocksize = encoder->blocksize; /* this encoder uses the same blocksize for the whole stream */
325         encoder->guts->metadata.data.encoding.max_blocksize = encoder->blocksize;
326         encoder->guts->metadata.data.encoding.min_framesize = 0; /* we don't know this yet; have to fill it in later */
327         encoder->guts->metadata.data.encoding.max_framesize = 0; /* we don't know this yet; have to fill it in later */
328         encoder->guts->metadata.data.encoding.sample_rate = encoder->sample_rate;
329         encoder->guts->metadata.data.encoding.channels = encoder->channels;
330         encoder->guts->metadata.data.encoding.bits_per_sample = encoder->bits_per_sample;
331         encoder->guts->metadata.data.encoding.total_samples = 0; /* we don't know this yet; have to fill it in later */
332         if(!FLAC__add_metadata_block(&encoder->guts->metadata, &encoder->guts->frame))
333                 return encoder->state = FLAC__ENCODER_FRAMING_ERROR;
334
335         assert(encoder->guts->frame.bits == 0); /* assert that we're byte-aligned before writing */
336         assert(encoder->guts->frame.total_consumed_bits == 0); /* assert that no reading of the buffer was done */
337         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)
338                 return encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_WRITING;
339
340         /* now that the metadata block is written, we can init this to an absurdly-high value */
341         encoder->guts->metadata.data.encoding.min_framesize = (1u << FLAC__STREAM_METADATA_ENCODING_MIN_FRAME_SIZE_LEN) - 1;
342
343         return encoder->state;
344 }
345
346 void FLAC__encoder_finish(FLAC__Encoder *encoder)
347 {
348         unsigned i;
349
350         assert(encoder != 0);
351         if(encoder->state == FLAC__ENCODER_UNINITIALIZED)
352                 return;
353         if(encoder->guts->current_sample_number != 0) {
354                 encoder->blocksize = encoder->guts->current_sample_number;
355                 encoder_process_frame_(encoder, true); /* true => is last frame */
356         }
357         encoder->guts->metadata_callback(encoder, &encoder->guts->metadata, encoder->guts->client_data);
358         if(encoder->guts != 0) {
359                 for(i = 0; i < encoder->channels; i++) {
360                         if(encoder->guts->integer_signal[i] != 0) {
361                                 free(encoder->guts->integer_signal[i]);
362                                 encoder->guts->integer_signal[i] = 0;
363                         }
364                         if(encoder->guts->real_signal[i] != 0) {
365                                 free(encoder->guts->real_signal[i]);
366                                 encoder->guts->real_signal[i] = 0;
367                         }
368                 }
369                 for(i = 0; i < 2; i++) {
370                         if(encoder->guts->integer_signal_mid_side[i] != 0) {
371                                 free(encoder->guts->integer_signal_mid_side[i]);
372                                 encoder->guts->integer_signal_mid_side[i] = 0;
373                         }
374                         if(encoder->guts->real_signal_mid_side[i] != 0) {
375                                 free(encoder->guts->real_signal_mid_side[i]);
376                                 encoder->guts->real_signal_mid_side[i] = 0;
377                         }
378                 }
379                 for(i = 0; i < 2; i++) {
380                         if(encoder->guts->residual[i] != 0) {
381                                 free(encoder->guts->residual[i]);
382                                 encoder->guts->residual[i] = 0;
383                         }
384                 }
385                 FLAC__bitbuffer_free(&encoder->guts->frame);
386                 free(encoder->guts);
387                 encoder->guts = 0;
388         }
389         encoder->state = FLAC__ENCODER_UNINITIALIZED;
390 }
391
392 bool FLAC__encoder_process(FLAC__Encoder *encoder, const int32 *buf[], unsigned samples)
393 {
394         unsigned i, j, channel;
395         int32 x, mid, side;
396         const bool ms = encoder->do_mid_side_stereo && encoder->channels == 2;
397         const int32 min_side = -((int64)1 << (encoder->bits_per_sample-1));
398         const int32 max_side =  ((int64)1 << (encoder->bits_per_sample-1)) - 1;
399
400         assert(encoder != 0);
401         assert(encoder->state == FLAC__ENCODER_OK);
402
403         j = 0;
404         do {
405                 for(i = encoder->guts->current_sample_number; i < encoder->blocksize && j < samples; i++, j++) {
406                         for(channel = 0; channel < encoder->channels; channel++) {
407                                 x = buf[channel][j];
408                                 encoder->guts->integer_signal[channel][i] = x;
409                                 encoder->guts->real_signal[channel][i] = (real)x;
410                         }
411                         if(ms && encoder->guts->current_frame_can_do_mid_side) {
412                                 side = buf[0][j] - buf[1][j];
413                                 if(side < min_side || side > max_side) {
414                                         encoder->guts->current_frame_can_do_mid_side = false;
415                                 }
416                                 else {
417                                         mid = (buf[0][j] + buf[1][j]) >> 1; /* NOTE: not the same as divide-by-two ! */
418                                         encoder->guts->integer_signal_mid_side[0][i] = mid;
419                                         encoder->guts->integer_signal_mid_side[1][i] = side;
420                                         encoder->guts->real_signal_mid_side[0][i] = (real)mid;
421                                         encoder->guts->real_signal_mid_side[1][i] = (real)side;
422                                 }
423                         }
424                         encoder->guts->current_sample_number++;
425                 }
426                 if(i == encoder->blocksize) {
427                         if(!encoder_process_frame_(encoder, false)) /* false => not last frame */
428                                 return false;
429                 }
430         } while(j < samples);
431
432         return true;
433 }
434
435 /* 'samples' is channel-wide samples, e.g. for 1 second at 44100Hz, 'samples' = 44100 regardless of the number of channels */
436 bool FLAC__encoder_process_interleaved(FLAC__Encoder *encoder, const int32 buf[], unsigned samples)
437 {
438         unsigned i, j, k, channel;
439         int32 x, left = 0, mid, side;
440         const bool ms = encoder->do_mid_side_stereo && encoder->channels == 2;
441         const int32 min_side = -((int64)1 << (encoder->bits_per_sample-1));
442         const int32 max_side =  ((int64)1 << (encoder->bits_per_sample-1)) - 1;
443
444         assert(encoder != 0);
445         assert(encoder->state == FLAC__ENCODER_OK);
446
447         j = k = 0;
448         do {
449                 for(i = encoder->guts->current_sample_number; i < encoder->blocksize && j < samples; i++, j++, k++) {
450                         for(channel = 0; channel < encoder->channels; channel++, k++) {
451                                 x = buf[k];
452                                 encoder->guts->integer_signal[channel][i] = x;
453                                 encoder->guts->real_signal[channel][i] = (real)x;
454                                 if(ms && encoder->guts->current_frame_can_do_mid_side) {
455                                         if(channel == 0) {
456                                                 left = x;
457                                         }
458                                         else {
459                                                 side = left - x;
460                                                 if(side < min_side || side > max_side) {
461                                                         encoder->guts->current_frame_can_do_mid_side = false;
462                                                 }
463                                                 else {
464                                                         mid = (left + x) >> 1; /* NOTE: not the same as divide-by-two ! */
465                                                         encoder->guts->integer_signal_mid_side[0][i] = mid;
466                                                         encoder->guts->integer_signal_mid_side[1][i] = side;
467                                                         encoder->guts->real_signal_mid_side[0][i] = (real)mid;
468                                                         encoder->guts->real_signal_mid_side[1][i] = (real)side;
469                                                 }
470                                         }
471                                 }
472                         }
473                         encoder->guts->current_sample_number++;
474                 }
475                 if(i == encoder->blocksize) {
476                         if(!encoder_process_frame_(encoder, false)) /* false => not last frame */
477                                 return false;
478                 }
479         } while(j < samples);
480
481         return true;
482 }
483
484 bool encoder_process_frame_(FLAC__Encoder *encoder, bool is_last_frame)
485 {
486         FLAC__FrameHeader frame_header;
487         FLAC__BitBuffer *smallest_frame;
488
489         assert(encoder->state == FLAC__ENCODER_OK);
490
491         /*
492          * First do a normal encoding pass
493          */
494         frame_header.blocksize = encoder->blocksize;
495         frame_header.sample_rate = encoder->sample_rate;
496         frame_header.channels = encoder->channels;
497         frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
498         frame_header.bits_per_sample = encoder->bits_per_sample;
499         frame_header.number.frame_number = encoder->guts->current_frame_number;
500
501         if(!FLAC__bitbuffer_clear(&encoder->guts->frame)) {
502                 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
503                 return false;
504         }
505         if(!FLAC__frame_add_header(&frame_header, encoder->streamable_subset, is_last_frame, &encoder->guts->frame)) {
506                 encoder->state = FLAC__ENCODER_FRAMING_ERROR;
507                 return false;
508         }
509
510         if(!encoder_process_subframes_(encoder, is_last_frame, &frame_header, encoder->channels, encoder->guts->integer_signal, encoder->guts->real_signal, &encoder->guts->frame))
511                 return false;
512
513         smallest_frame = &encoder->guts->frame;
514
515         /*
516          * Now try a mid-side version if necessary; otherwise, just use the previous step's frame
517          */
518         if(encoder->do_mid_side_stereo && encoder->guts->current_frame_can_do_mid_side) {
519                 int32 *integer_signal[2];
520                 real *real_signal[2];
521
522                 assert(encoder->channels == 2);
523
524                 /* mid-side */
525                 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
526                 if(!FLAC__bitbuffer_clear(&encoder->guts->frame_mid_side)) {
527                         encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
528                         return false;
529                 }
530                 if(!FLAC__frame_add_header(&frame_header, encoder->streamable_subset, is_last_frame, &encoder->guts->frame_mid_side)) {
531                         encoder->state = FLAC__ENCODER_FRAMING_ERROR;
532                         return false;
533                 }
534                 integer_signal[0] = encoder->guts->integer_signal_mid_side[0]; /* mid channel */
535                 integer_signal[1] = encoder->guts->integer_signal_mid_side[1]; /* side channel */
536                 real_signal[0] = encoder->guts->real_signal_mid_side[0]; /* mid channel */
537                 real_signal[1] = encoder->guts->real_signal_mid_side[1]; /* side channel */
538                 if(!encoder_process_subframes_(encoder, is_last_frame, &frame_header, encoder->channels, integer_signal, real_signal, &encoder->guts->frame_mid_side))
539                         return false;
540                 if(encoder->guts->frame_mid_side.total_bits < smallest_frame->total_bits)
541                         smallest_frame = &encoder->guts->frame_mid_side;
542
543                 /* left-side */
544                 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
545                 if(!FLAC__bitbuffer_clear(&encoder->guts->frame_left_side)) {
546                         encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
547                         return false;
548                 }
549                 if(!FLAC__frame_add_header(&frame_header, encoder->streamable_subset, is_last_frame, &encoder->guts->frame_left_side)) {
550                         encoder->state = FLAC__ENCODER_FRAMING_ERROR;
551                         return false;
552                 }
553                 integer_signal[0] = encoder->guts->integer_signal[0]; /* left channel */
554                 integer_signal[1] = encoder->guts->integer_signal_mid_side[1]; /* side channel */
555                 real_signal[0] = encoder->guts->real_signal[0]; /* left channel */
556                 real_signal[1] = encoder->guts->real_signal_mid_side[1]; /* side channel */
557                 if(!encoder_process_subframes_(encoder, is_last_frame, &frame_header, encoder->channels, integer_signal, real_signal, &encoder->guts->frame_left_side))
558                         return false;
559                 if(encoder->guts->frame_left_side.total_bits < smallest_frame->total_bits)
560                         smallest_frame = &encoder->guts->frame_left_side;
561
562                 /* right-side */
563                 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
564                 if(!FLAC__bitbuffer_clear(&encoder->guts->frame_right_side)) {
565                         encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
566                         return false;
567                 }
568                 if(!FLAC__frame_add_header(&frame_header, encoder->streamable_subset, is_last_frame, &encoder->guts->frame_right_side)) {
569                         encoder->state = FLAC__ENCODER_FRAMING_ERROR;
570                         return false;
571                 }
572                 integer_signal[0] = encoder->guts->integer_signal_mid_side[1]; /* side channel */
573                 integer_signal[1] = encoder->guts->integer_signal[1]; /* right channel */
574                 real_signal[0] = encoder->guts->real_signal_mid_side[1]; /* side channel */
575                 real_signal[1] = encoder->guts->real_signal[1]; /* right channel */
576                 if(!encoder_process_subframes_(encoder, is_last_frame, &frame_header, encoder->channels, integer_signal, real_signal, &encoder->guts->frame_right_side))
577                         return false;
578                 if(encoder->guts->frame_right_side.total_bits < smallest_frame->total_bits)
579                         smallest_frame = &encoder->guts->frame_right_side;
580         }
581
582         /*
583          * Zero-pad the frame to a byte_boundary
584          */
585         if(!FLAC__bitbuffer_zero_pad_to_byte_boundary(smallest_frame)) {
586                 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
587                 return false;
588         }
589
590         /*
591          * Write it
592          */
593         assert(smallest_frame->bits == 0); /* assert that we're byte-aligned before writing */
594         assert(smallest_frame->total_consumed_bits == 0); /* assert that no reading of the buffer was done */
595         if(encoder->guts->write_callback(encoder, smallest_frame->buffer, smallest_frame->bytes, encoder->blocksize, encoder->guts->current_frame_number, encoder->guts->client_data) != FLAC__ENCODER_WRITE_OK) {
596                 encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_WRITING;
597                 return false;
598         }
599
600         /*
601          * Get ready for the next frame
602          */
603         encoder->guts->current_frame_can_do_mid_side = true;
604         encoder->guts->current_sample_number = 0;
605         encoder->guts->current_frame_number++;
606         encoder->guts->metadata.data.encoding.total_samples += (uint64)encoder->blocksize;
607         encoder->guts->metadata.data.encoding.min_framesize = min(smallest_frame->bytes, encoder->guts->metadata.data.encoding.min_framesize);
608         encoder->guts->metadata.data.encoding.max_framesize = max(smallest_frame->bytes, encoder->guts->metadata.data.encoding.max_framesize);
609
610         return true;
611 }
612
613 bool encoder_process_subframes_(FLAC__Encoder *encoder, bool is_last_frame, const FLAC__FrameHeader *frame_header, unsigned channels, const int32 *integer_signal[], const real *real_signal[], FLAC__BitBuffer *frame)
614 {
615         real fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
616         real lpc_residual_bits_per_sample;
617         real autoc[FLAC__MAX_LPC_ORDER+1];
618         real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER];
619         real lpc_error[FLAC__MAX_LPC_ORDER];
620         unsigned channel;
621         unsigned min_lpc_order, max_lpc_order, lpc_order;
622         unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
623         unsigned max_partition_order;
624         unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
625         unsigned rice_parameter;
626         unsigned candidate_bits, best_bits;
627
628         if(is_last_frame) {
629                 max_partition_order = 0;
630         }
631         else {
632                 unsigned limit = 0, b = encoder->blocksize;
633                 while(!(b & 1)) {
634                         limit++;
635                         b >>= 1;
636                 }
637                 max_partition_order = min(encoder->rice_optimization_level, limit);
638         }
639
640         for(channel = 0; channel < channels; channel++) {
641                 /* verbatim subframe is the baseline against which we measure other compressed subframes */
642                 best_bits = encoder_evaluate_verbatim_subframe_(frame_header->blocksize, frame_header->bits_per_sample, &(encoder->guts->best_subframe));
643
644                 if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
645                         /* check for constant subframe */
646                         guess_fixed_order = FLAC__fixed_compute_best_predictor(integer_signal[channel]+FLAC__MAX_FIXED_ORDER, frame_header->blocksize-FLAC__MAX_FIXED_ORDER, fixed_residual_bits_per_sample);
647                         if(fixed_residual_bits_per_sample[1] == 0.0) {
648                                 /* the above means integer_signal[channel]+FLAC__MAX_FIXED_ORDER is constant, now we just have to check the warmup samples */
649                                 unsigned i, signal_is_constant = true;
650                                 for(i = 1; i <= FLAC__MAX_FIXED_ORDER; i++) {
651                                         if(integer_signal[channel][0] != integer_signal[channel][i]) {
652                                                 signal_is_constant = false;
653                                                 break;
654                                         }
655                                 }
656                                 if(signal_is_constant) {
657                                         candidate_bits = encoder_evaluate_constant_subframe_(integer_signal[channel][0], frame_header->bits_per_sample, &(encoder->guts->candidate_subframe));
658                                         if(candidate_bits < best_bits) {
659                                                 encoder_promote_candidate_subframe_(encoder);
660                                                 best_bits = candidate_bits;
661                                         }
662                                 }
663                         }
664                         else {
665                                 /* encode fixed */
666                                 if(encoder->do_exhaustive_model_search) {
667                                         min_fixed_order = 0;
668                                         max_fixed_order = FLAC__MAX_FIXED_ORDER;
669                                 }
670                                 else {
671                                         min_fixed_order = max_fixed_order = guess_fixed_order;
672                                 }
673                                 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
674                                         if(fixed_residual_bits_per_sample[fixed_order] >= (real)frame_header->bits_per_sample)
675                                                 continue; /* don't even try */
676                                         /* 0.5 is for rounding, another 1.0 is to account for the signed->unsigned conversion during rice coding */
677                                         rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > 0.0)? (unsigned)(fixed_residual_bits_per_sample[fixed_order]+1.5) : 0;
678                                         if(rice_parameter >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN))
679                                                 rice_parameter = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN) - 1;
680                                         candidate_bits = encoder_evaluate_fixed_subframe_(integer_signal[channel], encoder->guts->residual[!encoder->guts->best_residual], frame_header->blocksize, frame_header->bits_per_sample, fixed_order, rice_parameter, max_partition_order, &(encoder->guts->candidate_subframe));
681                                         if(candidate_bits < best_bits) {
682                                                 encoder_promote_candidate_subframe_(encoder);
683                                                 best_bits = candidate_bits;
684                                         }
685                                 }
686
687                                 /* encode lpc */
688                                 if(encoder->max_lpc_order > 0) {
689                                         if(encoder->max_lpc_order >= frame_header->blocksize)
690                                                 max_lpc_order = frame_header->blocksize-1;
691                                         else
692                                                 max_lpc_order = encoder->max_lpc_order;
693                                         if(max_lpc_order > 0) {
694                                                 FLAC__lpc_compute_autocorrelation(real_signal[channel], frame_header->blocksize, max_lpc_order+1, autoc);
695                                                 FLAC__lpc_compute_lp_coefficients(autoc, max_lpc_order, lp_coeff, lpc_error);
696                                                 if(encoder->do_exhaustive_model_search) {
697                                                         min_lpc_order = 1;
698                                                 }
699                                                 else {
700                                                         unsigned guess_lpc_order = FLAC__lpc_compute_best_order(lpc_error, max_lpc_order, frame_header->blocksize, frame_header->bits_per_sample);
701                                                         min_lpc_order = max_lpc_order = guess_lpc_order;
702                                                 }
703                                                 if(encoder->do_qlp_coeff_prec_search) {
704                                                         min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
705                                                         max_qlp_coeff_precision = 32 - frame_header->bits_per_sample - 1;
706                                                 }
707                                                 else {
708                                                         min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->qlp_coeff_precision;
709                                                 }
710                                                 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
711                                                         lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize);
712                                                         if(lpc_residual_bits_per_sample >= (real)frame_header->bits_per_sample)
713                                                                 continue; /* don't even try */
714                                                         /* 0.5 is for rounding, another 1.0 is to account for the signed->unsigned conversion during rice coding */
715                                                         rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+1.5) : 0;
716                                                         if(rice_parameter >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN))
717                                                                 rice_parameter = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN) - 1;
718                                                         for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
719                                                                 candidate_bits = encoder_evaluate_lpc_subframe_(integer_signal[channel], encoder->guts->residual[!encoder->guts->best_residual], lp_coeff[lpc_order-1], frame_header->blocksize, frame_header->bits_per_sample, lpc_order, qlp_coeff_precision, rice_parameter, max_partition_order, &(encoder->guts->candidate_subframe));
720                                                                 if(candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
721                                                                         if(candidate_bits < best_bits) {
722                                                                                 encoder_promote_candidate_subframe_(encoder);
723                                                                                 best_bits = candidate_bits;
724                                                                         }
725                                                                 }
726                                                         }
727                                                 }
728                                         }
729                                 }
730                         }
731                 }
732
733                 /* add the best subframe */
734                 switch(encoder->guts->best_subframe.type) {
735                         case FLAC__SUBFRAME_TYPE_CONSTANT:
736                                 if(!encoder_generate_constant_subframe_(&(encoder->guts->best_subframe), frame_header->bits_per_sample, frame)) {
737                                         encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING;
738                                         return false;
739                                 }
740                                 break;
741                         case FLAC__SUBFRAME_TYPE_FIXED:
742                                 if(!encoder_generate_fixed_subframe_(&(encoder->guts->best_subframe), encoder->guts->residual[encoder->guts->best_residual], frame_header->blocksize, frame_header->bits_per_sample, frame)) {
743                                         encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING;
744                                         return false;
745                                 }
746                                 break;
747                         case FLAC__SUBFRAME_TYPE_LPC:
748                                 if(!encoder_generate_lpc_subframe_(&(encoder->guts->best_subframe), encoder->guts->residual[encoder->guts->best_residual], frame_header->blocksize, frame_header->bits_per_sample, frame)) {
749                                         encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING;
750                                         return false;
751                                 }
752                                 break;
753                         case FLAC__SUBFRAME_TYPE_VERBATIM:
754                                 if(!encoder_generate_verbatim_subframe_(&(encoder->guts->best_subframe), integer_signal[channel], frame_header->blocksize, frame_header->bits_per_sample, frame)) {
755                                         encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING;
756                                         return false;
757                                 }
758                                 break;
759                 }
760         }
761
762         return true;
763 }
764
765 unsigned encoder_evaluate_constant_subframe_(const int32 signal, unsigned bits_per_sample, FLAC__SubframeHeader *subframe)
766 {
767         subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
768         subframe->data.constant.value = signal;
769
770         return FLAC__SUBFRAME_HEADER_TYPE_LEN + bits_per_sample;
771 }
772
773 unsigned encoder_evaluate_fixed_subframe_(const int32 signal[], int32 residual[], unsigned blocksize, unsigned bits_per_sample, unsigned order, unsigned rice_parameter, unsigned max_partition_order, FLAC__SubframeHeader *subframe)
774 {
775         unsigned i, residual_bits;
776         const unsigned residual_samples = blocksize - order;
777
778         FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
779
780         subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
781
782         subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
783
784         residual_bits = encoder_find_best_partition_order_(residual, 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);
785
786         subframe->data.fixed.order = order;
787         for(i = 0; i < order; i++)
788                 subframe->data.fixed.warmup[i] = signal[i];
789
790         return FLAC__SUBFRAME_HEADER_TYPE_LEN + (order * bits_per_sample) + residual_bits;
791 }
792
793 unsigned encoder_evaluate_lpc_subframe_(const int32 signal[], int32 residual[], const real lp_coeff[], unsigned blocksize, unsigned bits_per_sample, unsigned order, unsigned qlp_coeff_precision, unsigned rice_parameter, unsigned max_partition_order, FLAC__SubframeHeader *subframe)
794 {
795         int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
796         unsigned i, residual_bits;
797         int quantization, ret;
798         const unsigned residual_samples = blocksize - order;
799
800         ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, bits_per_sample, qlp_coeff, &quantization);
801         if(ret != 0)
802                 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
803
804         FLAC__lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
805
806         subframe->type = FLAC__SUBFRAME_TYPE_LPC;
807
808         subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
809
810         residual_bits = encoder_find_best_partition_order_(residual, 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);
811
812         subframe->data.lpc.order = order;
813         subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
814         subframe->data.lpc.quantization_level = quantization;
815         memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(int32)*FLAC__MAX_LPC_ORDER);
816         for(i = 0; i < order; i++)
817                 subframe->data.lpc.warmup[i] = signal[i];
818
819         return FLAC__SUBFRAME_HEADER_TYPE_LEN + FLAC__SUBFRAME_HEADER_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_HEADER_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + bits_per_sample)) + residual_bits;
820 }
821
822 unsigned encoder_evaluate_verbatim_subframe_(unsigned blocksize, unsigned bits_per_sample, FLAC__SubframeHeader *subframe)
823 {
824         subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
825
826         return FLAC__SUBFRAME_HEADER_TYPE_LEN + (blocksize * bits_per_sample);
827 }
828
829 unsigned encoder_find_best_partition_order_(int32 residual[], unsigned residual_samples, unsigned predictor_order, unsigned rice_parameter, unsigned max_partition_order, unsigned *best_partition_order, unsigned best_parameters[])
830 {
831         unsigned residual_bits, best_residual_bits = 0;
832         unsigned partition_order;
833         unsigned best_parameters_index = 0, parameters[2][1 << FLAC__MAX_RICE_PARTITION_ORDER];
834
835         for(partition_order = 0; partition_order <= max_partition_order; partition_order++) {
836                 if(!encoder_set_partitioned_rice_(residual, residual_samples, predictor_order, rice_parameter, partition_order, parameters[!best_parameters_index], &residual_bits)) {
837                         assert(best_residual_bits != 0);
838                         break;
839                 }
840                 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
841                         best_residual_bits = residual_bits;
842                         *best_partition_order = partition_order;
843                         best_parameters_index = !best_parameters_index;
844                 }
845         }
846         memcpy(best_parameters, parameters[best_parameters_index], sizeof(unsigned)*(1<<(*best_partition_order)));
847
848         return best_residual_bits;
849 }
850
851 bool encoder_generate_constant_subframe_(const FLAC__SubframeHeader *header, unsigned bits_per_sample, FLAC__BitBuffer *bitbuffer)
852 {
853         assert(header->type == FLAC__SUBFRAME_TYPE_CONSTANT);
854         return FLAC__subframe_add_constant(bits_per_sample, header, bitbuffer);
855 }
856
857 bool encoder_generate_fixed_subframe_(const FLAC__SubframeHeader *header, int32 residual[], unsigned blocksize, unsigned bits_per_sample, FLAC__BitBuffer *bitbuffer)
858 {
859         assert(header->type == FLAC__SUBFRAME_TYPE_FIXED);
860         return FLAC__subframe_add_fixed(residual, blocksize - header->data.fixed.order, bits_per_sample, header, bitbuffer);
861 }
862
863 bool encoder_generate_lpc_subframe_(const FLAC__SubframeHeader *header, int32 residual[], unsigned blocksize, unsigned bits_per_sample, FLAC__BitBuffer *bitbuffer)
864 {
865         assert(header->type == FLAC__SUBFRAME_TYPE_LPC);
866         return FLAC__subframe_add_lpc(residual, blocksize - header->data.lpc.order, bits_per_sample, header, bitbuffer);
867 }
868
869 bool encoder_generate_verbatim_subframe_(const FLAC__SubframeHeader *header, const int32 signal[], unsigned blocksize, unsigned bits_per_sample, FLAC__BitBuffer *bitbuffer)
870 {
871         assert(header->type == FLAC__SUBFRAME_TYPE_VERBATIM);
872 #ifdef NDEBUG
873         (void)header; /* silence compiler warning about unused parameter */
874 #endif
875         return FLAC__subframe_add_verbatim(signal, blocksize, bits_per_sample, bitbuffer);
876 }
877
878 void encoder_promote_candidate_subframe_(FLAC__Encoder *encoder)
879 {
880         assert(encoder->state == FLAC__ENCODER_OK);
881         encoder->guts->best_subframe = encoder->guts->candidate_subframe;
882         encoder->guts->best_residual = !encoder->guts->best_residual;
883 }
884
885 bool encoder_set_partitioned_rice_(const int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameter, const unsigned partition_order, unsigned parameters[], unsigned *bits)
886 {
887         unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
888
889         if(partition_order == 0) {
890                 unsigned i;
891                 parameters[0] = rice_parameter;
892                 bits_ += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
893                 for(i = 0; i < residual_samples; i++)
894                         bits_ += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter);
895         }
896         else {
897                 unsigned i, j, k = 0, k_last = 0;
898                 unsigned mean, parameter, partition_samples;
899                 const unsigned max_parameter = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN) - 1;
900                 for(i = 0; i < (1u<<partition_order); i++) {
901                         partition_samples = (residual_samples+predictor_order) >> partition_order;
902                         if(i == 0) {
903                                 if(partition_samples <= predictor_order)
904                                         return false;
905                                 else
906                                         partition_samples -= predictor_order;
907                         }
908                         mean = partition_samples >> 1;
909                         for(j = 0; j < partition_samples; j++, k++)
910                                 mean += ((residual[k] < 0)? (unsigned)(-residual[k]) : (unsigned)residual[k]);
911                         mean /= partition_samples;
912                         /* calc parameter = floor(log2(mean)) + 1 */
913                         parameter = 0;
914                         while(mean) {
915                                 parameter++;
916                                 mean >>= 1;
917                         }
918                         if(parameter > max_parameter)
919                                 parameter = max_parameter;
920                         parameters[i] = parameter;
921                         bits_ += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
922                         for(j = k_last; j < k; j++)
923                                 bits_ += FLAC__bitbuffer_rice_bits(residual[j], parameter);
924                         k_last = k;
925                 }
926         }
927
928         *bits = bits_;
929         return true;
930 }