rename some struct members to avoid C++ 'private' and 'protected' keywords
[platform/upstream/flac.git] / src / libFLAC / stream_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 <stdio.h>
21 #include <stdlib.h> /* for malloc() */
22 #include <string.h> /* for memcpy() */
23 #include "FLAC/assert.h"
24 #include "FLAC/seek_table.h"
25 #include "protected/stream_encoder.h"
26 #include "private/bitbuffer.h"
27 #include "private/bitmath.h"
28 #include "private/crc.h"
29 #include "private/cpu.h"
30 #include "private/stream_encoder_framing.h"
31 #include "private/fixed.h"
32 #include "private/lpc.h"
33 #include "private/md5.h"
34 #include "private/memory.h"
35
36 #ifdef min
37 #undef min
38 #endif
39 #define min(x,y) ((x)<(y)?(x):(y))
40
41 #ifdef max
42 #undef max
43 #endif
44 #define max(x,y) ((x)>(y)?(x):(y))
45
46 /***********************************************************************
47  *
48  * Private class method prototypes
49  *
50  ***********************************************************************/
51
52 static FLAC__bool stream_encoder_resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_size);
53 static FLAC__bool stream_encoder_process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame);
54 static FLAC__bool stream_encoder_process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame);
55 static FLAC__bool stream_encoder_process_subframe_(FLAC__StreamEncoder *encoder, unsigned min_partition_order, unsigned max_partition_order, FLAC__bool precompute_partition_sums, FLAC__bool verbatim_only, const FLAC__FrameHeader *frame_header, unsigned subframe_bps, const FLAC__int32 integer_signal[], const FLAC__real real_signal[], FLAC__Subframe *subframe[2], FLAC__int32 *residual[2], unsigned *best_subframe, unsigned *best_bits);
56 static FLAC__bool stream_encoder_add_subframe_(FLAC__StreamEncoder *encoder, const FLAC__FrameHeader *frame_header, unsigned subframe_bps, const FLAC__Subframe *subframe, FLAC__BitBuffer *frame);
57 static unsigned stream_encoder_evaluate_constant_subframe_(const FLAC__int32 signal, unsigned subframe_bps, FLAC__Subframe *subframe);
58 static unsigned stream_encoder_evaluate_fixed_subframe_(const FLAC__int32 signal[], FLAC__int32 residual[], FLAC__uint32 abs_residual[], FLAC__uint64 abs_residual_partition_sums[], unsigned raw_bits_per_partition[], unsigned blocksize, unsigned subframe_bps, unsigned order, unsigned rice_parameter, unsigned min_partition_order, unsigned max_partition_order, FLAC__bool precompute_partition_sums, FLAC__bool do_escape_coding, unsigned rice_parameter_search_dist, FLAC__Subframe *subframe);
59 static unsigned stream_encoder_evaluate_lpc_subframe_(FLAC__StreamEncoder *encoder, const FLAC__int32 signal[], FLAC__int32 residual[], FLAC__uint32 abs_residual[], FLAC__uint64 abs_residual_partition_sums[], unsigned raw_bits_per_partition[], const FLAC__real lp_coeff[], unsigned blocksize, unsigned subframe_bps, unsigned order, unsigned qlp_coeff_precision, unsigned rice_parameter, unsigned min_partition_order, unsigned max_partition_order, FLAC__bool precompute_partition_sums, FLAC__bool do_escape_coding, unsigned rice_parameter_search_dist, FLAC__Subframe *subframe);
60 static unsigned stream_encoder_evaluate_verbatim_subframe_(const FLAC__int32 signal[], unsigned blocksize, unsigned subframe_bps, FLAC__Subframe *subframe);
61 static unsigned stream_encoder_find_best_partition_order_(const FLAC__int32 residual[], FLAC__uint32 abs_residual[], FLAC__uint64 abs_residual_partition_sums[], unsigned raw_bits_per_partition[], unsigned residual_samples, unsigned predictor_order, unsigned rice_parameter, unsigned min_partition_order, unsigned max_partition_order, FLAC__bool precompute_partition_sums, FLAC__bool do_escape_coding, unsigned rice_parameter_search_dist, unsigned *best_partition_order, unsigned best_parameters[], unsigned best_raw_bits[]);
62 static void stream_encoder_precompute_partition_info_sums_(const FLAC__uint32 abs_residual[], FLAC__uint64 abs_residual_partition_sums[], unsigned residual_samples, unsigned predictor_order, unsigned min_partition_order, unsigned max_partition_order);
63 static void stream_encoder_precompute_partition_info_escapes_(const FLAC__int32 residual[], unsigned raw_bits_per_partition[], unsigned residual_samples, unsigned predictor_order, unsigned min_partition_order, unsigned max_partition_order);
64 #ifdef DONT_ESTIMATE_RICE_BITS
65 static FLAC__bool stream_encoder_set_partitioned_rice_(const FLAC__uint32 abs_residual[], const FLAC__int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned suggested_rice_parameter, const unsigned rice_parameter_search_dist, const unsigned partition_order, unsigned parameters[], unsigned *bits);
66 static FLAC__bool stream_encoder_set_partitioned_rice_with_precompute_(const FLAC__int32 residual[], const FLAC__uint64 abs_residual_partition_sums[], const unsigned raw_bits_per_partition[], const unsigned residual_samples, const unsigned predictor_order, const unsigned suggested_rice_parameter, const unsigned rice_parameter_search_dist, const unsigned partition_order, const FLAC__bool search_for_escapes, unsigned parameters[], unsigned raw_bits[], unsigned *bits);
67 #else
68 static FLAC__bool stream_encoder_set_partitioned_rice_(const FLAC__uint32 abs_residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned suggested_rice_parameter, const unsigned rice_parameter_search_dist, const unsigned partition_order, unsigned parameters[], unsigned *bits);
69 static FLAC__bool stream_encoder_set_partitioned_rice_with_precompute_(const FLAC__uint32 abs_residual[], const FLAC__uint64 abs_residual_partition_sums[], const unsigned raw_bits_per_partition[], const unsigned residual_samples, const unsigned predictor_order, const unsigned suggested_rice_parameter, const unsigned rice_parameter_search_dist, const unsigned partition_order, const FLAC__bool search_for_escapes, unsigned parameters[], unsigned raw_bits[], unsigned *bits);
70 #endif
71 static unsigned stream_encoder_get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
72
73 /***********************************************************************
74  *
75  * Private class data
76  *
77  ***********************************************************************/
78
79 typedef struct FLAC__StreamEncoderPrivate {
80         unsigned input_capacity;                          /* current size (in samples) of the signal and residual buffers */
81         FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS];  /* the integer version of the input signal */
82         FLAC__int32 *integer_signal_mid_side[2];          /* the integer version of the mid-side input signal (stereo only) */
83         FLAC__real *real_signal[FLAC__MAX_CHANNELS];      /* the floating-point version of the input signal */
84         FLAC__real *real_signal_mid_side[2];              /* the floating-point version of the mid-side input signal (stereo only) */
85         unsigned subframe_bps[FLAC__MAX_CHANNELS];        /* the effective bits per sample of the input signal (stream bps - wasted bits) */
86         unsigned subframe_bps_mid_side[2];                /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
87         FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
88         FLAC__int32 *residual_workspace_mid_side[2][2];
89         FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
90         FLAC__Subframe subframe_workspace_mid_side[2][2];
91         FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
92         FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
93         unsigned best_subframe[FLAC__MAX_CHANNELS];       /* index into the above workspaces */
94         unsigned best_subframe_mid_side[2];
95         unsigned best_subframe_bits[FLAC__MAX_CHANNELS];  /* size in bits of the best subframe for each channel */
96         unsigned best_subframe_bits_mid_side[2];
97         FLAC__uint32 *abs_residual;                       /* workspace where abs(candidate residual) is stored */
98         FLAC__uint64 *abs_residual_partition_sums;        /* workspace where the sum of abs(candidate residual) for each partition is stored */
99         unsigned *raw_bits_per_partition;                 /* workspace where the sum of silog2(candidate residual) for each partition is stored */
100         FLAC__BitBuffer frame;                            /* the current frame being worked on */
101         double loose_mid_side_stereo_frames_exact;        /* exact number of frames the encoder will use before trying both independent and mid/side frames again */
102         unsigned loose_mid_side_stereo_frames;            /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
103         unsigned loose_mid_side_stereo_frame_count;       /* number of frames using the current channel assignment */
104         FLAC__ChannelAssignment last_channel_assignment;
105         FLAC__StreamMetaData metadata;
106         unsigned current_sample_number;
107         unsigned current_frame_number;
108         struct MD5Context md5context;
109         FLAC__CPUInfo cpuinfo;
110         unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__real residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
111         void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
112         void (*local_lpc_compute_residual_from_qlp_coefficients)(const FLAC__int32 data[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
113         void (*local_lpc_compute_residual_from_qlp_coefficients_16bit)(const FLAC__int32 data[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
114         FLAC__bool use_wide_by_block;                     /* use slow 64-bit versions of some functions because of the block size */
115         FLAC__bool use_wide_by_partition;                 /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
116         FLAC__bool use_wide_by_order;                     /* use slow 64-bit versions of some functions because of the lpc order */
117         FLAC__bool precompute_partition_sums;             /* our initial guess as to whether precomputing the partitions sums will be a speed improvement */
118         FLAC__StreamEncoderWriteStatus (*write_callback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
119         void (*metadata_callback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data);
120         void *client_data;
121         /* unaligned (original) pointers to allocated data */
122         FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
123         FLAC__int32 *integer_signal_mid_side_unaligned[2];
124         FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS];
125         FLAC__real *real_signal_mid_side_unaligned[2];
126         FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
127         FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
128         FLAC__uint32 *abs_residual_unaligned;
129         FLAC__uint64 *abs_residual_partition_sums_unaligned;
130         unsigned *raw_bits_per_partition_unaligned;
131 } FLAC__StreamEncoderPrivate;
132
133 /***********************************************************************
134  *
135  * Public static class data
136  *
137  ***********************************************************************/
138
139 const char *FLAC__StreamEncoderStateString[] = {
140         "FLAC__STREAM_ENCODER_OK",
141         "FLAC__STREAM_ENCODER_INVALID_CALLBACK",
142         "FLAC__STREAM_ENCODER_INVALID_NUMBER_OF_CHANNELS",
143         "FLAC__STREAM_ENCODER_INVALID_BITS_PER_SAMPLE",
144         "FLAC__STREAM_ENCODER_INVALID_SAMPLE_RATE",
145         "FLAC__STREAM_ENCODER_INVALID_BLOCK_SIZE",
146         "FLAC__STREAM_ENCODER_INVALID_QLP_COEFF_PRECISION",
147         "FLAC__STREAM_ENCODER_MID_SIDE_CHANNELS_MISMATCH",
148         "FLAC__STREAM_ENCODER_MID_SIDE_SAMPLE_SIZE_MISMATCH",
149         "FLAC__STREAM_ENCODER_ILLEGAL_MID_SIDE_FORCE",
150         "FLAC__STREAM_ENCODER_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
151         "FLAC__STREAM_ENCODER_NOT_STREAMABLE",
152         "FLAC__STREAM_ENCODER_FRAMING_ERROR",
153         "FLAC__STREAM_ENCODER_INVALID_SEEK_TABLE",
154         "FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING",
155         "FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_WRITING",
156         "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR",
157         "FLAC__STREAM_ENCODER_ALREADY_INITIALIZED",
158         "FLAC__STREAM_ENCODER_UNINITIALIZED"
159 };
160
161 const char *FLAC__StreamEncoderWriteStatusString[] = {
162         "FLAC__STREAM_ENCODER_WRITE_OK",
163         "FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR"
164 };
165
166 /***********************************************************************
167  *
168  * Class constructor/destructor
169  *
170  ***********************************************************************/
171 FLAC__StreamEncoder *FLAC__stream_encoder_new()
172 {
173         FLAC__StreamEncoder *encoder;
174
175         FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
176
177         encoder = (FLAC__StreamEncoder*)malloc(sizeof(FLAC__StreamEncoder));
178         if(encoder == 0) {
179                 return 0;
180         }
181         encoder->protected_ = (FLAC__StreamEncoderProtected*)malloc(sizeof(FLAC__StreamEncoderProtected));
182         if(encoder->protected_ == 0) {
183                 free(encoder);
184                 return 0;
185         }
186         encoder->private_ = (FLAC__StreamEncoderPrivate*)malloc(sizeof(FLAC__StreamEncoderPrivate));
187         if(encoder->private_ == 0) {
188                 free(encoder->protected_);
189                 free(encoder);
190                 return 0;
191         }
192
193         encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
194
195         encoder->protected_->streamable_subset = true;
196         encoder->protected_->do_mid_side_stereo = false;
197         encoder->protected_->loose_mid_side_stereo = false;
198         encoder->protected_->channels = 2;
199         encoder->protected_->bits_per_sample = 16;
200         encoder->protected_->sample_rate = 44100;
201         encoder->protected_->blocksize = 1152;
202         encoder->protected_->max_lpc_order = 0;
203         encoder->protected_->qlp_coeff_precision = 0;
204         encoder->protected_->do_qlp_coeff_prec_search = false;
205         encoder->protected_->do_exhaustive_model_search = false;
206         encoder->protected_->do_escape_coding = false;
207         encoder->protected_->min_residual_partition_order = 0;
208         encoder->protected_->max_residual_partition_order = 0;
209         encoder->protected_->rice_parameter_search_dist = 0;
210         encoder->protected_->total_samples_estimate = 0;
211         encoder->protected_->seek_table = 0;
212         encoder->protected_->padding = 0;
213         encoder->protected_->last_metadata_is_last = true;
214
215         encoder->private_->write_callback = 0;
216         encoder->private_->metadata_callback = 0;
217         encoder->private_->client_data = 0;
218
219         return encoder;
220 }
221
222 void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
223 {
224         FLAC__ASSERT(encoder != 0);
225         FLAC__ASSERT(encoder->protected_ != 0);
226         FLAC__ASSERT(encoder->private_ != 0);
227
228         free(encoder->private_);
229         free(encoder->protected_);
230         free(encoder);
231 }
232
233 /***********************************************************************
234  *
235  * Public class methods
236  *
237  ***********************************************************************/
238
239 FLAC__StreamEncoderState FLAC__stream_encoder_init(FLAC__StreamEncoder *encoder)
240 {
241         unsigned i;
242         FLAC__StreamMetaData padding_block;
243         FLAC__StreamMetaData seek_table_block;
244
245         FLAC__ASSERT(encoder != 0);
246
247         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
248                 return encoder->protected_->state = FLAC__STREAM_ENCODER_ALREADY_INITIALIZED;
249
250         encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
251
252         if(0 == encoder->private_->write_callback || 0 == encoder->private_->metadata_callback)
253                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_CALLBACK;
254
255         if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
256                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_NUMBER_OF_CHANNELS;
257
258         if(encoder->protected_->do_mid_side_stereo && encoder->protected_->channels != 2)
259                 return encoder->protected_->state = FLAC__STREAM_ENCODER_MID_SIDE_CHANNELS_MISMATCH;
260
261         if(encoder->protected_->loose_mid_side_stereo && !encoder->protected_->do_mid_side_stereo)
262                 return encoder->protected_->state = FLAC__STREAM_ENCODER_ILLEGAL_MID_SIDE_FORCE;
263
264         if(encoder->protected_->bits_per_sample >= 32)
265                 encoder->protected_->do_mid_side_stereo = false; /* since we do 32-bit math, the side channel would have 33 bps and overflow */
266
267         if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__MAX_BITS_PER_SAMPLE)
268                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_BITS_PER_SAMPLE;
269
270         if(encoder->protected_->sample_rate == 0 || encoder->protected_->sample_rate > FLAC__MAX_SAMPLE_RATE)
271                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_SAMPLE_RATE;
272
273         if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
274                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_BLOCK_SIZE;
275
276         if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
277                 return encoder->protected_->state = FLAC__STREAM_ENCODER_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
278
279         if(encoder->protected_->qlp_coeff_precision == 0) {
280                 if(encoder->protected_->bits_per_sample < 16) {
281                         /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
282                         /* @@@ until then we'll make a guess */
283                         encoder->protected_->qlp_coeff_precision = max(5, 2 + encoder->protected_->bits_per_sample / 2);
284                 }
285                 else if(encoder->protected_->bits_per_sample == 16) {
286                         if(encoder->protected_->blocksize <= 192)
287                                 encoder->protected_->qlp_coeff_precision = 7;
288                         else if(encoder->protected_->blocksize <= 384)
289                                 encoder->protected_->qlp_coeff_precision = 8;
290                         else if(encoder->protected_->blocksize <= 576)
291                                 encoder->protected_->qlp_coeff_precision = 9;
292                         else if(encoder->protected_->blocksize <= 1152)
293                                 encoder->protected_->qlp_coeff_precision = 10;
294                         else if(encoder->protected_->blocksize <= 2304)
295                                 encoder->protected_->qlp_coeff_precision = 11;
296                         else if(encoder->protected_->blocksize <= 4608)
297                                 encoder->protected_->qlp_coeff_precision = 12;
298                         else
299                                 encoder->protected_->qlp_coeff_precision = 13;
300                 }
301                 else {
302                         encoder->protected_->qlp_coeff_precision = min(13, 8*sizeof(FLAC__int32) - encoder->protected_->bits_per_sample - 1 - 2); /* @@@ -2 to keep things 32-bit safe */
303                 }
304         }
305         else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision + encoder->protected_->bits_per_sample >= 8*sizeof(FLAC__uint32) || encoder->protected_->qlp_coeff_precision >= (1u<<FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
306                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_QLP_COEFF_PRECISION;
307
308         if(encoder->protected_->streamable_subset) {
309                 /*@@@ add check for blocksize here */
310                 if(encoder->protected_->bits_per_sample != 8 && encoder->protected_->bits_per_sample != 12 && encoder->protected_->bits_per_sample != 16 && encoder->protected_->bits_per_sample != 20 && encoder->protected_->bits_per_sample != 24)
311                         return encoder->protected_->state = FLAC__STREAM_ENCODER_NOT_STREAMABLE;
312                 if(encoder->protected_->sample_rate > 655350)
313                         return encoder->protected_->state = FLAC__STREAM_ENCODER_NOT_STREAMABLE;
314         }
315
316         if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
317                 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
318         if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
319                 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
320
321         encoder->private_->input_capacity = 0;
322         for(i = 0; i < encoder->protected_->channels; i++) {
323                 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
324                 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
325         }
326         for(i = 0; i < 2; i++) {
327                 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
328                 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
329         }
330         for(i = 0; i < encoder->protected_->channels; i++) {
331                 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
332                 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
333                 encoder->private_->best_subframe[i] = 0;
334         }
335         for(i = 0; i < 2; i++) {
336                 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
337                 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
338                 encoder->private_->best_subframe_mid_side[i] = 0;
339         }
340         for(i = 0; i < encoder->protected_->channels; i++) {
341                 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
342                 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
343         }
344         for(i = 0; i < 2; i++) {
345                 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
346                 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
347         }
348         encoder->private_->abs_residual_unaligned = encoder->private_->abs_residual = 0;
349         encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
350         encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
351         encoder->private_->loose_mid_side_stereo_frames_exact = (double)encoder->protected_->sample_rate * 0.4 / (double)encoder->protected_->blocksize;
352         encoder->private_->loose_mid_side_stereo_frames = (unsigned)(encoder->private_->loose_mid_side_stereo_frames_exact + 0.5);
353         if(encoder->private_->loose_mid_side_stereo_frames == 0)
354                 encoder->private_->loose_mid_side_stereo_frames = 1;
355         encoder->private_->loose_mid_side_stereo_frame_count = 0;
356         encoder->private_->current_sample_number = 0;
357         encoder->private_->current_frame_number = 0;
358
359         encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
360         encoder->private_->use_wide_by_order = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(max(encoder->protected_->max_lpc_order, FLAC__MAX_FIXED_ORDER))+1 > 30); /*@@@ need to use this? */
361         encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
362
363         /*
364          * get the CPU info and set the function pointers
365          */
366         FLAC__cpu_info(&encoder->private_->cpuinfo);
367         /* first default to the non-asm routines */
368         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
369         encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
370         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
371         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
372         /* now override with asm where appropriate */
373 #ifndef FLAC__NO_ASM
374         if(encoder->private_->cpuinfo.use_asm) {
375 #ifdef FLAC__CPU_IA32
376                 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
377 #ifdef FLAC__HAS_NASM
378                 if(0 && encoder->private_->cpuinfo.data.ia32.sse) {
379                         if(encoder->protected_->max_lpc_order < 4)
380                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
381                         else if(encoder->protected_->max_lpc_order < 8)
382                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
383                         else if(encoder->protected_->max_lpc_order < 12)
384                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
385                         else
386                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
387                 }
388                 else if(0 && encoder->private_->cpuinfo.data.ia32._3dnow) /*@@@ turn back on in first beta after 1.0 */
389                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
390                 else
391                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
392                 if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
393                         encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
394                 if(encoder->private_->cpuinfo.data.ia32.mmx) {
395                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
396                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
397                 }
398                 else {
399                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
400                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
401                 }
402 #endif
403 #endif
404         }
405 #endif
406         /* finally override based on wide-ness if necessary */
407         if(encoder->private_->use_wide_by_block) {
408                 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
409         }
410
411         /* we require precompute_partition_sums if do_escape_coding because of their intertwined nature */
412         encoder->private_->precompute_partition_sums = (encoder->protected_->max_residual_partition_order > encoder->protected_->min_residual_partition_order) || encoder->protected_->do_escape_coding;
413
414         if(!stream_encoder_resize_buffers_(encoder, encoder->protected_->blocksize)) {
415                 /* the above function sets the state for us in case of an error */
416                 return encoder->protected_->state;
417         }
418         FLAC__bitbuffer_init(&encoder->private_->frame);
419
420         /*
421          * write the stream header
422          */
423
424         if(!FLAC__bitbuffer_clear(&encoder->private_->frame))
425                 return encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
426         if(!FLAC__bitbuffer_write_raw_uint32(&encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN))
427                 return encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
428
429         encoder->private_->metadata.type = FLAC__METADATA_TYPE_STREAMINFO;
430         encoder->private_->metadata.is_last = (encoder->protected_->seek_table == 0 && encoder->protected_->padding == 0 && encoder->protected_->last_metadata_is_last);
431         encoder->private_->metadata.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
432         encoder->private_->metadata.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
433         encoder->private_->metadata.data.stream_info.max_blocksize = encoder->protected_->blocksize;
434         encoder->private_->metadata.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
435         encoder->private_->metadata.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
436         encoder->private_->metadata.data.stream_info.sample_rate = encoder->protected_->sample_rate;
437         encoder->private_->metadata.data.stream_info.channels = encoder->protected_->channels;
438         encoder->private_->metadata.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
439         encoder->private_->metadata.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
440         memset(encoder->private_->metadata.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
441         MD5Init(&encoder->private_->md5context);
442         if(!FLAC__add_metadata_block(&encoder->private_->metadata, &encoder->private_->frame))
443                 return encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
444
445         if(0 != encoder->protected_->seek_table) {
446                 if(!FLAC__seek_table_is_valid(encoder->protected_->seek_table))
447                         return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_SEEK_TABLE;
448                 seek_table_block.type = FLAC__METADATA_TYPE_SEEKTABLE;
449                 seek_table_block.is_last = (encoder->protected_->padding == 0 && encoder->protected_->last_metadata_is_last);
450                 seek_table_block.length = encoder->protected_->seek_table->num_points * FLAC__STREAM_METADATA_SEEKPOINT_LEN;
451                 seek_table_block.data.seek_table = *encoder->protected_->seek_table;
452                 if(!FLAC__add_metadata_block(&seek_table_block, &encoder->private_->frame))
453                         return encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
454         }
455
456         /* add a PADDING block if requested */
457         if(encoder->protected_->padding > 0) {
458                 padding_block.type = FLAC__METADATA_TYPE_PADDING;
459                 padding_block.is_last = encoder->protected_->last_metadata_is_last;
460                 padding_block.length = encoder->protected_->padding;
461                 if(!FLAC__add_metadata_block(&padding_block, &encoder->private_->frame))
462                         return encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
463         }
464
465         FLAC__ASSERT(encoder->private_->frame.bits == 0); /* assert that we're byte-aligned before writing */
466         FLAC__ASSERT(encoder->private_->frame.total_consumed_bits == 0); /* assert that no reading of the buffer was done */
467         if(encoder->private_->write_callback(encoder, encoder->private_->frame.buffer, encoder->private_->frame.bytes, 0, encoder->private_->current_frame_number, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_OK)
468                 return encoder->protected_->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_WRITING;
469
470         /* now that the metadata block is written, we can init this to an absurdly-high value... */
471         encoder->private_->metadata.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
472         /* ... and clear this to 0 */
473         encoder->private_->metadata.data.stream_info.total_samples = 0;
474
475         return encoder->protected_->state;
476 }
477
478 void FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
479 {
480         unsigned i, channel;
481
482         FLAC__ASSERT(encoder != 0);
483         if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
484                 return;
485         if(encoder->private_->current_sample_number != 0) {
486                 encoder->protected_->blocksize = encoder->private_->current_sample_number;
487                 stream_encoder_process_frame_(encoder, true); /* true => is last frame */
488         }
489         MD5Final(encoder->private_->metadata.data.stream_info.md5sum, &encoder->private_->md5context);
490         encoder->private_->metadata_callback(encoder, &encoder->private_->metadata, encoder->private_->client_data);
491         for(i = 0; i < encoder->protected_->channels; i++) {
492                 if(encoder->private_->integer_signal_unaligned[i] != 0) {
493                         free(encoder->private_->integer_signal_unaligned[i]);
494                         encoder->private_->integer_signal_unaligned[i] = 0;
495                 }
496                 if(encoder->private_->real_signal_unaligned[i] != 0) {
497                         free(encoder->private_->real_signal_unaligned[i]);
498                         encoder->private_->real_signal_unaligned[i] = 0;
499                 }
500         }
501         for(i = 0; i < 2; i++) {
502                 if(encoder->private_->integer_signal_mid_side_unaligned[i] != 0) {
503                         free(encoder->private_->integer_signal_mid_side_unaligned[i]);
504                         encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
505                 }
506                 if(encoder->private_->real_signal_mid_side_unaligned[i] != 0) {
507                         free(encoder->private_->real_signal_mid_side_unaligned[i]);
508                         encoder->private_->real_signal_mid_side_unaligned[i] = 0;
509                 }
510         }
511         for(channel = 0; channel < encoder->protected_->channels; channel++) {
512                 for(i = 0; i < 2; i++) {
513                         if(encoder->private_->residual_workspace_unaligned[channel][i] != 0) {
514                                 free(encoder->private_->residual_workspace_unaligned[channel][i]);
515                                 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
516                         }
517                 }
518         }
519         for(channel = 0; channel < 2; channel++) {
520                 for(i = 0; i < 2; i++) {
521                         if(encoder->private_->residual_workspace_mid_side_unaligned[channel][i] != 0) {
522                                 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
523                                 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
524                         }
525                 }
526         }
527         if(encoder->private_->abs_residual_unaligned != 0) {
528                 free(encoder->private_->abs_residual_unaligned);
529                 encoder->private_->abs_residual_unaligned = 0;
530         }
531         if(encoder->private_->abs_residual_partition_sums_unaligned != 0) {
532                 free(encoder->private_->abs_residual_partition_sums_unaligned);
533                 encoder->private_->abs_residual_partition_sums_unaligned = 0;
534         }
535         if(encoder->private_->raw_bits_per_partition_unaligned != 0) {
536                 free(encoder->private_->raw_bits_per_partition_unaligned);
537                 encoder->private_->raw_bits_per_partition_unaligned = 0;
538         }
539         FLAC__bitbuffer_free(&encoder->private_->frame);
540
541         encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
542 }
543
544 FLAC__bool FLAC__stream_encoder_set_streamable_subset(const FLAC__StreamEncoder *encoder, FLAC__bool value)
545 {
546         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
547                 return false;
548         encoder->protected_->streamable_subset = value;
549         return true;
550 }
551
552 FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(const FLAC__StreamEncoder *encoder, FLAC__bool value)
553 {
554         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
555                 return false;
556         encoder->protected_->do_mid_side_stereo = value;
557         return true;
558 }
559
560 FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder, FLAC__bool value)
561 {
562         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
563                 return false;
564         encoder->protected_->loose_mid_side_stereo = value;
565         return true;
566 }
567
568 FLAC__bool FLAC__stream_encoder_set_channels(const FLAC__StreamEncoder *encoder, unsigned value)
569 {
570         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
571                 return false;
572         encoder->protected_->channels = value;
573         return true;
574 }
575
576 FLAC__bool FLAC__stream_encoder_set_bits_per_sample(const FLAC__StreamEncoder *encoder, unsigned value)
577 {
578         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
579                 return false;
580         encoder->protected_->bits_per_sample = value;
581         return true;
582 }
583
584 FLAC__bool FLAC__stream_encoder_set_sample_rate(const FLAC__StreamEncoder *encoder, unsigned value)
585 {
586         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
587                 return false;
588         encoder->protected_->sample_rate = value;
589         return true;
590 }
591
592 FLAC__bool FLAC__stream_encoder_set_blocksize(const FLAC__StreamEncoder *encoder, unsigned value)
593 {
594         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
595                 return false;
596         encoder->protected_->blocksize = value;
597         return true;
598 }
599
600 FLAC__bool FLAC__stream_encoder_set_max_lpc_order(const FLAC__StreamEncoder *encoder, unsigned value)
601 {
602         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
603                 return false;
604         encoder->protected_->max_lpc_order = value;
605         return true;
606 }
607
608 FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(const FLAC__StreamEncoder *encoder, unsigned value)
609 {
610         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
611                 return false;
612         encoder->protected_->qlp_coeff_precision = value;
613         return true;
614 }
615
616 FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder, FLAC__bool value)
617 {
618         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
619                 return false;
620         encoder->protected_->do_qlp_coeff_prec_search = value;
621         return true;
622 }
623
624 FLAC__bool FLAC__stream_encoder_set_do_escape_coding(const FLAC__StreamEncoder *encoder, FLAC__bool value)
625 {
626         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
627                 return false;
628         encoder->protected_->do_escape_coding = value;
629         return true;
630 }
631
632 FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder, FLAC__bool value)
633 {
634         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
635                 return false;
636         encoder->protected_->do_exhaustive_model_search = value;
637         return true;
638 }
639
640 FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(const FLAC__StreamEncoder *encoder, unsigned value)
641 {
642         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
643                 return false;
644         encoder->protected_->min_residual_partition_order = value;
645         return true;
646 }
647
648 FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(const FLAC__StreamEncoder *encoder, unsigned value)
649 {
650         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
651                 return false;
652         encoder->protected_->max_residual_partition_order = value;
653         return true;
654 }
655
656 FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder, unsigned value)
657 {
658         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
659                 return false;
660         encoder->protected_->rice_parameter_search_dist = value;
661         return true;
662 }
663
664 FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(const FLAC__StreamEncoder *encoder, FLAC__uint64 value)
665 {
666         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
667                 return false;
668         encoder->protected_->total_samples_estimate = value;
669         return true;
670 }
671
672 FLAC__bool FLAC__stream_encoder_set_seek_table(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetaData_SeekTable *value)
673 {
674         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
675                 return false;
676         encoder->protected_->seek_table = value;
677         return true;
678 }
679
680 FLAC__bool FLAC__stream_encoder_set_padding(const FLAC__StreamEncoder *encoder, unsigned value)
681 {
682         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
683                 return false;
684         encoder->protected_->padding = value;
685         return true;
686 }
687
688 FLAC__bool FLAC__stream_encoder_set_last_metadata_is_last(const FLAC__StreamEncoder *encoder, FLAC__bool value)
689 {
690         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
691                 return false;
692         encoder->protected_->last_metadata_is_last = value;
693         return true;
694 }
695
696 FLAC__bool FLAC__stream_encoder_set_write_callback(const FLAC__StreamEncoder *encoder, FLAC__StreamEncoderWriteStatus (*value)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data))
697 {
698         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
699                 return false;
700         encoder->private_->write_callback = value;
701         return true;
702 }
703
704 FLAC__bool FLAC__stream_encoder_set_metadata_callback(const FLAC__StreamEncoder *encoder, void (*value)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data))
705 {
706         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
707                 return false;
708         encoder->private_->metadata_callback = value;
709         return true;
710 }
711
712 FLAC__bool FLAC__stream_encoder_set_client_data(const FLAC__StreamEncoder *encoder, void *value)
713 {
714         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
715                 return false;
716         encoder->private_->client_data = value;
717         return true;
718 }
719
720 FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
721 {
722         return encoder->protected_->state;
723 }
724
725 FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
726 {
727         return encoder->protected_->streamable_subset;
728 }
729
730 FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
731 {
732         return encoder->protected_->do_mid_side_stereo;
733 }
734
735 FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
736 {
737         return encoder->protected_->loose_mid_side_stereo;
738 }
739
740 unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
741 {
742         return encoder->protected_->channels;
743 }
744
745 unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
746 {
747         return encoder->protected_->bits_per_sample;
748 }
749
750 unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
751 {
752         return encoder->protected_->sample_rate;
753 }
754
755 unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
756 {
757         return encoder->protected_->blocksize;
758 }
759
760 unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
761 {
762         return encoder->protected_->max_lpc_order;
763 }
764
765 unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
766 {
767         return encoder->protected_->qlp_coeff_precision;
768 }
769
770 FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
771 {
772         return encoder->protected_->do_qlp_coeff_prec_search;
773 }
774
775 FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
776 {
777         return encoder->protected_->do_escape_coding;
778 }
779
780 FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
781 {
782         return encoder->protected_->do_exhaustive_model_search;
783 }
784
785 unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
786 {
787         return encoder->protected_->min_residual_partition_order;
788 }
789
790 unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
791 {
792         return encoder->protected_->max_residual_partition_order;
793 }
794
795 unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
796 {
797         return encoder->protected_->rice_parameter_search_dist;
798 }
799
800 FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 *buf[], unsigned samples)
801 {
802         unsigned i, j, channel;
803         FLAC__int32 x, mid, side;
804         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
805
806         FLAC__ASSERT(encoder != 0);
807         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
808
809         j = 0;
810         if(encoder->protected_->do_mid_side_stereo && channels == 2) {
811                 do {
812                         for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
813                                 x = mid = side = buf[0][j];
814                                 encoder->private_->integer_signal[0][i] = x;
815                                 encoder->private_->real_signal[0][i] = (FLAC__real)x;
816                                 x = buf[1][j];
817                                 encoder->private_->integer_signal[1][i] = x;
818                                 encoder->private_->real_signal[1][i] = (FLAC__real)x;
819                                 mid += x;
820                                 side -= x;
821                                 mid >>= 1; /* NOTE: not the same as 'mid = (buf[0][j] + buf[1][j]) / 2' ! */
822                                 encoder->private_->integer_signal_mid_side[1][i] = side;
823                                 encoder->private_->integer_signal_mid_side[0][i] = mid;
824                                 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
825                                 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
826                                 encoder->private_->current_sample_number++;
827                         }
828                         if(i == blocksize) {
829                                 if(!stream_encoder_process_frame_(encoder, false)) /* false => not last frame */
830                                         return false;
831                         }
832                 } while(j < samples);
833         }
834         else {
835                 do {
836                         for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
837                                 for(channel = 0; channel < channels; channel++) {
838                                         x = buf[channel][j];
839                                         encoder->private_->integer_signal[channel][i] = x;
840                                         encoder->private_->real_signal[channel][i] = (FLAC__real)x;
841                                 }
842                                 encoder->private_->current_sample_number++;
843                         }
844                         if(i == blocksize) {
845                                 if(!stream_encoder_process_frame_(encoder, false)) /* false => not last frame */
846                                         return false;
847                         }
848                 } while(j < samples);
849         }
850
851         return true;
852 }
853
854 /* 'samples' is channel-wide samples, e.g. for 1 second at 44100Hz, 'samples' = 44100 regardless of the number of channels */
855 FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buf[], unsigned samples)
856 {
857         unsigned i, j, k, channel;
858         FLAC__int32 x, mid, side;
859         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
860
861         FLAC__ASSERT(encoder != 0);
862         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
863
864         j = k = 0;
865         if(encoder->protected_->do_mid_side_stereo && channels == 2) {
866                 do {
867                         for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
868                                 x = mid = side = buf[k++];
869                                 encoder->private_->integer_signal[0][i] = x;
870                                 encoder->private_->real_signal[0][i] = (FLAC__real)x;
871                                 x = buf[k++];
872                                 encoder->private_->integer_signal[1][i] = x;
873                                 encoder->private_->real_signal[1][i] = (FLAC__real)x;
874                                 mid += x;
875                                 side -= x;
876                                 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
877                                 encoder->private_->integer_signal_mid_side[1][i] = side;
878                                 encoder->private_->integer_signal_mid_side[0][i] = mid;
879                                 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
880                                 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
881                                 encoder->private_->current_sample_number++;
882                         }
883                         if(i == blocksize) {
884                                 if(!stream_encoder_process_frame_(encoder, false)) /* false => not last frame */
885                                         return false;
886                         }
887                 } while(j < samples);
888         }
889         else {
890                 do {
891                         for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
892                                 for(channel = 0; channel < channels; channel++) {
893                                         x = buf[k++];
894                                         encoder->private_->integer_signal[channel][i] = x;
895                                         encoder->private_->real_signal[channel][i] = (FLAC__real)x;
896                                 }
897                                 encoder->private_->current_sample_number++;
898                         }
899                         if(i == blocksize) {
900                                 if(!stream_encoder_process_frame_(encoder, false)) /* false => not last frame */
901                                         return false;
902                         }
903                 } while(j < samples);
904         }
905
906         return true;
907 }
908
909 FLAC__bool stream_encoder_resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_size)
910 {
911         FLAC__bool ok;
912         unsigned i, channel;
913
914         FLAC__ASSERT(new_size > 0);
915         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
916         FLAC__ASSERT(encoder->private_->current_sample_number == 0);
917
918         /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
919         if(new_size <= encoder->private_->input_capacity)
920                 return true;
921
922         ok = true;
923
924         /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx() requires that the input arrays (in our case the integer signals) have a buffer of up to 3 zeroes in front (at negative indices) for alignment purposes; we use 4 to keep the data well-aligned. */
925
926         for(i = 0; ok && i < encoder->protected_->channels; i++) {
927                 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size+4, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
928                 ok = ok && FLAC__memory_alloc_aligned_real_array(new_size, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
929                 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
930                 encoder->private_->integer_signal[i] += 4;
931         }
932         for(i = 0; ok && i < 2; i++) {
933                 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size+4, &encoder->private_->integer_signal_mid_side_unaligned[i], &encoder->private_->integer_signal_mid_side[i]);
934                 ok = ok && FLAC__memory_alloc_aligned_real_array(new_size, &encoder->private_->real_signal_mid_side_unaligned[i], &encoder->private_->real_signal_mid_side[i]);
935                 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
936                 encoder->private_->integer_signal_mid_side[i] += 4;
937         }
938         for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
939                 for(i = 0; ok && i < 2; i++) {
940                         ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
941                 }
942         }
943         for(channel = 0; ok && channel < 2; channel++) {
944                 for(i = 0; ok && i < 2; i++) {
945                         ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size, &encoder->private_->residual_workspace_mid_side_unaligned[channel][i], &encoder->private_->residual_workspace_mid_side[channel][i]);
946                 }
947         }
948         ok = ok && FLAC__memory_alloc_aligned_uint32_array(new_size, &encoder->private_->abs_residual_unaligned, &encoder->private_->abs_residual);
949         if(encoder->private_->precompute_partition_sums || encoder->protected_->do_escape_coding) /* we require precompute_partition_sums if do_escape_coding because of their intertwined nature */
950                 ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_size * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
951         if(encoder->protected_->do_escape_coding)
952                 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_size * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
953
954         if(ok)
955                 encoder->private_->input_capacity = new_size;
956         else
957                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
958
959         return ok;
960 }
961
962 /***********************************************************************
963  *
964  * Private class methods
965  *
966  ***********************************************************************/
967
968 FLAC__bool stream_encoder_process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame)
969 {
970         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
971
972         /*
973          * Accumulate raw signal to the MD5 signature
974          */
975         /* NOTE: some versions of GCC can't figure out const-ness right and will give you an 'incompatible pointer type' warning on arg 2 here: */
976         if(!FLAC__MD5Accumulate(&encoder->private_->md5context, encoder->private_->integer_signal, encoder->protected_->channels, encoder->protected_->blocksize, (encoder->protected_->bits_per_sample+7) / 8)) {
977                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
978                 return false;
979         }
980
981         /*
982          * Process the frame header and subframes into the frame bitbuffer
983          */
984         if(!stream_encoder_process_subframes_(encoder, is_last_frame)) {
985                 /* the above function sets the state for us in case of an error */
986                 return false;
987         }
988
989         /*
990          * Zero-pad the frame to a byte_boundary
991          */
992         if(!FLAC__bitbuffer_zero_pad_to_byte_boundary(&encoder->private_->frame)) {
993                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
994                 return false;
995         }
996
997         /*
998          * CRC-16 the whole thing
999          */
1000         FLAC__ASSERT(encoder->private_->frame.bits == 0); /* assert that we're byte-aligned */
1001         FLAC__ASSERT(encoder->private_->frame.total_consumed_bits == 0); /* assert that no reading of the buffer was done */
1002         FLAC__bitbuffer_write_raw_uint32(&encoder->private_->frame, FLAC__crc16(encoder->private_->frame.buffer, encoder->private_->frame.bytes), FLAC__FRAME_FOOTER_CRC_LEN);
1003
1004         /*
1005          * Write it
1006          */
1007         if(encoder->private_->write_callback(encoder, encoder->private_->frame.buffer, encoder->private_->frame.bytes, encoder->protected_->blocksize, encoder->private_->current_frame_number, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_OK) {
1008                 encoder->protected_->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_WRITING;
1009                 return false;
1010         }
1011
1012         /*
1013          * Get ready for the next frame
1014          */
1015         encoder->private_->current_sample_number = 0;
1016         encoder->private_->current_frame_number++;
1017         encoder->private_->metadata.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
1018         encoder->private_->metadata.data.stream_info.min_framesize = min(encoder->private_->frame.bytes, encoder->private_->metadata.data.stream_info.min_framesize);
1019         encoder->private_->metadata.data.stream_info.max_framesize = max(encoder->private_->frame.bytes, encoder->private_->metadata.data.stream_info.max_framesize);
1020
1021         return true;
1022 }
1023
1024 FLAC__bool stream_encoder_process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame)
1025 {
1026         FLAC__FrameHeader frame_header;
1027         unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
1028         FLAC__bool do_independent, do_mid_side, precompute_partition_sums;
1029
1030         /*
1031          * Calculate the min,max Rice partition orders
1032          */
1033         if(is_last_frame) {
1034                 max_partition_order = 0;
1035         }
1036         else {
1037                 unsigned limit = 0, b = encoder->protected_->blocksize;
1038                 while(!(b & 1)) {
1039                         limit++;
1040                         b >>= 1;
1041                 }
1042                 max_partition_order = min(encoder->protected_->max_residual_partition_order, limit);
1043         }
1044         min_partition_order = min(min_partition_order, max_partition_order);
1045
1046         precompute_partition_sums = encoder->private_->precompute_partition_sums && ((max_partition_order > min_partition_order) || encoder->protected_->do_escape_coding);
1047
1048         /*
1049          * Setup the frame
1050          */
1051         if(!FLAC__bitbuffer_clear(&encoder->private_->frame)) {
1052                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1053                 return false;
1054         }
1055         frame_header.blocksize = encoder->protected_->blocksize;
1056         frame_header.sample_rate = encoder->protected_->sample_rate;
1057         frame_header.channels = encoder->protected_->channels;
1058         frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
1059         frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
1060         frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
1061         frame_header.number.frame_number = encoder->private_->current_frame_number;
1062
1063         /*
1064          * Figure out what channel assignments to try
1065          */
1066         if(encoder->protected_->do_mid_side_stereo) {
1067                 if(encoder->protected_->loose_mid_side_stereo) {
1068                         if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
1069                                 do_independent = true;
1070                                 do_mid_side = true;
1071                         }
1072                         else {
1073                                 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
1074                                 do_mid_side = !do_independent;
1075                         }
1076                 }
1077                 else {
1078                         do_independent = true;
1079                         do_mid_side = true;
1080                 }
1081         }
1082         else {
1083                 do_independent = true;
1084                 do_mid_side = false;
1085         }
1086
1087         FLAC__ASSERT(do_independent || do_mid_side);
1088
1089         /*
1090          * Check for wasted bits; set effective bps for each subframe
1091          */
1092         if(do_independent) {
1093                 unsigned w;
1094                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
1095                         w = stream_encoder_get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
1096                         encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
1097                         encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
1098                 }
1099         }
1100         if(do_mid_side) {
1101                 unsigned w;
1102                 FLAC__ASSERT(encoder->protected_->channels == 2);
1103                 for(channel = 0; channel < 2; channel++) {
1104                         w = stream_encoder_get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
1105                         encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
1106                         encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
1107                 }
1108         }
1109
1110         /*
1111          * First do a normal encoding pass of each independent channel
1112          */
1113         if(do_independent) {
1114                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
1115                         if(!stream_encoder_process_subframe_(encoder, min_partition_order, max_partition_order, precompute_partition_sums, false, &frame_header, encoder->private_->subframe_bps[channel], encoder->private_->integer_signal[channel], encoder->private_->real_signal[channel], encoder->private_->subframe_workspace_ptr[channel], encoder->private_->residual_workspace[channel], encoder->private_->best_subframe+channel, encoder->private_->best_subframe_bits+channel))
1116                                 return false;
1117                 }
1118         }
1119
1120         /*
1121          * Now do mid and side channels if requested
1122          */
1123         if(do_mid_side) {
1124                 FLAC__ASSERT(encoder->protected_->channels == 2);
1125
1126                 for(channel = 0; channel < 2; channel++) {
1127                         if(!stream_encoder_process_subframe_(encoder, min_partition_order, max_partition_order, precompute_partition_sums, false, &frame_header, encoder->private_->subframe_bps_mid_side[channel], encoder->private_->integer_signal_mid_side[channel], encoder->private_->real_signal_mid_side[channel], encoder->private_->subframe_workspace_ptr_mid_side[channel], encoder->private_->residual_workspace_mid_side[channel], encoder->private_->best_subframe_mid_side+channel, encoder->private_->best_subframe_bits_mid_side+channel))
1128                                 return false;
1129                 }
1130         }
1131
1132         /*
1133          * Compose the frame bitbuffer
1134          */
1135         if(do_mid_side) {
1136                 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
1137                 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
1138                 FLAC__ChannelAssignment channel_assignment;
1139
1140                 FLAC__ASSERT(encoder->protected_->channels == 2);
1141
1142                 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
1143                         channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
1144                 }
1145                 else {
1146                         unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
1147                         unsigned min_bits;
1148                         FLAC__ChannelAssignment ca;
1149
1150                         FLAC__ASSERT(do_independent && do_mid_side);
1151
1152                         /* We have to figure out which channel assignent results in the smallest frame */
1153                         bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits         [1];
1154                         bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE  ] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits_mid_side[1];
1155                         bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits         [1] + encoder->private_->best_subframe_bits_mid_side[1];
1156                         bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE   ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
1157
1158                         for(channel_assignment = 0, min_bits = bits[0], ca = 1; ca <= 3; ca++) {
1159                                 if(bits[ca] < min_bits) {
1160                                         min_bits = bits[ca];
1161                                         channel_assignment = ca;
1162                                 }
1163                         }
1164                 }
1165
1166                 frame_header.channel_assignment = channel_assignment;
1167
1168                 if(!FLAC__frame_add_header(&frame_header, encoder->protected_->streamable_subset, is_last_frame, &encoder->private_->frame)) {
1169                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1170                         return false;
1171                 }
1172
1173                 switch(channel_assignment) {
1174                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1175                                 left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
1176                                 right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
1177                                 break;
1178                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1179                                 left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
1180                                 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
1181                                 break;
1182                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1183                                 left_subframe  = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
1184                                 right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
1185                                 break;
1186                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1187                                 left_subframe  = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
1188                                 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
1189                                 break;
1190                         default:
1191                                 FLAC__ASSERT(0);
1192                 }
1193
1194                 switch(channel_assignment) {
1195                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1196                                 left_bps  = encoder->private_->subframe_bps         [0];
1197                                 right_bps = encoder->private_->subframe_bps         [1];
1198                                 break;
1199                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1200                                 left_bps  = encoder->private_->subframe_bps         [0];
1201                                 right_bps = encoder->private_->subframe_bps_mid_side[1];
1202                                 break;
1203                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1204                                 left_bps  = encoder->private_->subframe_bps_mid_side[1];
1205                                 right_bps = encoder->private_->subframe_bps         [1];
1206                                 break;
1207                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1208                                 left_bps  = encoder->private_->subframe_bps_mid_side[0];
1209                                 right_bps = encoder->private_->subframe_bps_mid_side[1];
1210                                 break;
1211                         default:
1212                                 FLAC__ASSERT(0);
1213                 }
1214
1215                 /* note that encoder_add_subframe_ sets the state for us in case of an error */
1216                 if(!stream_encoder_add_subframe_(encoder, &frame_header, left_bps , left_subframe , &encoder->private_->frame))
1217                         return false;
1218                 if(!stream_encoder_add_subframe_(encoder, &frame_header, right_bps, right_subframe, &encoder->private_->frame))
1219                         return false;
1220         }
1221         else {
1222                 if(!FLAC__frame_add_header(&frame_header, encoder->protected_->streamable_subset, is_last_frame, &encoder->private_->frame)) {
1223                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1224                         return false;
1225                 }
1226
1227                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
1228                         if(!stream_encoder_add_subframe_(encoder, &frame_header, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], &encoder->private_->frame)) {
1229                                 /* the above function sets the state for us in case of an error */
1230                                 return false;
1231                         }
1232                 }
1233         }
1234
1235         if(encoder->protected_->loose_mid_side_stereo) {
1236                 encoder->private_->loose_mid_side_stereo_frame_count++;
1237                 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
1238                         encoder->private_->loose_mid_side_stereo_frame_count = 0;
1239         }
1240
1241         encoder->private_->last_channel_assignment = frame_header.channel_assignment;
1242
1243         return true;
1244 }
1245
1246 FLAC__bool stream_encoder_process_subframe_(FLAC__StreamEncoder *encoder, unsigned min_partition_order, unsigned max_partition_order, FLAC__bool precompute_partition_sums, FLAC__bool verbatim_only, const FLAC__FrameHeader *frame_header, unsigned subframe_bps, const FLAC__int32 integer_signal[], const FLAC__real real_signal[], FLAC__Subframe *subframe[2], FLAC__int32 *residual[2], unsigned *best_subframe, unsigned *best_bits)
1247 {
1248         FLAC__real fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
1249         FLAC__real lpc_residual_bits_per_sample;
1250         FLAC__real autoc[FLAC__MAX_LPC_ORDER+1]; /* WATCHOUT: the size is important even though encoder->protected_->max_lpc_order might be less; some asm routines need all the space */
1251         FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER];
1252         FLAC__real lpc_error[FLAC__MAX_LPC_ORDER];
1253         unsigned min_lpc_order, max_lpc_order, lpc_order;
1254         unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
1255         unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
1256         unsigned rice_parameter;
1257         unsigned _candidate_bits, _best_bits;
1258         unsigned _best_subframe;
1259
1260         /* verbatim subframe is the baseline against which we measure other compressed subframes */
1261         _best_subframe = 0;
1262         _best_bits = stream_encoder_evaluate_verbatim_subframe_(integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
1263
1264         if(!verbatim_only && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
1265                 /* check for constant subframe */
1266                 guess_fixed_order = encoder->private_->local_fixed_compute_best_predictor(integer_signal+FLAC__MAX_FIXED_ORDER, frame_header->blocksize-FLAC__MAX_FIXED_ORDER, fixed_residual_bits_per_sample);
1267                 if(fixed_residual_bits_per_sample[1] == 0.0) {
1268                         /* the above means integer_signal+FLAC__MAX_FIXED_ORDER is constant, now we just have to check the warmup samples */
1269                         unsigned i, signal_is_constant = true;
1270                         for(i = 1; i <= FLAC__MAX_FIXED_ORDER; i++) {
1271                                 if(integer_signal[0] != integer_signal[i]) {
1272                                         signal_is_constant = false;
1273                                         break;
1274                                 }
1275                         }
1276                         if(signal_is_constant) {
1277                                 _candidate_bits = stream_encoder_evaluate_constant_subframe_(integer_signal[0], subframe_bps, subframe[!_best_subframe]);
1278                                 if(_candidate_bits < _best_bits) {
1279                                         _best_subframe = !_best_subframe;
1280                                         _best_bits = _candidate_bits;
1281                                 }
1282                         }
1283                 }
1284                 else {
1285                         /* encode fixed */
1286                         if(encoder->protected_->do_exhaustive_model_search) {
1287                                 min_fixed_order = 0;
1288                                 max_fixed_order = FLAC__MAX_FIXED_ORDER;
1289                         }
1290                         else {
1291                                 min_fixed_order = max_fixed_order = guess_fixed_order;
1292                         }
1293                         for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
1294                                 if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__real)subframe_bps)
1295                                         continue; /* don't even try */
1296                                 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 */
1297 #ifndef FLAC__SYMMETRIC_RICE
1298                                 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
1299 #endif
1300                                 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1301 #ifdef DEBUG_VERBOSE
1302                                         fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
1303 #endif
1304                                         rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1305                                 }
1306                                 _candidate_bits = stream_encoder_evaluate_fixed_subframe_(integer_signal, residual[!_best_subframe], encoder->private_->abs_residual, encoder->private_->abs_residual_partition_sums, encoder->private_->raw_bits_per_partition, frame_header->blocksize, subframe_bps, fixed_order, rice_parameter, min_partition_order, max_partition_order, precompute_partition_sums, encoder->protected_->do_escape_coding, encoder->protected_->rice_parameter_search_dist, subframe[!_best_subframe]);
1307                                 if(_candidate_bits < _best_bits) {
1308                                         _best_subframe = !_best_subframe;
1309                                         _best_bits = _candidate_bits;
1310                                 }
1311                         }
1312
1313                         /* encode lpc */
1314                         if(encoder->protected_->max_lpc_order > 0) {
1315                                 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
1316                                         max_lpc_order = frame_header->blocksize-1;
1317                                 else
1318                                         max_lpc_order = encoder->protected_->max_lpc_order;
1319                                 if(max_lpc_order > 0) {
1320                                         encoder->private_->local_lpc_compute_autocorrelation(real_signal, frame_header->blocksize, max_lpc_order+1, autoc);
1321                                         /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
1322                                         if(autoc[0] != 0.0) {
1323                                                 FLAC__lpc_compute_lp_coefficients(autoc, max_lpc_order, lp_coeff, lpc_error);
1324                                                 if(encoder->protected_->do_exhaustive_model_search) {
1325                                                         min_lpc_order = 1;
1326                                                 }
1327                                                 else {
1328                                                         unsigned guess_lpc_order = FLAC__lpc_compute_best_order(lpc_error, max_lpc_order, frame_header->blocksize, subframe_bps);
1329                                                         min_lpc_order = max_lpc_order = guess_lpc_order;
1330                                                 }
1331                                                 if(encoder->protected_->do_qlp_coeff_prec_search) {
1332                                                         min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
1333                                                         max_qlp_coeff_precision = min(8*sizeof(FLAC__int32) - subframe_bps - 1 - 2, (1u<<FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN)-1); /* -2 to keep things 32-bit safe */
1334                                                 }
1335                                                 else {
1336                                                         min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
1337                                                 }
1338                                                 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
1339                                                         lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
1340                                                         if(lpc_residual_bits_per_sample >= (FLAC__real)subframe_bps)
1341                                                                 continue; /* don't even try */
1342                                                         rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
1343 #ifndef FLAC__SYMMETRIC_RICE
1344                                                         rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
1345 #endif
1346                                                         if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1347 #ifdef DEBUG_VERBOSE
1348                                                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
1349 #endif
1350                                                                 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1351                                                         }
1352                                                         for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
1353                                                                 _candidate_bits = stream_encoder_evaluate_lpc_subframe_(encoder, integer_signal, residual[!_best_subframe], encoder->private_->abs_residual, encoder->private_->abs_residual_partition_sums, encoder->private_->raw_bits_per_partition, lp_coeff[lpc_order-1], frame_header->blocksize, subframe_bps, lpc_order, qlp_coeff_precision, rice_parameter, min_partition_order, max_partition_order, precompute_partition_sums, encoder->protected_->do_escape_coding, encoder->protected_->rice_parameter_search_dist, subframe[!_best_subframe]);
1354                                                                 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
1355                                                                         if(_candidate_bits < _best_bits) {
1356                                                                                 _best_subframe = !_best_subframe;
1357                                                                                 _best_bits = _candidate_bits;
1358                                                                         }
1359                                                                 }
1360                                                         }
1361                                                 }
1362                                         }
1363                                 }
1364                         }
1365                 }
1366         }
1367
1368         *best_subframe = _best_subframe;
1369         *best_bits = _best_bits;
1370
1371         return true;
1372 }
1373
1374 FLAC__bool stream_encoder_add_subframe_(FLAC__StreamEncoder *encoder, const FLAC__FrameHeader *frame_header, unsigned subframe_bps, const FLAC__Subframe *subframe, FLAC__BitBuffer *frame)
1375 {
1376         switch(subframe->type) {
1377                 case FLAC__SUBFRAME_TYPE_CONSTANT:
1378                         if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
1379                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING;
1380                                 return false;
1381                         }
1382                         break;
1383                 case FLAC__SUBFRAME_TYPE_FIXED:
1384                         if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), frame_header->blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
1385                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING;
1386                                 return false;
1387                         }
1388                         break;
1389                 case FLAC__SUBFRAME_TYPE_LPC:
1390                         if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), frame_header->blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
1391                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING;
1392                                 return false;
1393                         }
1394                         break;
1395                 case FLAC__SUBFRAME_TYPE_VERBATIM:
1396                         if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), frame_header->blocksize, subframe_bps, subframe->wasted_bits, frame)) {
1397                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING;
1398                                 return false;
1399                         }
1400                         break;
1401                 default:
1402                         FLAC__ASSERT(0);
1403         }
1404
1405         return true;
1406 }
1407
1408 unsigned stream_encoder_evaluate_constant_subframe_(const FLAC__int32 signal, unsigned subframe_bps, FLAC__Subframe *subframe)
1409 {
1410         subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
1411         subframe->data.constant.value = signal;
1412
1413         return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe_bps;
1414 }
1415
1416 unsigned stream_encoder_evaluate_fixed_subframe_(const FLAC__int32 signal[], FLAC__int32 residual[], FLAC__uint32 abs_residual[], FLAC__uint64 abs_residual_partition_sums[], unsigned raw_bits_per_partition[], unsigned blocksize, unsigned subframe_bps, unsigned order, unsigned rice_parameter, unsigned min_partition_order, unsigned max_partition_order, FLAC__bool precompute_partition_sums, FLAC__bool do_escape_coding, unsigned rice_parameter_search_dist, FLAC__Subframe *subframe)
1417 {
1418         unsigned i, residual_bits;
1419         const unsigned residual_samples = blocksize - order;
1420
1421         FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
1422
1423         subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
1424
1425         subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
1426         subframe->data.fixed.residual = residual;
1427
1428         residual_bits = stream_encoder_find_best_partition_order_(residual, abs_residual, abs_residual_partition_sums, raw_bits_per_partition, residual_samples, order, rice_parameter, min_partition_order, max_partition_order, precompute_partition_sums, do_escape_coding, rice_parameter_search_dist, &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);
1429
1430         subframe->data.fixed.order = order;
1431         for(i = 0; i < order; i++)
1432                 subframe->data.fixed.warmup[i] = signal[i];
1433
1434         return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (order * subframe_bps) + residual_bits;
1435 }
1436
1437 unsigned stream_encoder_evaluate_lpc_subframe_(FLAC__StreamEncoder *encoder, const FLAC__int32 signal[], FLAC__int32 residual[], FLAC__uint32 abs_residual[], FLAC__uint64 abs_residual_partition_sums[], unsigned raw_bits_per_partition[], const FLAC__real lp_coeff[], unsigned blocksize, unsigned subframe_bps, unsigned order, unsigned qlp_coeff_precision, unsigned rice_parameter, unsigned min_partition_order, unsigned max_partition_order, FLAC__bool precompute_partition_sums, FLAC__bool do_escape_coding, unsigned rice_parameter_search_dist, FLAC__Subframe *subframe)
1438 {
1439         FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
1440         unsigned i, residual_bits;
1441         int quantization, ret;
1442         const unsigned residual_samples = blocksize - order;
1443
1444         ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, subframe_bps, qlp_coeff, &quantization);
1445         if(ret != 0)
1446                 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
1447
1448         if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
1449                 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
1450         else
1451                 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
1452
1453         subframe->type = FLAC__SUBFRAME_TYPE_LPC;
1454
1455         subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
1456         subframe->data.lpc.residual = residual;
1457
1458         residual_bits = stream_encoder_find_best_partition_order_(residual, abs_residual, abs_residual_partition_sums, raw_bits_per_partition, residual_samples, order, rice_parameter, min_partition_order, max_partition_order, precompute_partition_sums, do_escape_coding, rice_parameter_search_dist, &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);
1459
1460         subframe->data.lpc.order = order;
1461         subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
1462         subframe->data.lpc.quantization_level = quantization;
1463         memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
1464         for(i = 0; i < order; i++)
1465                 subframe->data.lpc.warmup[i] = signal[i];
1466
1467         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;
1468 }
1469
1470 unsigned stream_encoder_evaluate_verbatim_subframe_(const FLAC__int32 signal[], unsigned blocksize, unsigned subframe_bps, FLAC__Subframe *subframe)
1471 {
1472         subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
1473
1474         subframe->data.verbatim.data = signal;
1475
1476         return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (blocksize * subframe_bps);
1477 }
1478
1479 unsigned stream_encoder_find_best_partition_order_(const FLAC__int32 residual[], FLAC__uint32 abs_residual[], FLAC__uint64 abs_residual_partition_sums[], unsigned raw_bits_per_partition[], unsigned residual_samples, unsigned predictor_order, unsigned rice_parameter, unsigned min_partition_order, unsigned max_partition_order, FLAC__bool precompute_partition_sums, FLAC__bool do_escape_coding, unsigned rice_parameter_search_dist, unsigned *best_partition_order, unsigned best_parameters[], unsigned best_raw_bits[])
1480 {
1481         FLAC__int32 r;
1482         unsigned residual_bits, best_residual_bits = 0;
1483         unsigned residual_sample;
1484         unsigned best_parameters_index = 0, parameters[2][1 << FLAC__MAX_RICE_PARTITION_ORDER], raw_bits[2][1 << FLAC__MAX_RICE_PARTITION_ORDER];
1485         const unsigned blocksize = residual_samples + predictor_order;
1486
1487         /* compute abs(residual) for use later */
1488         for(residual_sample = 0; residual_sample < residual_samples; residual_sample++) {
1489                 r = residual[residual_sample];
1490                 abs_residual[residual_sample] = (FLAC__uint32)(r<0? -r : r);
1491         }
1492
1493         while(max_partition_order > 0 && blocksize >> max_partition_order <= predictor_order)
1494                 max_partition_order--;
1495         FLAC__ASSERT(blocksize >> max_partition_order > predictor_order);
1496         min_partition_order = min(min_partition_order, max_partition_order);
1497
1498         if(precompute_partition_sums) {
1499                 int partition_order;
1500                 unsigned sum;
1501
1502                 stream_encoder_precompute_partition_info_sums_(abs_residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order);
1503
1504                 if(do_escape_coding)
1505                         stream_encoder_precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
1506
1507                 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
1508 #ifdef DONT_ESTIMATE_RICE_BITS
1509                         if(!stream_encoder_set_partitioned_rice_with_precompute_(residual, abs_residual_partition_sums+sum, raw_bits_per_partition+sum, residual_samples, predictor_order, rice_parameter, rice_parameter_search_dist, (unsigned)partition_order, do_escape_coding, parameters[!best_parameters_index], raw_bits[!best_parameters_index], &residual_bits))
1510 #else
1511                         if(!stream_encoder_set_partitioned_rice_with_precompute_(abs_residual, abs_residual_partition_sums+sum, raw_bits_per_partition+sum, residual_samples, predictor_order, rice_parameter, rice_parameter_search_dist, (unsigned)partition_order, do_escape_coding, parameters[!best_parameters_index], raw_bits[!best_parameters_index], &residual_bits))
1512 #endif
1513                         {
1514                                 FLAC__ASSERT(best_residual_bits != 0);
1515                                 break;
1516                         }
1517                         sum += 1u << partition_order;
1518                         if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
1519                                 best_residual_bits = residual_bits;
1520                                 *best_partition_order = partition_order;
1521                                 best_parameters_index = !best_parameters_index;
1522                         }
1523                 }
1524         }
1525         else {
1526                 unsigned partition_order;
1527                 for(partition_order = min_partition_order; partition_order <= max_partition_order; partition_order++) {
1528 #ifdef DONT_ESTIMATE_RICE_BITS
1529                         if(!stream_encoder_set_partitioned_rice_(abs_residual, residual, residual_samples, predictor_order, rice_parameter, rice_parameter_search_dist, partition_order, parameters[!best_parameters_index], &residual_bits))
1530 #else
1531                         if(!stream_encoder_set_partitioned_rice_(abs_residual, residual_samples, predictor_order, rice_parameter, rice_parameter_search_dist, partition_order, parameters[!best_parameters_index], &residual_bits))
1532 #endif
1533                         {
1534                                 FLAC__ASSERT(best_residual_bits != 0);
1535                                 break;
1536                         }
1537                         if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
1538                                 best_residual_bits = residual_bits;
1539                                 *best_partition_order = partition_order;
1540                                 best_parameters_index = !best_parameters_index;
1541                         }
1542                 }
1543         }
1544
1545         memcpy(best_parameters, parameters[best_parameters_index], sizeof(unsigned)*(1<<(*best_partition_order)));
1546         memcpy(best_raw_bits, raw_bits[best_parameters_index], sizeof(unsigned)*(1<<(*best_partition_order)));
1547
1548         return best_residual_bits;
1549 }
1550
1551 void stream_encoder_precompute_partition_info_sums_(const FLAC__uint32 abs_residual[], FLAC__uint64 abs_residual_partition_sums[], unsigned residual_samples, unsigned predictor_order, unsigned min_partition_order, unsigned max_partition_order)
1552 {
1553         int partition_order;
1554         unsigned from_partition, to_partition = 0;
1555         const unsigned blocksize = residual_samples + predictor_order;
1556
1557         /* first do max_partition_order */
1558         for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
1559                 FLAC__uint64 abs_residual_partition_sum;
1560                 FLAC__uint32 abs_r;
1561                 unsigned partition, partition_sample, partition_samples, residual_sample;
1562                 const unsigned partitions = 1u << partition_order;
1563                 const unsigned default_partition_samples = blocksize >> partition_order;
1564
1565                 FLAC__ASSERT(default_partition_samples > predictor_order);
1566
1567                 for(partition = residual_sample = 0; partition < partitions; partition++) {
1568                         partition_samples = default_partition_samples;
1569                         if(partition == 0)
1570                                 partition_samples -= predictor_order;
1571                         abs_residual_partition_sum = 0;
1572                         for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
1573                                 abs_r = abs_residual[residual_sample];
1574                                 abs_residual_partition_sum += abs_r;
1575                                 residual_sample++;
1576                         }
1577                         abs_residual_partition_sums[partition] = abs_residual_partition_sum;
1578                 }
1579                 to_partition = partitions;
1580                 break;
1581         }
1582
1583         /* now merge partitions for lower orders */
1584         for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
1585                 FLAC__uint64 s;
1586                 unsigned i;
1587                 const unsigned partitions = 1u << partition_order;
1588                 for(i = 0; i < partitions; i++) {
1589                         s = abs_residual_partition_sums[from_partition];
1590                         from_partition++;
1591                         abs_residual_partition_sums[to_partition] = s + abs_residual_partition_sums[from_partition];
1592                         from_partition++;
1593                         to_partition++;
1594                 }
1595         }
1596 }
1597
1598 void stream_encoder_precompute_partition_info_escapes_(const FLAC__int32 residual[], unsigned raw_bits_per_partition[], unsigned residual_samples, unsigned predictor_order, unsigned min_partition_order, unsigned max_partition_order)
1599 {
1600         int partition_order;
1601         unsigned from_partition, to_partition = 0;
1602         const unsigned blocksize = residual_samples + predictor_order;
1603
1604         /* first do max_partition_order */
1605         for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
1606                 FLAC__int32 r, residual_partition_min, residual_partition_max;
1607                 unsigned silog2_min, silog2_max;
1608                 unsigned partition, partition_sample, partition_samples, residual_sample;
1609                 const unsigned partitions = 1u << partition_order;
1610                 const unsigned default_partition_samples = blocksize >> partition_order;
1611
1612                 FLAC__ASSERT(default_partition_samples > predictor_order);
1613
1614                 for(partition = residual_sample = 0; partition < partitions; partition++) {
1615                         partition_samples = default_partition_samples;
1616                         if(partition == 0)
1617                                 partition_samples -= predictor_order;
1618                         residual_partition_min = residual_partition_max = 0;
1619                         for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
1620                                 r = residual[residual_sample];
1621                                 if(r < residual_partition_min)
1622                                         residual_partition_min = r;
1623                                 else if(r > residual_partition_max)
1624                                         residual_partition_max = r;
1625                                 residual_sample++;
1626                         }
1627                         silog2_min = FLAC__bitmath_silog2(residual_partition_min);
1628                         silog2_max = FLAC__bitmath_silog2(residual_partition_max);
1629                         raw_bits_per_partition[partition] = max(silog2_min, silog2_max);
1630                 }
1631                 to_partition = partitions;
1632                 break;
1633         }
1634
1635         /* now merge partitions for lower orders */
1636         for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
1637                 unsigned m;
1638                 unsigned i;
1639                 const unsigned partitions = 1u << partition_order;
1640                 for(i = 0; i < partitions; i++) {
1641                         m = raw_bits_per_partition[from_partition];
1642                         from_partition++;
1643                         raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
1644                         from_partition++;
1645                         to_partition++;
1646                 }
1647         }
1648 }
1649
1650 #ifdef VARIABLE_RICE_BITS
1651 #undef VARIABLE_RICE_BITS
1652 #endif
1653 #ifndef DONT_ESTIMATE_RICE_BITS
1654 #define VARIABLE_RICE_BITS(value, parameter) ((value) >> (parameter))
1655 #endif
1656
1657 #ifdef DONT_ESTIMATE_RICE_BITS
1658 FLAC__bool stream_encoder_set_partitioned_rice_(const FLAC__uint32 abs_residual[], const FLAC__int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned suggested_rice_parameter, const unsigned rice_parameter_search_dist, const unsigned partition_order, unsigned parameters[], unsigned *bits)
1659 #else
1660 FLAC__bool stream_encoder_set_partitioned_rice_(const FLAC__uint32 abs_residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned suggested_rice_parameter, const unsigned rice_parameter_search_dist, const unsigned partition_order, unsigned parameters[], unsigned *bits)
1661 #endif
1662 {
1663         unsigned rice_parameter, partition_bits;
1664 #ifndef NO_RICE_SEARCH
1665         unsigned best_partition_bits;
1666         unsigned min_rice_parameter, max_rice_parameter, best_rice_parameter = 0;
1667 #endif
1668         unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
1669
1670         FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
1671
1672         if(partition_order == 0) {
1673                 unsigned i;
1674
1675 #ifndef NO_RICE_SEARCH
1676                 if(rice_parameter_search_dist) {
1677                         if(suggested_rice_parameter < rice_parameter_search_dist)
1678                                 min_rice_parameter = 0;
1679                         else
1680                                 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
1681                         max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
1682                         if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1683 #ifdef DEBUG_VERBOSE
1684                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @2\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
1685 #endif
1686                                 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1687                         }
1688                 }
1689                 else
1690                         min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
1691
1692                 best_partition_bits = 0xffffffff;
1693                 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
1694 #endif
1695 #ifdef VARIABLE_RICE_BITS
1696 #ifdef FLAC__SYMMETRIC_RICE
1697                         partition_bits = (2+rice_parameter) * residual_samples;
1698 #else
1699                         const unsigned rice_parameter_estimate = rice_parameter-1;
1700                         partition_bits = (1+rice_parameter) * residual_samples;
1701 #endif
1702 #else
1703                         partition_bits = 0;
1704 #endif
1705                         partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
1706                         for(i = 0; i < residual_samples; i++) {
1707 #ifdef VARIABLE_RICE_BITS
1708 #ifdef FLAC__SYMMETRIC_RICE
1709                                 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter);
1710 #else
1711                                 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter_estimate);
1712 #endif
1713 #else
1714                                 partition_bits += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter); /* NOTE: we will need to pass in residual[] in addition to abs_residual[] */
1715 #endif
1716                         }
1717 #ifndef NO_RICE_SEARCH
1718                         if(partition_bits < best_partition_bits) {
1719                                 best_rice_parameter = rice_parameter;
1720                                 best_partition_bits = partition_bits;
1721                         }
1722                 }
1723 #endif
1724                 parameters[0] = best_rice_parameter;
1725                 bits_ += best_partition_bits;
1726         }
1727         else {
1728                 unsigned partition, residual_sample, save_residual_sample, partition_sample;
1729                 unsigned partition_samples;
1730                 FLAC__uint64 mean, k;
1731                 const unsigned partitions = 1u << partition_order;
1732                 for(partition = residual_sample = 0; partition < partitions; partition++) {
1733                         partition_samples = (residual_samples+predictor_order) >> partition_order;
1734                         if(partition == 0) {
1735                                 if(partition_samples <= predictor_order)
1736                                         return false;
1737                                 else
1738                                         partition_samples -= predictor_order;
1739                         }
1740                         mean = 0;
1741                         save_residual_sample = residual_sample;
1742                         for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++)
1743                                 mean += abs_residual[residual_sample];
1744                         residual_sample = save_residual_sample;
1745 #ifdef FLAC__SYMMETRIC_RICE
1746                         mean += partition_samples >> 1; /* for rounding effect */
1747                         mean /= partition_samples;
1748
1749                         /* calc rice_parameter = floor(log2(mean)) */
1750                         rice_parameter = 0;
1751                         mean>>=1;
1752                         while(mean) {
1753                                 rice_parameter++;
1754                                 mean >>= 1;
1755                         }
1756 #else
1757                         /* calc rice_parameter ala LOCO-I */
1758                         for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
1759                                 ;
1760 #endif
1761                         if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1762 #ifdef DEBUG_VERBOSE
1763                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @3\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
1764 #endif
1765                                 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1766                         }
1767
1768 #ifndef NO_RICE_SEARCH
1769                         if(rice_parameter_search_dist) {
1770                                 if(rice_parameter < rice_parameter_search_dist)
1771                                         min_rice_parameter = 0;
1772                                 else
1773                                         min_rice_parameter = rice_parameter - rice_parameter_search_dist;
1774                                 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
1775                                 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1776 #ifdef DEBUG_VERBOSE
1777                                         fprintf(stderr, "clipping rice_parameter (%u -> %u) @4\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
1778 #endif
1779                                         max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1780                                 }
1781                         }
1782                         else
1783                                 min_rice_parameter = max_rice_parameter = rice_parameter;
1784
1785                         best_partition_bits = 0xffffffff;
1786                         for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
1787 #endif
1788 #ifdef VARIABLE_RICE_BITS
1789 #ifdef FLAC__SYMMETRIC_RICE
1790                                 partition_bits = (2+rice_parameter) * partition_samples;
1791 #else
1792                                 const unsigned rice_parameter_estimate = rice_parameter-1;
1793                                 partition_bits = (1+rice_parameter) * partition_samples;
1794 #endif
1795 #else
1796                                 partition_bits = 0;
1797 #endif
1798                                 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
1799                                 save_residual_sample = residual_sample;
1800                                 for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++) {
1801 #ifdef VARIABLE_RICE_BITS
1802 #ifdef FLAC__SYMMETRIC_RICE
1803                                         partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter);
1804 #else
1805                                         partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter_estimate);
1806 #endif
1807 #else
1808                                         partition_bits += FLAC__bitbuffer_rice_bits(residual[residual_sample], rice_parameter); /* NOTE: we will need to pass in residual[] in addition to abs_residual[] */
1809 #endif
1810                                 }
1811 #ifndef NO_RICE_SEARCH
1812                                 if(rice_parameter != max_rice_parameter)
1813                                         residual_sample = save_residual_sample;
1814                                 if(partition_bits < best_partition_bits) {
1815                                         best_rice_parameter = rice_parameter;
1816                                         best_partition_bits = partition_bits;
1817                                 }
1818                         }
1819 #endif
1820                         parameters[partition] = best_rice_parameter;
1821                         bits_ += best_partition_bits;
1822                 }
1823         }
1824
1825         *bits = bits_;
1826         return true;
1827 }
1828
1829 #ifdef DONT_ESTIMATE_RICE_BITS
1830 FLAC__bool stream_encoder_set_partitioned_rice_with_precompute_(const FLAC__int32 residual[], const FLAC__uint64 abs_residual_partition_sums[], const unsigned raw_bits_per_partition[], const unsigned residual_samples, const unsigned predictor_order, const unsigned suggested_rice_parameter, const unsigned rice_parameter_search_dist, const unsigned partition_order, const FLAC__bool search_for_escapes, unsigned parameters[], unsigned raw_bits[], unsigned *bits)
1831 #else
1832 FLAC__bool stream_encoder_set_partitioned_rice_with_precompute_(const FLAC__uint32 abs_residual[], const FLAC__uint64 abs_residual_partition_sums[], const unsigned raw_bits_per_partition[], const unsigned residual_samples, const unsigned predictor_order, const unsigned suggested_rice_parameter, const unsigned rice_parameter_search_dist, const unsigned partition_order, const FLAC__bool search_for_escapes, unsigned parameters[], unsigned raw_bits[], unsigned *bits)
1833 #endif
1834 {
1835         unsigned rice_parameter, partition_bits;
1836 #ifndef NO_RICE_SEARCH
1837         unsigned best_partition_bits;
1838         unsigned min_rice_parameter, max_rice_parameter, best_rice_parameter = 0;
1839 #endif
1840         unsigned flat_bits;
1841         unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
1842
1843         FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
1844
1845         if(partition_order == 0) {
1846                 unsigned i;
1847
1848 #ifndef NO_RICE_SEARCH
1849                 if(rice_parameter_search_dist) {
1850                         if(suggested_rice_parameter < rice_parameter_search_dist)
1851                                 min_rice_parameter = 0;
1852                         else
1853                                 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
1854                         max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
1855                         if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1856 #ifdef DEBUG_VERBOSE
1857                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
1858 #endif
1859                                 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1860                         }
1861                 }
1862                 else
1863                         min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
1864
1865                 best_partition_bits = 0xffffffff;
1866                 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
1867 #endif
1868 #ifdef VARIABLE_RICE_BITS
1869 #ifdef FLAC__SYMMETRIC_RICE
1870                         partition_bits = (2+rice_parameter) * residual_samples;
1871 #else
1872                         const unsigned rice_parameter_estimate = rice_parameter-1;
1873                         partition_bits = (1+rice_parameter) * residual_samples;
1874 #endif
1875 #else
1876                         partition_bits = 0;
1877 #endif
1878                         partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
1879                         for(i = 0; i < residual_samples; i++) {
1880 #ifdef VARIABLE_RICE_BITS
1881 #ifdef FLAC__SYMMETRIC_RICE
1882                                 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter);
1883 #else
1884                                 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter_estimate);
1885 #endif
1886 #else
1887                                 partition_bits += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
1888 #endif
1889                         }
1890 #ifndef NO_RICE_SEARCH
1891                         if(partition_bits < best_partition_bits) {
1892                                 best_rice_parameter = rice_parameter;
1893                                 best_partition_bits = partition_bits;
1894                         }
1895                 }
1896 #endif
1897                 if(search_for_escapes) {
1898                         flat_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[0] * residual_samples;
1899                         if(flat_bits <= best_partition_bits) {
1900                                 raw_bits[0] = raw_bits_per_partition[0];
1901                                 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
1902                                 best_partition_bits = flat_bits;
1903                         }
1904                 }
1905                 parameters[0] = best_rice_parameter;
1906                 bits_ += best_partition_bits;
1907         }
1908         else {
1909                 unsigned partition, residual_sample, save_residual_sample, partition_sample;
1910                 unsigned partition_samples;
1911                 FLAC__uint64 mean, k;
1912                 const unsigned partitions = 1u << partition_order;
1913                 for(partition = residual_sample = 0; partition < partitions; partition++) {
1914                         partition_samples = (residual_samples+predictor_order) >> partition_order;
1915                         if(partition == 0) {
1916                                 if(partition_samples <= predictor_order)
1917                                         return false;
1918                                 else
1919                                         partition_samples -= predictor_order;
1920                         }
1921                         mean = abs_residual_partition_sums[partition];
1922 #ifdef FLAC__SYMMETRIC_RICE
1923                         mean += partition_samples >> 1; /* for rounding effect */
1924                         mean /= partition_samples;
1925
1926                         /* calc rice_parameter = floor(log2(mean)) */
1927                         rice_parameter = 0;
1928                         mean>>=1;
1929                         while(mean) {
1930                                 rice_parameter++;
1931                                 mean >>= 1;
1932                         }
1933 #else
1934                         /* calc rice_parameter ala LOCO-I */
1935                         for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
1936                                 ;
1937 #endif
1938                         if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1939 #ifdef DEBUG_VERBOSE
1940                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
1941 #endif
1942                                 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1943                         }
1944
1945 #ifndef NO_RICE_SEARCH
1946                         if(rice_parameter_search_dist) {
1947                                 if(rice_parameter < rice_parameter_search_dist)
1948                                         min_rice_parameter = 0;
1949                                 else
1950                                         min_rice_parameter = rice_parameter - rice_parameter_search_dist;
1951                                 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
1952                                 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1953 #ifdef DEBUG_VERBOSE
1954                                         fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
1955 #endif
1956                                         max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1957                                 }
1958                         }
1959                         else
1960                                 min_rice_parameter = max_rice_parameter = rice_parameter;
1961
1962                         best_partition_bits = 0xffffffff;
1963                         for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
1964 #endif
1965 #ifdef VARIABLE_RICE_BITS
1966 #ifdef FLAC__SYMMETRIC_RICE
1967                                 partition_bits = (2+rice_parameter) * partition_samples;
1968 #else
1969                                 const unsigned rice_parameter_estimate = rice_parameter-1;
1970                                 partition_bits = (1+rice_parameter) * partition_samples;
1971 #endif
1972 #else
1973                                 partition_bits = 0;
1974 #endif
1975                                 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
1976                                 save_residual_sample = residual_sample;
1977                                 for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++) {
1978 #ifdef VARIABLE_RICE_BITS
1979 #ifdef FLAC__SYMMETRIC_RICE
1980                                         partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter);
1981 #else
1982                                         partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter_estimate);
1983 #endif
1984 #else
1985                                         partition_bits += FLAC__bitbuffer_rice_bits(residual[residual_sample], rice_parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
1986 #endif
1987                                 }
1988 #ifndef NO_RICE_SEARCH
1989                                 if(rice_parameter != max_rice_parameter)
1990                                         residual_sample = save_residual_sample;
1991                                 if(partition_bits < best_partition_bits) {
1992                                         best_rice_parameter = rice_parameter;
1993                                         best_partition_bits = partition_bits;
1994                                 }
1995                         }
1996 #endif
1997                         if(search_for_escapes) {
1998                                 flat_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[partition] * partition_samples;
1999                                 if(flat_bits <= best_partition_bits) {
2000                                         raw_bits[partition] = raw_bits_per_partition[partition];
2001                                         best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
2002                                         best_partition_bits = flat_bits;
2003                                 }
2004                         }
2005                         parameters[partition] = best_rice_parameter;
2006                         bits_ += best_partition_bits;
2007                 }
2008         }
2009
2010         *bits = bits_;
2011         return true;
2012 }
2013
2014 unsigned stream_encoder_get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
2015 {
2016         unsigned i, shift;
2017         FLAC__int32 x = 0;
2018
2019         for(i = 0; i < samples && !(x&1); i++)
2020                 x |= signal[i];
2021
2022         if(x == 0) {
2023                 shift = 0;
2024         }
2025         else {
2026                 for(shift = 0; !(x&1); shift++)
2027                         x >>= 1;
2028         }
2029
2030         if(shift > 0) {
2031                 for(i = 0; i < samples; i++)
2032                          signal[i] >>= shift;
2033         }
2034
2035         return shift;
2036 }