acf97cd4d9bc04516f3d615d99fe3e63eeb927e0
[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         FLAC__ASSERT(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) { /* SSE version lacks necessary resolution, plus SSE flag doesn't check for OS support */
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
389                 encoder->private->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
390         if(encoder->private->cpuinfo.data.ia32.mmx && encoder->private->cpuinfo.data.ia32.cmov)
391                 encoder->private->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
392         if(encoder->private->cpuinfo.data.ia32.mmx) {
393                 encoder->private->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
394                 encoder->private->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
395         }
396         else {
397                 encoder->private->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
398                 encoder->private->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
399         }
400 #endif
401 #endif
402 #endif
403         /* finally override based on wide-ness if necessary */
404         if(encoder->private->use_wide_by_block) {
405                 encoder->private->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
406         }
407
408         /* we require precompute_partition_sums if do_escape_coding because of their intertwined nature */
409         encoder->private->precompute_partition_sums = (encoder->protected->max_residual_partition_order > encoder->protected->min_residual_partition_order) || encoder->protected->do_escape_coding;
410
411         if(!stream_encoder_resize_buffers_(encoder, encoder->protected->blocksize)) {
412                 /* the above function sets the state for us in case of an error */
413                 return encoder->protected->state;
414         }
415         FLAC__bitbuffer_init(&encoder->private->frame);
416
417         /*
418          * write the stream header
419          */
420
421         if(!FLAC__bitbuffer_clear(&encoder->private->frame))
422                 return encoder->protected->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
423         if(!FLAC__bitbuffer_write_raw_uint32(&encoder->private->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN))
424                 return encoder->protected->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
425
426         encoder->private->metadata.type = FLAC__METADATA_TYPE_STREAMINFO;
427         encoder->private->metadata.is_last = (encoder->protected->seek_table == 0 && encoder->protected->padding == 0 && encoder->protected->last_metadata_is_last);
428         encoder->private->metadata.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
429         encoder->private->metadata.data.stream_info.min_blocksize = encoder->protected->blocksize; /* this encoder uses the same blocksize for the whole stream */
430         encoder->private->metadata.data.stream_info.max_blocksize = encoder->protected->blocksize;
431         encoder->private->metadata.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
432         encoder->private->metadata.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
433         encoder->private->metadata.data.stream_info.sample_rate = encoder->protected->sample_rate;
434         encoder->private->metadata.data.stream_info.channels = encoder->protected->channels;
435         encoder->private->metadata.data.stream_info.bits_per_sample = encoder->protected->bits_per_sample;
436         encoder->private->metadata.data.stream_info.total_samples = encoder->protected->total_samples_estimate; /* we will replace this later with the real total */
437         memset(encoder->private->metadata.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
438         MD5Init(&encoder->private->md5context);
439         if(!FLAC__add_metadata_block(&encoder->private->metadata, &encoder->private->frame))
440                 return encoder->protected->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
441
442         if(0 != encoder->protected->seek_table) {
443                 if(!FLAC__seek_table_is_valid(encoder->protected->seek_table))
444                         return encoder->protected->state = FLAC__STREAM_ENCODER_INVALID_SEEK_TABLE;
445                 seek_table_block.type = FLAC__METADATA_TYPE_SEEKTABLE;
446                 seek_table_block.is_last = (encoder->protected->padding == 0 && encoder->protected->last_metadata_is_last);
447                 seek_table_block.length = encoder->protected->seek_table->num_points * FLAC__STREAM_METADATA_SEEKPOINT_LEN;
448                 seek_table_block.data.seek_table = *encoder->protected->seek_table;
449                 if(!FLAC__add_metadata_block(&seek_table_block, &encoder->private->frame))
450                         return encoder->protected->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
451         }
452
453         /* add a PADDING block if requested */
454         if(encoder->protected->padding > 0) {
455                 padding_block.type = FLAC__METADATA_TYPE_PADDING;
456                 padding_block.is_last = encoder->protected->last_metadata_is_last;
457                 padding_block.length = encoder->protected->padding;
458                 if(!FLAC__add_metadata_block(&padding_block, &encoder->private->frame))
459                         return encoder->protected->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
460         }
461
462         FLAC__ASSERT(encoder->private->frame.bits == 0); /* assert that we're byte-aligned before writing */
463         FLAC__ASSERT(encoder->private->frame.total_consumed_bits == 0); /* assert that no reading of the buffer was done */
464         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)
465                 return encoder->protected->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_WRITING;
466
467         /* now that the metadata block is written, we can init this to an absurdly-high value... */
468         encoder->private->metadata.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
469         /* ... and clear this to 0 */
470         encoder->private->metadata.data.stream_info.total_samples = 0;
471
472         return encoder->protected->state;
473 }
474
475 void FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
476 {
477         unsigned i, channel;
478
479         FLAC__ASSERT(encoder != 0);
480         if(encoder->protected->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
481                 return;
482         if(encoder->private->current_sample_number != 0) {
483                 encoder->protected->blocksize = encoder->private->current_sample_number;
484                 stream_encoder_process_frame_(encoder, true); /* true => is last frame */
485         }
486         MD5Final(encoder->private->metadata.data.stream_info.md5sum, &encoder->private->md5context);
487         encoder->private->metadata_callback(encoder, &encoder->private->metadata, encoder->private->client_data);
488         for(i = 0; i < encoder->protected->channels; i++) {
489                 if(encoder->private->integer_signal_unaligned[i] != 0) {
490                         free(encoder->private->integer_signal_unaligned[i]);
491                         encoder->private->integer_signal_unaligned[i] = 0;
492                 }
493                 if(encoder->private->real_signal_unaligned[i] != 0) {
494                         free(encoder->private->real_signal_unaligned[i]);
495                         encoder->private->real_signal_unaligned[i] = 0;
496                 }
497         }
498         for(i = 0; i < 2; i++) {
499                 if(encoder->private->integer_signal_mid_side_unaligned[i] != 0) {
500                         free(encoder->private->integer_signal_mid_side_unaligned[i]);
501                         encoder->private->integer_signal_mid_side_unaligned[i] = 0;
502                 }
503                 if(encoder->private->real_signal_mid_side_unaligned[i] != 0) {
504                         free(encoder->private->real_signal_mid_side_unaligned[i]);
505                         encoder->private->real_signal_mid_side_unaligned[i] = 0;
506                 }
507         }
508         for(channel = 0; channel < encoder->protected->channels; channel++) {
509                 for(i = 0; i < 2; i++) {
510                         if(encoder->private->residual_workspace_unaligned[channel][i] != 0) {
511                                 free(encoder->private->residual_workspace_unaligned[channel][i]);
512                                 encoder->private->residual_workspace_unaligned[channel][i] = 0;
513                         }
514                 }
515         }
516         for(channel = 0; channel < 2; channel++) {
517                 for(i = 0; i < 2; i++) {
518                         if(encoder->private->residual_workspace_mid_side_unaligned[channel][i] != 0) {
519                                 free(encoder->private->residual_workspace_mid_side_unaligned[channel][i]);
520                                 encoder->private->residual_workspace_mid_side_unaligned[channel][i] = 0;
521                         }
522                 }
523         }
524         if(encoder->private->abs_residual_unaligned != 0) {
525                 free(encoder->private->abs_residual_unaligned);
526                 encoder->private->abs_residual_unaligned = 0;
527         }
528         if(encoder->private->abs_residual_partition_sums_unaligned != 0) {
529                 free(encoder->private->abs_residual_partition_sums_unaligned);
530                 encoder->private->abs_residual_partition_sums_unaligned = 0;
531         }
532         if(encoder->private->raw_bits_per_partition_unaligned != 0) {
533                 free(encoder->private->raw_bits_per_partition_unaligned);
534                 encoder->private->raw_bits_per_partition_unaligned = 0;
535         }
536         FLAC__bitbuffer_free(&encoder->private->frame);
537
538         encoder->protected->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
539 }
540
541 FLAC__bool FLAC__stream_encoder_set_streamable_subset(const FLAC__StreamEncoder *encoder, FLAC__bool value)
542 {
543         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
544                 return false;
545         encoder->protected->streamable_subset = value;
546         return true;
547 }
548
549 FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(const FLAC__StreamEncoder *encoder, FLAC__bool value)
550 {
551         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
552                 return false;
553         encoder->protected->do_mid_side_stereo = value;
554         return true;
555 }
556
557 FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder, FLAC__bool value)
558 {
559         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
560                 return false;
561         encoder->protected->loose_mid_side_stereo = value;
562         return true;
563 }
564
565 FLAC__bool FLAC__stream_encoder_set_channels(const FLAC__StreamEncoder *encoder, unsigned value)
566 {
567         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
568                 return false;
569         encoder->protected->channels = value;
570         return true;
571 }
572
573 FLAC__bool FLAC__stream_encoder_set_bits_per_sample(const FLAC__StreamEncoder *encoder, unsigned value)
574 {
575         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
576                 return false;
577         encoder->protected->bits_per_sample = value;
578         return true;
579 }
580
581 FLAC__bool FLAC__stream_encoder_set_sample_rate(const FLAC__StreamEncoder *encoder, unsigned value)
582 {
583         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
584                 return false;
585         encoder->protected->sample_rate = value;
586         return true;
587 }
588
589 FLAC__bool FLAC__stream_encoder_set_blocksize(const FLAC__StreamEncoder *encoder, unsigned value)
590 {
591         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
592                 return false;
593         encoder->protected->blocksize = value;
594         return true;
595 }
596
597 FLAC__bool FLAC__stream_encoder_set_max_lpc_order(const FLAC__StreamEncoder *encoder, unsigned value)
598 {
599         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
600                 return false;
601         encoder->protected->max_lpc_order = value;
602         return true;
603 }
604
605 FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(const FLAC__StreamEncoder *encoder, unsigned value)
606 {
607         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
608                 return false;
609         encoder->protected->qlp_coeff_precision = value;
610         return true;
611 }
612
613 FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder, FLAC__bool value)
614 {
615         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
616                 return false;
617         encoder->protected->do_qlp_coeff_prec_search = value;
618         return true;
619 }
620
621 FLAC__bool FLAC__stream_encoder_set_do_escape_coding(const FLAC__StreamEncoder *encoder, FLAC__bool value)
622 {
623         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
624                 return false;
625         encoder->protected->do_escape_coding = value;
626         return true;
627 }
628
629 FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder, FLAC__bool value)
630 {
631         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
632                 return false;
633         encoder->protected->do_exhaustive_model_search = value;
634         return true;
635 }
636
637 FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(const FLAC__StreamEncoder *encoder, unsigned value)
638 {
639         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
640                 return false;
641         encoder->protected->min_residual_partition_order = value;
642         return true;
643 }
644
645 FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(const FLAC__StreamEncoder *encoder, unsigned value)
646 {
647         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
648                 return false;
649         encoder->protected->max_residual_partition_order = value;
650         return true;
651 }
652
653 FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder, unsigned value)
654 {
655         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
656                 return false;
657         encoder->protected->rice_parameter_search_dist = value;
658         return true;
659 }
660
661 FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(const FLAC__StreamEncoder *encoder, FLAC__uint64 value)
662 {
663         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
664                 return false;
665         encoder->protected->total_samples_estimate = value;
666         return true;
667 }
668
669 FLAC__bool FLAC__stream_encoder_set_seek_table(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetaData_SeekTable *value)
670 {
671         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
672                 return false;
673         encoder->protected->seek_table = value;
674         return true;
675 }
676
677 FLAC__bool FLAC__stream_encoder_set_padding(const FLAC__StreamEncoder *encoder, unsigned value)
678 {
679         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
680                 return false;
681         encoder->protected->padding = value;
682         return true;
683 }
684
685 FLAC__bool FLAC__stream_encoder_set_last_metadata_is_last(const FLAC__StreamEncoder *encoder, FLAC__bool value)
686 {
687         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
688                 return false;
689         encoder->protected->last_metadata_is_last = value;
690         return true;
691 }
692
693 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))
694 {
695         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
696                 return false;
697         encoder->private->write_callback = value;
698         return true;
699 }
700
701 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))
702 {
703         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
704                 return false;
705         encoder->private->metadata_callback = value;
706         return true;
707 }
708
709 FLAC__bool FLAC__stream_encoder_set_client_data(const FLAC__StreamEncoder *encoder, void *value)
710 {
711         if(encoder->protected->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
712                 return false;
713         encoder->private->client_data = value;
714         return true;
715 }
716
717 FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
718 {
719         return encoder->protected->state;
720 }
721
722 FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
723 {
724         return encoder->protected->streamable_subset;
725 }
726
727 FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
728 {
729         return encoder->protected->do_mid_side_stereo;
730 }
731
732 FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
733 {
734         return encoder->protected->loose_mid_side_stereo;
735 }
736
737 unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
738 {
739         return encoder->protected->channels;
740 }
741
742 unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
743 {
744         return encoder->protected->bits_per_sample;
745 }
746
747 unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
748 {
749         return encoder->protected->sample_rate;
750 }
751
752 unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
753 {
754         return encoder->protected->blocksize;
755 }
756
757 unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
758 {
759         return encoder->protected->max_lpc_order;
760 }
761
762 unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
763 {
764         return encoder->protected->qlp_coeff_precision;
765 }
766
767 FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
768 {
769         return encoder->protected->do_qlp_coeff_prec_search;
770 }
771
772 FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
773 {
774         return encoder->protected->do_escape_coding;
775 }
776
777 FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
778 {
779         return encoder->protected->do_exhaustive_model_search;
780 }
781
782 unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
783 {
784         return encoder->protected->min_residual_partition_order;
785 }
786
787 unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
788 {
789         return encoder->protected->max_residual_partition_order;
790 }
791
792 unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
793 {
794         return encoder->protected->rice_parameter_search_dist;
795 }
796
797 FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 *buf[], unsigned samples)
798 {
799         unsigned i, j, channel;
800         FLAC__int32 x, mid, side;
801         const unsigned channels = encoder->protected->channels, blocksize = encoder->protected->blocksize;
802
803         FLAC__ASSERT(encoder != 0);
804         FLAC__ASSERT(encoder->protected->state == FLAC__STREAM_ENCODER_OK);
805
806         j = 0;
807         if(encoder->protected->do_mid_side_stereo && channels == 2) {
808                 do {
809                         for(i = encoder->private->current_sample_number; i < blocksize && j < samples; i++, j++) {
810                                 x = mid = side = buf[0][j];
811                                 encoder->private->integer_signal[0][i] = x;
812                                 encoder->private->real_signal[0][i] = (FLAC__real)x;
813                                 x = buf[1][j];
814                                 encoder->private->integer_signal[1][i] = x;
815                                 encoder->private->real_signal[1][i] = (FLAC__real)x;
816                                 mid += x;
817                                 side -= x;
818                                 mid >>= 1; /* NOTE: not the same as 'mid = (buf[0][j] + buf[1][j]) / 2' ! */
819                                 encoder->private->integer_signal_mid_side[1][i] = side;
820                                 encoder->private->integer_signal_mid_side[0][i] = mid;
821                                 encoder->private->real_signal_mid_side[1][i] = (FLAC__real)side;
822                                 encoder->private->real_signal_mid_side[0][i] = (FLAC__real)mid;
823                                 encoder->private->current_sample_number++;
824                         }
825                         if(i == blocksize) {
826                                 if(!stream_encoder_process_frame_(encoder, false)) /* false => not last frame */
827                                         return false;
828                         }
829                 } while(j < samples);
830         }
831         else {
832                 do {
833                         for(i = encoder->private->current_sample_number; i < blocksize && j < samples; i++, j++) {
834                                 for(channel = 0; channel < channels; channel++) {
835                                         x = buf[channel][j];
836                                         encoder->private->integer_signal[channel][i] = x;
837                                         encoder->private->real_signal[channel][i] = (FLAC__real)x;
838                                 }
839                                 encoder->private->current_sample_number++;
840                         }
841                         if(i == blocksize) {
842                                 if(!stream_encoder_process_frame_(encoder, false)) /* false => not last frame */
843                                         return false;
844                         }
845                 } while(j < samples);
846         }
847
848         return true;
849 }
850
851 /* 'samples' is channel-wide samples, e.g. for 1 second at 44100Hz, 'samples' = 44100 regardless of the number of channels */
852 FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buf[], unsigned samples)
853 {
854         unsigned i, j, k, channel;
855         FLAC__int32 x, mid, side;
856         const unsigned channels = encoder->protected->channels, blocksize = encoder->protected->blocksize;
857
858         FLAC__ASSERT(encoder != 0);
859         FLAC__ASSERT(encoder->protected->state == FLAC__STREAM_ENCODER_OK);
860
861         j = k = 0;
862         if(encoder->protected->do_mid_side_stereo && channels == 2) {
863                 do {
864                         for(i = encoder->private->current_sample_number; i < blocksize && j < samples; i++, j++) {
865                                 x = mid = side = buf[k++];
866                                 encoder->private->integer_signal[0][i] = x;
867                                 encoder->private->real_signal[0][i] = (FLAC__real)x;
868                                 x = buf[k++];
869                                 encoder->private->integer_signal[1][i] = x;
870                                 encoder->private->real_signal[1][i] = (FLAC__real)x;
871                                 mid += x;
872                                 side -= x;
873                                 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
874                                 encoder->private->integer_signal_mid_side[1][i] = side;
875                                 encoder->private->integer_signal_mid_side[0][i] = mid;
876                                 encoder->private->real_signal_mid_side[1][i] = (FLAC__real)side;
877                                 encoder->private->real_signal_mid_side[0][i] = (FLAC__real)mid;
878                                 encoder->private->current_sample_number++;
879                         }
880                         if(i == blocksize) {
881                                 if(!stream_encoder_process_frame_(encoder, false)) /* false => not last frame */
882                                         return false;
883                         }
884                 } while(j < samples);
885         }
886         else {
887                 do {
888                         for(i = encoder->private->current_sample_number; i < blocksize && j < samples; i++, j++) {
889                                 for(channel = 0; channel < channels; channel++) {
890                                         x = buf[k++];
891                                         encoder->private->integer_signal[channel][i] = x;
892                                         encoder->private->real_signal[channel][i] = (FLAC__real)x;
893                                 }
894                                 encoder->private->current_sample_number++;
895                         }
896                         if(i == blocksize) {
897                                 if(!stream_encoder_process_frame_(encoder, false)) /* false => not last frame */
898                                         return false;
899                         }
900                 } while(j < samples);
901         }
902
903         return true;
904 }
905
906 FLAC__bool stream_encoder_resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_size)
907 {
908         FLAC__bool ok;
909         unsigned i, channel;
910
911         FLAC__ASSERT(new_size > 0);
912         FLAC__ASSERT(encoder->protected->state == FLAC__STREAM_ENCODER_OK);
913         FLAC__ASSERT(encoder->private->current_sample_number == 0);
914
915         /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
916         if(new_size <= encoder->private->input_capacity)
917                 return true;
918
919         ok = true;
920
921         /* 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. */
922
923         for(i = 0; ok && i < encoder->protected->channels; i++) {
924                 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size+4, &encoder->private->integer_signal_unaligned[i], &encoder->private->integer_signal[i]);
925                 ok = ok && FLAC__memory_alloc_aligned_real_array(new_size, &encoder->private->real_signal_unaligned[i], &encoder->private->real_signal[i]);
926                 memset(encoder->private->integer_signal[i], 0, sizeof(FLAC__int32)*4);
927                 encoder->private->integer_signal[i] += 4;
928         }
929         for(i = 0; ok && i < 2; i++) {
930                 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]);
931                 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]);
932                 memset(encoder->private->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
933                 encoder->private->integer_signal_mid_side[i] += 4;
934         }
935         for(channel = 0; ok && channel < encoder->protected->channels; channel++) {
936                 for(i = 0; ok && i < 2; i++) {
937                         ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size, &encoder->private->residual_workspace_unaligned[channel][i], &encoder->private->residual_workspace[channel][i]);
938                 }
939         }
940         for(channel = 0; ok && channel < 2; channel++) {
941                 for(i = 0; ok && i < 2; i++) {
942                         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]);
943                 }
944         }
945         ok = ok && FLAC__memory_alloc_aligned_uint32_array(new_size, &encoder->private->abs_residual_unaligned, &encoder->private->abs_residual);
946         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 */
947                 ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_size * 2, &encoder->private->abs_residual_partition_sums_unaligned, &encoder->private->abs_residual_partition_sums);
948         if(encoder->protected->do_escape_coding)
949                 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_size * 2, &encoder->private->raw_bits_per_partition_unaligned, &encoder->private->raw_bits_per_partition);
950
951         if(ok)
952                 encoder->private->input_capacity = new_size;
953         else
954                 encoder->protected->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
955
956         return ok;
957 }
958
959 /***********************************************************************
960  *
961  * Private class methods
962  *
963  ***********************************************************************/
964
965 FLAC__bool stream_encoder_process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame)
966 {
967         FLAC__ASSERT(encoder->protected->state == FLAC__STREAM_ENCODER_OK);
968
969         /*
970          * Accumulate raw signal to the MD5 signature
971          */
972         /* 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: */
973         if(!FLAC__MD5Accumulate(&encoder->private->md5context, encoder->private->integer_signal, encoder->protected->channels, encoder->protected->blocksize, (encoder->protected->bits_per_sample+7) / 8)) {
974                 encoder->protected->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
975                 return false;
976         }
977
978         /*
979          * Process the frame header and subframes into the frame bitbuffer
980          */
981         if(!stream_encoder_process_subframes_(encoder, is_last_frame)) {
982                 /* the above function sets the state for us in case of an error */
983                 return false;
984         }
985
986         /*
987          * Zero-pad the frame to a byte_boundary
988          */
989         if(!FLAC__bitbuffer_zero_pad_to_byte_boundary(&encoder->private->frame)) {
990                 encoder->protected->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
991                 return false;
992         }
993
994         /*
995          * CRC-16 the whole thing
996          */
997         FLAC__ASSERT(encoder->private->frame.bits == 0); /* assert that we're byte-aligned */
998         FLAC__ASSERT(encoder->private->frame.total_consumed_bits == 0); /* assert that no reading of the buffer was done */
999         FLAC__bitbuffer_write_raw_uint32(&encoder->private->frame, FLAC__crc16(encoder->private->frame.buffer, encoder->private->frame.bytes), FLAC__FRAME_FOOTER_CRC_LEN);
1000
1001         /*
1002          * Write it
1003          */
1004         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) {
1005                 encoder->protected->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_WRITING;
1006                 return false;
1007         }
1008
1009         /*
1010          * Get ready for the next frame
1011          */
1012         encoder->private->current_sample_number = 0;
1013         encoder->private->current_frame_number++;
1014         encoder->private->metadata.data.stream_info.total_samples += (FLAC__uint64)encoder->protected->blocksize;
1015         encoder->private->metadata.data.stream_info.min_framesize = min(encoder->private->frame.bytes, encoder->private->metadata.data.stream_info.min_framesize);
1016         encoder->private->metadata.data.stream_info.max_framesize = max(encoder->private->frame.bytes, encoder->private->metadata.data.stream_info.max_framesize);
1017
1018         return true;
1019 }
1020
1021 FLAC__bool stream_encoder_process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame)
1022 {
1023         FLAC__FrameHeader frame_header;
1024         unsigned channel, min_partition_order = encoder->protected->min_residual_partition_order, max_partition_order;
1025         FLAC__bool do_independent, do_mid_side, precompute_partition_sums;
1026
1027         /*
1028          * Calculate the min,max Rice partition orders
1029          */
1030         if(is_last_frame) {
1031                 max_partition_order = 0;
1032         }
1033         else {
1034                 unsigned limit = 0, b = encoder->protected->blocksize;
1035                 while(!(b & 1)) {
1036                         limit++;
1037                         b >>= 1;
1038                 }
1039                 max_partition_order = min(encoder->protected->max_residual_partition_order, limit);
1040         }
1041         min_partition_order = min(min_partition_order, max_partition_order);
1042
1043         precompute_partition_sums = encoder->private->precompute_partition_sums && ((max_partition_order > min_partition_order) || encoder->protected->do_escape_coding);
1044
1045         /*
1046          * Setup the frame
1047          */
1048         if(!FLAC__bitbuffer_clear(&encoder->private->frame)) {
1049                 encoder->protected->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1050                 return false;
1051         }
1052         frame_header.blocksize = encoder->protected->blocksize;
1053         frame_header.sample_rate = encoder->protected->sample_rate;
1054         frame_header.channels = encoder->protected->channels;
1055         frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
1056         frame_header.bits_per_sample = encoder->protected->bits_per_sample;
1057         frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
1058         frame_header.number.frame_number = encoder->private->current_frame_number;
1059
1060         /*
1061          * Figure out what channel assignments to try
1062          */
1063         if(encoder->protected->do_mid_side_stereo) {
1064                 if(encoder->protected->loose_mid_side_stereo) {
1065                         if(encoder->private->loose_mid_side_stereo_frame_count == 0) {
1066                                 do_independent = true;
1067                                 do_mid_side = true;
1068                         }
1069                         else {
1070                                 do_independent = (encoder->private->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
1071                                 do_mid_side = !do_independent;
1072                         }
1073                 }
1074                 else {
1075                         do_independent = true;
1076                         do_mid_side = true;
1077                 }
1078         }
1079         else {
1080                 do_independent = true;
1081                 do_mid_side = false;
1082         }
1083
1084         FLAC__ASSERT(do_independent || do_mid_side);
1085
1086         /*
1087          * Check for wasted bits; set effective bps for each subframe
1088          */
1089         if(do_independent) {
1090                 unsigned w;
1091                 for(channel = 0; channel < encoder->protected->channels; channel++) {
1092                         w = stream_encoder_get_wasted_bits_(encoder->private->integer_signal[channel], encoder->protected->blocksize);
1093                         encoder->private->subframe_workspace[channel][0].wasted_bits = encoder->private->subframe_workspace[channel][1].wasted_bits = w;
1094                         encoder->private->subframe_bps[channel] = encoder->protected->bits_per_sample - w;
1095                 }
1096         }
1097         if(do_mid_side) {
1098                 unsigned w;
1099                 FLAC__ASSERT(encoder->protected->channels == 2);
1100                 for(channel = 0; channel < 2; channel++) {
1101                         w = stream_encoder_get_wasted_bits_(encoder->private->integer_signal_mid_side[channel], encoder->protected->blocksize);
1102                         encoder->private->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private->subframe_workspace_mid_side[channel][1].wasted_bits = w;
1103                         encoder->private->subframe_bps_mid_side[channel] = encoder->protected->bits_per_sample - w + (channel==0? 0:1);
1104                 }
1105         }
1106
1107         /*
1108          * First do a normal encoding pass of each independent channel
1109          */
1110         if(do_independent) {
1111                 for(channel = 0; channel < encoder->protected->channels; channel++) {
1112                         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))
1113                                 return false;
1114                 }
1115         }
1116
1117         /*
1118          * Now do mid and side channels if requested
1119          */
1120         if(do_mid_side) {
1121                 FLAC__ASSERT(encoder->protected->channels == 2);
1122
1123                 for(channel = 0; channel < 2; channel++) {
1124                         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))
1125                                 return false;
1126                 }
1127         }
1128
1129         /*
1130          * Compose the frame bitbuffer
1131          */
1132         if(do_mid_side) {
1133                 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
1134                 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
1135                 FLAC__ChannelAssignment channel_assignment;
1136
1137                 FLAC__ASSERT(encoder->protected->channels == 2);
1138
1139                 if(encoder->protected->loose_mid_side_stereo && encoder->private->loose_mid_side_stereo_frame_count > 0) {
1140                         channel_assignment = (encoder->private->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
1141                 }
1142                 else {
1143                         unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
1144                         unsigned min_bits;
1145                         FLAC__ChannelAssignment ca;
1146
1147                         FLAC__ASSERT(do_independent && do_mid_side);
1148
1149                         /* We have to figure out which channel assignent results in the smallest frame */
1150                         bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private->best_subframe_bits         [0] + encoder->private->best_subframe_bits         [1];
1151                         bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE  ] = encoder->private->best_subframe_bits         [0] + encoder->private->best_subframe_bits_mid_side[1];
1152                         bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private->best_subframe_bits         [1] + encoder->private->best_subframe_bits_mid_side[1];
1153                         bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE   ] = encoder->private->best_subframe_bits_mid_side[0] + encoder->private->best_subframe_bits_mid_side[1];
1154
1155                         for(channel_assignment = 0, min_bits = bits[0], ca = 1; ca <= 3; ca++) {
1156                                 if(bits[ca] < min_bits) {
1157                                         min_bits = bits[ca];
1158                                         channel_assignment = ca;
1159                                 }
1160                         }
1161                 }
1162
1163                 frame_header.channel_assignment = channel_assignment;
1164
1165                 if(!FLAC__frame_add_header(&frame_header, encoder->protected->streamable_subset, is_last_frame, &encoder->private->frame)) {
1166                         encoder->protected->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1167                         return false;
1168                 }
1169
1170                 switch(channel_assignment) {
1171                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1172                                 left_subframe  = &encoder->private->subframe_workspace         [0][encoder->private->best_subframe         [0]];
1173                                 right_subframe = &encoder->private->subframe_workspace         [1][encoder->private->best_subframe         [1]];
1174                                 break;
1175                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1176                                 left_subframe  = &encoder->private->subframe_workspace         [0][encoder->private->best_subframe         [0]];
1177                                 right_subframe = &encoder->private->subframe_workspace_mid_side[1][encoder->private->best_subframe_mid_side[1]];
1178                                 break;
1179                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1180                                 left_subframe  = &encoder->private->subframe_workspace_mid_side[1][encoder->private->best_subframe_mid_side[1]];
1181                                 right_subframe = &encoder->private->subframe_workspace         [1][encoder->private->best_subframe         [1]];
1182                                 break;
1183                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1184                                 left_subframe  = &encoder->private->subframe_workspace_mid_side[0][encoder->private->best_subframe_mid_side[0]];
1185                                 right_subframe = &encoder->private->subframe_workspace_mid_side[1][encoder->private->best_subframe_mid_side[1]];
1186                                 break;
1187                         default:
1188                                 FLAC__ASSERT(0);
1189                 }
1190
1191                 switch(channel_assignment) {
1192                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1193                                 left_bps  = encoder->private->subframe_bps         [0];
1194                                 right_bps = encoder->private->subframe_bps         [1];
1195                                 break;
1196                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1197                                 left_bps  = encoder->private->subframe_bps         [0];
1198                                 right_bps = encoder->private->subframe_bps_mid_side[1];
1199                                 break;
1200                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1201                                 left_bps  = encoder->private->subframe_bps_mid_side[1];
1202                                 right_bps = encoder->private->subframe_bps         [1];
1203                                 break;
1204                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1205                                 left_bps  = encoder->private->subframe_bps_mid_side[0];
1206                                 right_bps = encoder->private->subframe_bps_mid_side[1];
1207                                 break;
1208                         default:
1209                                 FLAC__ASSERT(0);
1210                 }
1211
1212                 /* note that encoder_add_subframe_ sets the state for us in case of an error */
1213                 if(!stream_encoder_add_subframe_(encoder, &frame_header, left_bps , left_subframe , &encoder->private->frame))
1214                         return false;
1215                 if(!stream_encoder_add_subframe_(encoder, &frame_header, right_bps, right_subframe, &encoder->private->frame))
1216                         return false;
1217         }
1218         else {
1219                 if(!FLAC__frame_add_header(&frame_header, encoder->protected->streamable_subset, is_last_frame, &encoder->private->frame)) {
1220                         encoder->protected->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1221                         return false;
1222                 }
1223
1224                 for(channel = 0; channel < encoder->protected->channels; channel++) {
1225                         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)) {
1226                                 /* the above function sets the state for us in case of an error */
1227                                 return false;
1228                         }
1229                 }
1230         }
1231
1232         if(encoder->protected->loose_mid_side_stereo) {
1233                 encoder->private->loose_mid_side_stereo_frame_count++;
1234                 if(encoder->private->loose_mid_side_stereo_frame_count >= encoder->private->loose_mid_side_stereo_frames)
1235                         encoder->private->loose_mid_side_stereo_frame_count = 0;
1236         }
1237
1238         encoder->private->last_channel_assignment = frame_header.channel_assignment;
1239
1240         return true;
1241 }
1242
1243 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)
1244 {
1245         FLAC__real fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
1246         FLAC__real lpc_residual_bits_per_sample;
1247         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 */
1248         FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER];
1249         FLAC__real lpc_error[FLAC__MAX_LPC_ORDER];
1250         unsigned min_lpc_order, max_lpc_order, lpc_order;
1251         unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
1252         unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
1253         unsigned rice_parameter;
1254         unsigned _candidate_bits, _best_bits;
1255         unsigned _best_subframe;
1256
1257         /* verbatim subframe is the baseline against which we measure other compressed subframes */
1258         _best_subframe = 0;
1259         _best_bits = stream_encoder_evaluate_verbatim_subframe_(integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
1260
1261         if(!verbatim_only && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
1262                 /* check for constant subframe */
1263                 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);
1264                 if(fixed_residual_bits_per_sample[1] == 0.0) {
1265                         /* the above means integer_signal+FLAC__MAX_FIXED_ORDER is constant, now we just have to check the warmup samples */
1266                         unsigned i, signal_is_constant = true;
1267                         for(i = 1; i <= FLAC__MAX_FIXED_ORDER; i++) {
1268                                 if(integer_signal[0] != integer_signal[i]) {
1269                                         signal_is_constant = false;
1270                                         break;
1271                                 }
1272                         }
1273                         if(signal_is_constant) {
1274                                 _candidate_bits = stream_encoder_evaluate_constant_subframe_(integer_signal[0], subframe_bps, subframe[!_best_subframe]);
1275                                 if(_candidate_bits < _best_bits) {
1276                                         _best_subframe = !_best_subframe;
1277                                         _best_bits = _candidate_bits;
1278                                 }
1279                         }
1280                 }
1281                 else {
1282                         /* encode fixed */
1283                         if(encoder->protected->do_exhaustive_model_search) {
1284                                 min_fixed_order = 0;
1285                                 max_fixed_order = FLAC__MAX_FIXED_ORDER;
1286                         }
1287                         else {
1288                                 min_fixed_order = max_fixed_order = guess_fixed_order;
1289                         }
1290                         for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
1291                                 if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__real)subframe_bps)
1292                                         continue; /* don't even try */
1293                                 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 */
1294 #ifndef FLAC__SYMMETRIC_RICE
1295                                 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
1296 #endif
1297                                 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1298 #ifdef DEBUG
1299                                         fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
1300 #endif
1301                                         rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1302                                 }
1303                                 _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]);
1304                                 if(_candidate_bits < _best_bits) {
1305                                         _best_subframe = !_best_subframe;
1306                                         _best_bits = _candidate_bits;
1307                                 }
1308                         }
1309
1310                         /* encode lpc */
1311                         if(encoder->protected->max_lpc_order > 0) {
1312                                 if(encoder->protected->max_lpc_order >= frame_header->blocksize)
1313                                         max_lpc_order = frame_header->blocksize-1;
1314                                 else
1315                                         max_lpc_order = encoder->protected->max_lpc_order;
1316                                 if(max_lpc_order > 0) {
1317                                         encoder->private->local_lpc_compute_autocorrelation(real_signal, frame_header->blocksize, max_lpc_order+1, autoc);
1318                                         /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
1319                                         if(autoc[0] != 0.0) {
1320                                                 FLAC__lpc_compute_lp_coefficients(autoc, max_lpc_order, lp_coeff, lpc_error);
1321                                                 if(encoder->protected->do_exhaustive_model_search) {
1322                                                         min_lpc_order = 1;
1323                                                 }
1324                                                 else {
1325                                                         unsigned guess_lpc_order = FLAC__lpc_compute_best_order(lpc_error, max_lpc_order, frame_header->blocksize, subframe_bps);
1326                                                         min_lpc_order = max_lpc_order = guess_lpc_order;
1327                                                 }
1328                                                 if(encoder->protected->do_qlp_coeff_prec_search) {
1329                                                         min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
1330                                                         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 */
1331                                                 }
1332                                                 else {
1333                                                         min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected->qlp_coeff_precision;
1334                                                 }
1335                                                 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
1336                                                         lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
1337                                                         if(lpc_residual_bits_per_sample >= (FLAC__real)subframe_bps)
1338                                                                 continue; /* don't even try */
1339                                                         rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
1340 #ifndef FLAC__SYMMETRIC_RICE
1341                                                         rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
1342 #endif
1343                                                         if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1344 #ifdef DEBUG
1345                                                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
1346 #endif
1347                                                                 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1348                                                         }
1349                                                         for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
1350                                                                 _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]);
1351                                                                 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
1352                                                                         if(_candidate_bits < _best_bits) {
1353                                                                                 _best_subframe = !_best_subframe;
1354                                                                                 _best_bits = _candidate_bits;
1355                                                                         }
1356                                                                 }
1357                                                         }
1358                                                 }
1359                                         }
1360                                 }
1361                         }
1362                 }
1363         }
1364
1365         *best_subframe = _best_subframe;
1366         *best_bits = _best_bits;
1367
1368         return true;
1369 }
1370
1371 FLAC__bool stream_encoder_add_subframe_(FLAC__StreamEncoder *encoder, const FLAC__FrameHeader *frame_header, unsigned subframe_bps, const FLAC__Subframe *subframe, FLAC__BitBuffer *frame)
1372 {
1373         switch(subframe->type) {
1374                 case FLAC__SUBFRAME_TYPE_CONSTANT:
1375                         if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
1376                                 encoder->protected->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING;
1377                                 return false;
1378                         }
1379                         break;
1380                 case FLAC__SUBFRAME_TYPE_FIXED:
1381                         if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), frame_header->blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
1382                                 encoder->protected->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING;
1383                                 return false;
1384                         }
1385                         break;
1386                 case FLAC__SUBFRAME_TYPE_LPC:
1387                         if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), frame_header->blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
1388                                 encoder->protected->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING;
1389                                 return false;
1390                         }
1391                         break;
1392                 case FLAC__SUBFRAME_TYPE_VERBATIM:
1393                         if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), frame_header->blocksize, subframe_bps, subframe->wasted_bits, frame)) {
1394                                 encoder->protected->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING;
1395                                 return false;
1396                         }
1397                         break;
1398                 default:
1399                         FLAC__ASSERT(0);
1400         }
1401
1402         return true;
1403 }
1404
1405 unsigned stream_encoder_evaluate_constant_subframe_(const FLAC__int32 signal, unsigned subframe_bps, FLAC__Subframe *subframe)
1406 {
1407         subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
1408         subframe->data.constant.value = signal;
1409
1410         return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe_bps;
1411 }
1412
1413 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)
1414 {
1415         unsigned i, residual_bits;
1416         const unsigned residual_samples = blocksize - order;
1417
1418         FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
1419
1420         subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
1421
1422         subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
1423         subframe->data.fixed.residual = residual;
1424
1425         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);
1426
1427         subframe->data.fixed.order = order;
1428         for(i = 0; i < order; i++)
1429                 subframe->data.fixed.warmup[i] = signal[i];
1430
1431         return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (order * subframe_bps) + residual_bits;
1432 }
1433
1434 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)
1435 {
1436         FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
1437         unsigned i, residual_bits;
1438         int quantization, ret;
1439         const unsigned residual_samples = blocksize - order;
1440
1441         ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, subframe_bps, qlp_coeff, &quantization);
1442         if(ret != 0)
1443                 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
1444
1445         if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
1446                 encoder->private->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
1447         else
1448                 encoder->private->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
1449
1450         subframe->type = FLAC__SUBFRAME_TYPE_LPC;
1451
1452         subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
1453         subframe->data.lpc.residual = residual;
1454
1455         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);
1456
1457         subframe->data.lpc.order = order;
1458         subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
1459         subframe->data.lpc.quantization_level = quantization;
1460         memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
1461         for(i = 0; i < order; i++)
1462                 subframe->data.lpc.warmup[i] = signal[i];
1463
1464         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;
1465 }
1466
1467 unsigned stream_encoder_evaluate_verbatim_subframe_(const FLAC__int32 signal[], unsigned blocksize, unsigned subframe_bps, FLAC__Subframe *subframe)
1468 {
1469         subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
1470
1471         subframe->data.verbatim.data = signal;
1472
1473         return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (blocksize * subframe_bps);
1474 }
1475
1476 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[])
1477 {
1478         FLAC__int32 r;
1479         unsigned residual_bits, best_residual_bits = 0;
1480         unsigned residual_sample;
1481         unsigned best_parameters_index = 0, parameters[2][1 << FLAC__MAX_RICE_PARTITION_ORDER], raw_bits[2][1 << FLAC__MAX_RICE_PARTITION_ORDER];
1482         const unsigned blocksize = residual_samples + predictor_order;
1483
1484         /* compute abs(residual) for use later */
1485         for(residual_sample = 0; residual_sample < residual_samples; residual_sample++) {
1486                 r = residual[residual_sample];
1487                 abs_residual[residual_sample] = (FLAC__uint32)(r<0? -r : r);
1488         }
1489
1490         while(max_partition_order > 0 && blocksize >> max_partition_order <= predictor_order)
1491                 max_partition_order--;
1492         FLAC__ASSERT(blocksize >> max_partition_order > predictor_order);
1493         min_partition_order = min(min_partition_order, max_partition_order);
1494
1495         if(precompute_partition_sums) {
1496                 int partition_order;
1497                 unsigned sum;
1498
1499                 stream_encoder_precompute_partition_info_sums_(abs_residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order);
1500
1501                 if(do_escape_coding)
1502                         stream_encoder_precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
1503
1504                 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
1505 #ifdef DONT_ESTIMATE_RICE_BITS
1506                         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))
1507 #else
1508                         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))
1509 #endif
1510                         {
1511                                 FLAC__ASSERT(best_residual_bits != 0);
1512                                 break;
1513                         }
1514                         sum += 1u << partition_order;
1515                         if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
1516                                 best_residual_bits = residual_bits;
1517                                 *best_partition_order = partition_order;
1518                                 best_parameters_index = !best_parameters_index;
1519                         }
1520                 }
1521         }
1522         else {
1523                 unsigned partition_order;
1524                 for(partition_order = min_partition_order; partition_order <= max_partition_order; partition_order++) {
1525 #ifdef DONT_ESTIMATE_RICE_BITS
1526                         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))
1527 #else
1528                         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))
1529 #endif
1530                         {
1531                                 FLAC__ASSERT(best_residual_bits != 0);
1532                                 break;
1533                         }
1534                         if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
1535                                 best_residual_bits = residual_bits;
1536                                 *best_partition_order = partition_order;
1537                                 best_parameters_index = !best_parameters_index;
1538                         }
1539                 }
1540         }
1541
1542         memcpy(best_parameters, parameters[best_parameters_index], sizeof(unsigned)*(1<<(*best_partition_order)));
1543         memcpy(best_raw_bits, raw_bits[best_parameters_index], sizeof(unsigned)*(1<<(*best_partition_order)));
1544
1545         return best_residual_bits;
1546 }
1547
1548 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)
1549 {
1550         int partition_order;
1551         unsigned from_partition, to_partition = 0;
1552         const unsigned blocksize = residual_samples + predictor_order;
1553
1554         /* first do max_partition_order */
1555         for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
1556                 FLAC__uint64 abs_residual_partition_sum;
1557                 FLAC__uint32 abs_r;
1558                 unsigned partition, partition_sample, partition_samples, residual_sample;
1559                 const unsigned partitions = 1u << partition_order;
1560                 const unsigned default_partition_samples = blocksize >> partition_order;
1561
1562                 FLAC__ASSERT(default_partition_samples > predictor_order);
1563
1564                 for(partition = residual_sample = 0; partition < partitions; partition++) {
1565                         partition_samples = default_partition_samples;
1566                         if(partition == 0)
1567                                 partition_samples -= predictor_order;
1568                         abs_residual_partition_sum = 0;
1569                         for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
1570                                 abs_r = abs_residual[residual_sample];
1571                                 abs_residual_partition_sum += abs_r;
1572                                 residual_sample++;
1573                         }
1574                         abs_residual_partition_sums[partition] = abs_residual_partition_sum;
1575                 }
1576                 to_partition = partitions;
1577                 break;
1578         }
1579
1580         /* now merge partitions for lower orders */
1581         for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
1582                 FLAC__uint64 s;
1583                 unsigned i;
1584                 const unsigned partitions = 1u << partition_order;
1585                 for(i = 0; i < partitions; i++) {
1586                         s = abs_residual_partition_sums[from_partition];
1587                         from_partition++;
1588                         abs_residual_partition_sums[to_partition] = s + abs_residual_partition_sums[from_partition];
1589                         from_partition++;
1590                         to_partition++;
1591                 }
1592         }
1593 }
1594
1595 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)
1596 {
1597         int partition_order;
1598         unsigned from_partition, to_partition = 0;
1599         const unsigned blocksize = residual_samples + predictor_order;
1600
1601         /* first do max_partition_order */
1602         for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
1603                 FLAC__int32 r, residual_partition_min, residual_partition_max;
1604                 unsigned silog2_min, silog2_max;
1605                 unsigned partition, partition_sample, partition_samples, residual_sample;
1606                 const unsigned partitions = 1u << partition_order;
1607                 const unsigned default_partition_samples = blocksize >> partition_order;
1608
1609                 FLAC__ASSERT(default_partition_samples > predictor_order);
1610
1611                 for(partition = residual_sample = 0; partition < partitions; partition++) {
1612                         partition_samples = default_partition_samples;
1613                         if(partition == 0)
1614                                 partition_samples -= predictor_order;
1615                         residual_partition_min = residual_partition_max = 0;
1616                         for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
1617                                 r = residual[residual_sample];
1618                                 if(r < residual_partition_min)
1619                                         residual_partition_min = r;
1620                                 else if(r > residual_partition_max)
1621                                         residual_partition_max = r;
1622                                 residual_sample++;
1623                         }
1624                         silog2_min = FLAC__bitmath_silog2(residual_partition_min);
1625                         silog2_max = FLAC__bitmath_silog2(residual_partition_max);
1626                         raw_bits_per_partition[partition] = max(silog2_min, silog2_max);
1627                 }
1628                 to_partition = partitions;
1629                 break;
1630         }
1631
1632         /* now merge partitions for lower orders */
1633         for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
1634                 unsigned m;
1635                 unsigned i;
1636                 const unsigned partitions = 1u << partition_order;
1637                 for(i = 0; i < partitions; i++) {
1638                         m = raw_bits_per_partition[from_partition];
1639                         from_partition++;
1640                         raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
1641                         from_partition++;
1642                         to_partition++;
1643                 }
1644         }
1645 }
1646
1647 #ifdef VARIABLE_RICE_BITS
1648 #undef VARIABLE_RICE_BITS
1649 #endif
1650 #ifndef DONT_ESTIMATE_RICE_BITS
1651 #define VARIABLE_RICE_BITS(value, parameter) ((value) >> (parameter))
1652 #endif
1653
1654 #ifdef DONT_ESTIMATE_RICE_BITS
1655 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)
1656 #else
1657 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)
1658 #endif
1659 {
1660         unsigned rice_parameter, partition_bits;
1661 #ifndef NO_RICE_SEARCH
1662         unsigned best_partition_bits;
1663         unsigned min_rice_parameter, max_rice_parameter, best_rice_parameter = 0;
1664 #endif
1665         unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
1666
1667         FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
1668
1669         if(partition_order == 0) {
1670                 unsigned i;
1671
1672 #ifndef NO_RICE_SEARCH
1673                 if(rice_parameter_search_dist) {
1674                         if(suggested_rice_parameter < rice_parameter_search_dist)
1675                                 min_rice_parameter = 0;
1676                         else
1677                                 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
1678                         max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
1679                         if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1680 #ifdef DEBUG
1681                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @2\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
1682 #endif
1683                                 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1684                         }
1685                 }
1686                 else
1687                         min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
1688
1689                 best_partition_bits = 0xffffffff;
1690                 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
1691 #endif
1692 #ifdef VARIABLE_RICE_BITS
1693 #ifdef FLAC__SYMMETRIC_RICE
1694                         partition_bits = (2+rice_parameter) * residual_samples;
1695 #else
1696                         const unsigned rice_parameter_estimate = rice_parameter-1;
1697                         partition_bits = (1+rice_parameter) * residual_samples;
1698 #endif
1699 #else
1700                         partition_bits = 0;
1701 #endif
1702                         partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
1703                         for(i = 0; i < residual_samples; i++) {
1704 #ifdef VARIABLE_RICE_BITS
1705 #ifdef FLAC__SYMMETRIC_RICE
1706                                 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter);
1707 #else
1708                                 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter_estimate);
1709 #endif
1710 #else
1711                                 partition_bits += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter); /* NOTE: we will need to pass in residual[] in addition to abs_residual[] */
1712 #endif
1713                         }
1714 #ifndef NO_RICE_SEARCH
1715                         if(partition_bits < best_partition_bits) {
1716                                 best_rice_parameter = rice_parameter;
1717                                 best_partition_bits = partition_bits;
1718                         }
1719                 }
1720 #endif
1721                 parameters[0] = best_rice_parameter;
1722                 bits_ += best_partition_bits;
1723         }
1724         else {
1725                 unsigned partition, residual_sample, save_residual_sample, partition_sample;
1726                 unsigned partition_samples;
1727                 FLAC__uint64 mean, k;
1728                 const unsigned partitions = 1u << partition_order;
1729                 for(partition = residual_sample = 0; partition < partitions; partition++) {
1730                         partition_samples = (residual_samples+predictor_order) >> partition_order;
1731                         if(partition == 0) {
1732                                 if(partition_samples <= predictor_order)
1733                                         return false;
1734                                 else
1735                                         partition_samples -= predictor_order;
1736                         }
1737                         mean = 0;
1738                         save_residual_sample = residual_sample;
1739                         for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++)
1740                                 mean += abs_residual[residual_sample];
1741                         residual_sample = save_residual_sample;
1742 #ifdef FLAC__SYMMETRIC_RICE
1743                         mean += partition_samples >> 1; /* for rounding effect */
1744                         mean /= partition_samples;
1745
1746                         /* calc rice_parameter = floor(log2(mean)) */
1747                         rice_parameter = 0;
1748                         mean>>=1;
1749                         while(mean) {
1750                                 rice_parameter++;
1751                                 mean >>= 1;
1752                         }
1753 #else
1754                         /* calc rice_parameter ala LOCO-I */
1755                         for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
1756                                 ;
1757 #endif
1758                         if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1759 #ifdef DEBUG
1760                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @3\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
1761 #endif
1762                                 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1763                         }
1764
1765 #ifndef NO_RICE_SEARCH
1766                         if(rice_parameter_search_dist) {
1767                                 if(rice_parameter < rice_parameter_search_dist)
1768                                         min_rice_parameter = 0;
1769                                 else
1770                                         min_rice_parameter = rice_parameter - rice_parameter_search_dist;
1771                                 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
1772                                 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1773 #ifdef DEBUG
1774                                         fprintf(stderr, "clipping rice_parameter (%u -> %u) @4\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
1775 #endif
1776                                         max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1777                                 }
1778                         }
1779                         else
1780                                 min_rice_parameter = max_rice_parameter = rice_parameter;
1781
1782                         best_partition_bits = 0xffffffff;
1783                         for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
1784 #endif
1785 #ifdef VARIABLE_RICE_BITS
1786 #ifdef FLAC__SYMMETRIC_RICE
1787                                 partition_bits = (2+rice_parameter) * partition_samples;
1788 #else
1789                                 const unsigned rice_parameter_estimate = rice_parameter-1;
1790                                 partition_bits = (1+rice_parameter) * partition_samples;
1791 #endif
1792 #else
1793                                 partition_bits = 0;
1794 #endif
1795                                 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
1796                                 save_residual_sample = residual_sample;
1797                                 for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++) {
1798 #ifdef VARIABLE_RICE_BITS
1799 #ifdef FLAC__SYMMETRIC_RICE
1800                                         partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter);
1801 #else
1802                                         partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter_estimate);
1803 #endif
1804 #else
1805                                         partition_bits += FLAC__bitbuffer_rice_bits(residual[residual_sample], rice_parameter); /* NOTE: we will need to pass in residual[] in addition to abs_residual[] */
1806 #endif
1807                                 }
1808 #ifndef NO_RICE_SEARCH
1809                                 if(rice_parameter != max_rice_parameter)
1810                                         residual_sample = save_residual_sample;
1811                                 if(partition_bits < best_partition_bits) {
1812                                         best_rice_parameter = rice_parameter;
1813                                         best_partition_bits = partition_bits;
1814                                 }
1815                         }
1816 #endif
1817                         parameters[partition] = best_rice_parameter;
1818                         bits_ += best_partition_bits;
1819                 }
1820         }
1821
1822         *bits = bits_;
1823         return true;
1824 }
1825
1826 #ifdef DONT_ESTIMATE_RICE_BITS
1827 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)
1828 #else
1829 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)
1830 #endif
1831 {
1832         unsigned rice_parameter, partition_bits;
1833 #ifndef NO_RICE_SEARCH
1834         unsigned best_partition_bits;
1835         unsigned min_rice_parameter, max_rice_parameter, best_rice_parameter = 0;
1836 #endif
1837         unsigned flat_bits;
1838         unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
1839
1840         FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
1841
1842         if(partition_order == 0) {
1843                 unsigned i;
1844
1845 #ifndef NO_RICE_SEARCH
1846                 if(rice_parameter_search_dist) {
1847                         if(suggested_rice_parameter < rice_parameter_search_dist)
1848                                 min_rice_parameter = 0;
1849                         else
1850                                 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
1851                         max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
1852                         if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1853 #ifdef DEBUG
1854                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
1855 #endif
1856                                 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1857                         }
1858                 }
1859                 else
1860                         min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
1861
1862                 best_partition_bits = 0xffffffff;
1863                 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
1864 #endif
1865 #ifdef VARIABLE_RICE_BITS
1866 #ifdef FLAC__SYMMETRIC_RICE
1867                         partition_bits = (2+rice_parameter) * residual_samples;
1868 #else
1869                         const unsigned rice_parameter_estimate = rice_parameter-1;
1870                         partition_bits = (1+rice_parameter) * residual_samples;
1871 #endif
1872 #else
1873                         partition_bits = 0;
1874 #endif
1875                         partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
1876                         for(i = 0; i < residual_samples; i++) {
1877 #ifdef VARIABLE_RICE_BITS
1878 #ifdef FLAC__SYMMETRIC_RICE
1879                                 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter);
1880 #else
1881                                 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter_estimate);
1882 #endif
1883 #else
1884                                 partition_bits += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
1885 #endif
1886                         }
1887 #ifndef NO_RICE_SEARCH
1888                         if(partition_bits < best_partition_bits) {
1889                                 best_rice_parameter = rice_parameter;
1890                                 best_partition_bits = partition_bits;
1891                         }
1892                 }
1893 #endif
1894                 if(search_for_escapes) {
1895                         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;
1896                         if(flat_bits <= best_partition_bits) {
1897                                 raw_bits[0] = raw_bits_per_partition[0];
1898                                 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
1899                                 best_partition_bits = flat_bits;
1900                         }
1901                 }
1902                 parameters[0] = best_rice_parameter;
1903                 bits_ += best_partition_bits;
1904         }
1905         else {
1906                 unsigned partition, residual_sample, save_residual_sample, partition_sample;
1907                 unsigned partition_samples;
1908                 FLAC__uint64 mean, k;
1909                 const unsigned partitions = 1u << partition_order;
1910                 for(partition = residual_sample = 0; partition < partitions; partition++) {
1911                         partition_samples = (residual_samples+predictor_order) >> partition_order;
1912                         if(partition == 0) {
1913                                 if(partition_samples <= predictor_order)
1914                                         return false;
1915                                 else
1916                                         partition_samples -= predictor_order;
1917                         }
1918                         mean = abs_residual_partition_sums[partition];
1919 #ifdef FLAC__SYMMETRIC_RICE
1920                         mean += partition_samples >> 1; /* for rounding effect */
1921                         mean /= partition_samples;
1922
1923                         /* calc rice_parameter = floor(log2(mean)) */
1924                         rice_parameter = 0;
1925                         mean>>=1;
1926                         while(mean) {
1927                                 rice_parameter++;
1928                                 mean >>= 1;
1929                         }
1930 #else
1931                         /* calc rice_parameter ala LOCO-I */
1932                         for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
1933                                 ;
1934 #endif
1935                         if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1936 #ifdef DEBUG
1937                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
1938 #endif
1939                                 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1940                         }
1941
1942 #ifndef NO_RICE_SEARCH
1943                         if(rice_parameter_search_dist) {
1944                                 if(rice_parameter < rice_parameter_search_dist)
1945                                         min_rice_parameter = 0;
1946                                 else
1947                                         min_rice_parameter = rice_parameter - rice_parameter_search_dist;
1948                                 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
1949                                 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1950 #ifdef DEBUG
1951                                         fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
1952 #endif
1953                                         max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1954                                 }
1955                         }
1956                         else
1957                                 min_rice_parameter = max_rice_parameter = rice_parameter;
1958
1959                         best_partition_bits = 0xffffffff;
1960                         for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
1961 #endif
1962 #ifdef VARIABLE_RICE_BITS
1963 #ifdef FLAC__SYMMETRIC_RICE
1964                                 partition_bits = (2+rice_parameter) * partition_samples;
1965 #else
1966                                 const unsigned rice_parameter_estimate = rice_parameter-1;
1967                                 partition_bits = (1+rice_parameter) * partition_samples;
1968 #endif
1969 #else
1970                                 partition_bits = 0;
1971 #endif
1972                                 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
1973                                 save_residual_sample = residual_sample;
1974                                 for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++) {
1975 #ifdef VARIABLE_RICE_BITS
1976 #ifdef FLAC__SYMMETRIC_RICE
1977                                         partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter);
1978 #else
1979                                         partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter_estimate);
1980 #endif
1981 #else
1982                                         partition_bits += FLAC__bitbuffer_rice_bits(residual[residual_sample], rice_parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
1983 #endif
1984                                 }
1985 #ifndef NO_RICE_SEARCH
1986                                 if(rice_parameter != max_rice_parameter)
1987                                         residual_sample = save_residual_sample;
1988                                 if(partition_bits < best_partition_bits) {
1989                                         best_rice_parameter = rice_parameter;
1990                                         best_partition_bits = partition_bits;
1991                                 }
1992                         }
1993 #endif
1994                         if(search_for_escapes) {
1995                                 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;
1996                                 if(flat_bits <= best_partition_bits) {
1997                                         raw_bits[partition] = raw_bits_per_partition[partition];
1998                                         best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
1999                                         best_partition_bits = flat_bits;
2000                                 }
2001                         }
2002                         parameters[partition] = best_rice_parameter;
2003                         bits_ += best_partition_bits;
2004                 }
2005         }
2006
2007         *bits = bits_;
2008         return true;
2009 }
2010
2011 unsigned stream_encoder_get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
2012 {
2013         unsigned i, shift;
2014         FLAC__int32 x = 0;
2015
2016         for(i = 0; i < samples && !(x&1); i++)
2017                 x |= signal[i];
2018
2019         if(x == 0) {
2020                 shift = 0;
2021         }
2022         else {
2023                 for(shift = 0; !(x&1); shift++)
2024                         x >>= 1;
2025         }
2026
2027         if(shift > 0) {
2028                 for(i = 0; i < samples; i++)
2029                          signal[i] >>= shift;
2030         }
2031
2032         return shift;
2033 }