fix memory leaks found with valgrind
[platform/upstream/flac.git] / src / libFLAC / stream_encoder.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000,2001,2002  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 <limits.h>
21 #include <stdio.h>
22 #include <stdlib.h> /* for malloc() */
23 #include <string.h> /* for memcpy() */
24 #include "FLAC/assert.h"
25 #include "FLAC/stream_decoder.h"
26 #include "protected/stream_encoder.h"
27 #include "private/bitbuffer.h"
28 #include "private/bitmath.h"
29 #include "private/crc.h"
30 #include "private/cpu.h"
31 #include "private/fixed.h"
32 #include "private/format.h"
33 #include "private/lpc.h"
34 #include "private/md5.h"
35 #include "private/memory.h"
36 #include "private/stream_encoder_framing.h"
37
38 #ifdef min
39 #undef min
40 #endif
41 #define min(x,y) ((x)<(y)?(x):(y))
42
43 #ifdef max
44 #undef max
45 #endif
46 #define max(x,y) ((x)>(y)?(x):(y))
47
48 typedef struct {
49         FLAC__int32 *data[FLAC__MAX_CHANNELS];
50         unsigned size; /* of each data[] in samples */
51         unsigned tail;
52 } verify_input_fifo;
53
54 typedef struct {
55         const FLAC__byte *data;
56         unsigned capacity;
57         unsigned bytes;
58 } verify_output;
59
60 typedef enum {
61         ENCODER_IN_MAGIC = 0,
62         ENCODER_IN_METADATA = 1,
63         ENCODER_IN_AUDIO = 2
64 } EncoderStateHint;
65
66 /***********************************************************************
67  *
68  * Private class method prototypes
69  *
70  ***********************************************************************/
71
72 static void set_defaults_(FLAC__StreamEncoder *encoder);
73 static void free_(FLAC__StreamEncoder *encoder);
74 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_size);
75 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples);
76 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame);
77 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame);
78
79 static FLAC__bool process_subframe_(
80         FLAC__StreamEncoder *encoder,
81         unsigned min_partition_order,
82         unsigned max_partition_order,
83         FLAC__bool precompute_partition_sums,
84         const FLAC__FrameHeader *frame_header,
85         unsigned subframe_bps,
86         const FLAC__int32 integer_signal[],
87         const FLAC__real real_signal[],
88         FLAC__Subframe *subframe[2],
89         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
90         FLAC__int32 *residual[2],
91         unsigned *best_subframe,
92         unsigned *best_bits
93 );
94
95 static FLAC__bool add_subframe_(
96         FLAC__StreamEncoder *encoder,
97         const FLAC__FrameHeader *frame_header,
98         unsigned subframe_bps,
99         const FLAC__Subframe *subframe,
100         FLAC__BitBuffer *frame
101 );
102
103 static unsigned evaluate_constant_subframe_(
104         const FLAC__int32 signal,
105         unsigned subframe_bps,
106         FLAC__Subframe *subframe
107 );
108
109 static unsigned evaluate_fixed_subframe_(
110         FLAC__StreamEncoder *encoder,
111         const FLAC__int32 signal[],
112         FLAC__int32 residual[],
113         FLAC__uint32 abs_residual[],
114         FLAC__uint64 abs_residual_partition_sums[],
115         unsigned raw_bits_per_partition[],
116         unsigned blocksize,
117         unsigned subframe_bps,
118         unsigned order,
119         unsigned rice_parameter,
120         unsigned min_partition_order,
121         unsigned max_partition_order,
122         FLAC__bool precompute_partition_sums,
123         FLAC__bool do_escape_coding,
124         unsigned rice_parameter_search_dist,
125         FLAC__Subframe *subframe,
126         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
127 );
128
129 static unsigned evaluate_lpc_subframe_(
130         FLAC__StreamEncoder *encoder,
131         const FLAC__int32 signal[],
132         FLAC__int32 residual[],
133         FLAC__uint32 abs_residual[],
134         FLAC__uint64 abs_residual_partition_sums[],
135         unsigned raw_bits_per_partition[],
136         const FLAC__real lp_coeff[],
137         unsigned blocksize,
138         unsigned subframe_bps,
139         unsigned order,
140         unsigned qlp_coeff_precision,
141         unsigned rice_parameter,
142         unsigned min_partition_order,
143         unsigned max_partition_order,
144         FLAC__bool precompute_partition_sums,
145         FLAC__bool do_escape_coding,
146         unsigned rice_parameter_search_dist,
147         FLAC__Subframe *subframe,
148         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
149 );
150
151 static unsigned evaluate_verbatim_subframe_(
152         const FLAC__int32 signal[],
153         unsigned blocksize,
154         unsigned subframe_bps,
155         FLAC__Subframe *subframe
156 );
157
158 static unsigned find_best_partition_order_(
159         struct FLAC__StreamEncoderPrivate *private_,
160         const FLAC__int32 residual[],
161         FLAC__uint32 abs_residual[],
162         FLAC__uint64 abs_residual_partition_sums[],
163         unsigned raw_bits_per_partition[],
164         unsigned residual_samples,
165         unsigned predictor_order,
166         unsigned rice_parameter,
167         unsigned min_partition_order,
168         unsigned max_partition_order,
169         FLAC__bool precompute_partition_sums,
170         FLAC__bool do_escape_coding,
171         unsigned rice_parameter_search_dist,
172         FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
173 );
174
175 static void precompute_partition_info_sums_(
176         const FLAC__uint32 abs_residual[],
177         FLAC__uint64 abs_residual_partition_sums[],
178         unsigned residual_samples,
179         unsigned predictor_order,
180         unsigned min_partition_order,
181         unsigned max_partition_order
182 );
183
184 static void precompute_partition_info_escapes_(
185         const FLAC__int32 residual[],
186         unsigned raw_bits_per_partition[],
187         unsigned residual_samples,
188         unsigned predictor_order,
189         unsigned min_partition_order,
190         unsigned max_partition_order
191 );
192
193 #ifdef DONT_ESTIMATE_RICE_BITS
194 static FLAC__bool set_partitioned_rice_(
195         const FLAC__uint32 abs_residual[],
196         const FLAC__int32 residual[],
197         const unsigned residual_samples,
198         const unsigned predictor_order,
199         const unsigned suggested_rice_parameter,
200         const unsigned rice_parameter_search_dist,
201         const unsigned partition_order,
202         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
203         unsigned *bits
204 );
205
206 static FLAC__bool set_partitioned_rice_with_precompute_(
207         const FLAC__int32 residual[],
208         const FLAC__uint64 abs_residual_partition_sums[],
209         const unsigned raw_bits_per_partition[],
210         const unsigned residual_samples,
211         const unsigned predictor_order,
212         const unsigned suggested_rice_parameter,
213         const unsigned rice_parameter_search_dist,
214         const unsigned partition_order,
215         const FLAC__bool search_for_escapes,
216         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
217         unsigned *bits
218 );
219 #else
220 static FLAC__bool set_partitioned_rice_(
221         const FLAC__uint32 abs_residual[],
222         const unsigned residual_samples,
223         const unsigned predictor_order,
224         const unsigned suggested_rice_parameter,
225         const unsigned rice_parameter_search_dist,
226         const unsigned partition_order,
227         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
228         unsigned *bits
229 );
230
231 static FLAC__bool set_partitioned_rice_with_precompute_(
232         const FLAC__uint32 abs_residual[],
233         const FLAC__uint64 abs_residual_partition_sums[],
234         const unsigned raw_bits_per_partition[],
235         const unsigned residual_samples,
236         const unsigned predictor_order,
237         const unsigned suggested_rice_parameter,
238         const unsigned rice_parameter_search_dist,
239         const unsigned partition_order,
240         const FLAC__bool search_for_escapes,
241         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
242         unsigned *bits
243 );
244 #endif
245
246 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
247
248 /* verify-related routines: */
249 static void append_to_verify_fifo_(
250         verify_input_fifo *fifo,
251         const FLAC__int32 * const input[],
252         unsigned input_offset,
253         unsigned channels,
254         unsigned wide_samples
255 );
256
257 static void append_to_verify_fifo_interleaved_(
258         verify_input_fifo *fifo,
259         const FLAC__int32 input[],
260         unsigned input_offset,
261         unsigned channels,
262         unsigned wide_samples
263 );
264
265 static FLAC__StreamDecoderReadStatus verify_read_callback_(
266         const FLAC__StreamDecoder *decoder,
267         FLAC__byte buffer[],
268         unsigned *bytes,
269         void *client_data
270 );
271
272 static FLAC__StreamDecoderWriteStatus verify_write_callback_(
273         const FLAC__StreamDecoder *decoder,
274         const FLAC__Frame *frame,
275         const FLAC__int32 * const buffer[],
276         void *client_data
277 );
278
279 static void verify_metadata_callback_(
280         const FLAC__StreamDecoder *decoder,
281         const FLAC__StreamMetadata *metadata,
282         void *client_data
283 );
284
285 static void verify_error_callback_(
286         const FLAC__StreamDecoder *decoder,
287         FLAC__StreamDecoderErrorStatus status,
288         void *client_data
289 );
290
291
292 /***********************************************************************
293  *
294  * Private class data
295  *
296  ***********************************************************************/
297
298 typedef struct FLAC__StreamEncoderPrivate {
299         unsigned input_capacity;                          /* current size (in samples) of the signal and residual buffers */
300         FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS];  /* the integer version of the input signal */
301         FLAC__int32 *integer_signal_mid_side[2];          /* the integer version of the mid-side input signal (stereo only) */
302         FLAC__real *real_signal[FLAC__MAX_CHANNELS];      /* the floating-point version of the input signal */
303         FLAC__real *real_signal_mid_side[2];              /* the floating-point version of the mid-side input signal (stereo only) */
304         unsigned subframe_bps[FLAC__MAX_CHANNELS];        /* the effective bits per sample of the input signal (stream bps - wasted bits) */
305         unsigned subframe_bps_mid_side[2];                /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
306         FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
307         FLAC__int32 *residual_workspace_mid_side[2][2];
308         FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
309         FLAC__Subframe subframe_workspace_mid_side[2][2];
310         FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
311         FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
312         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
313         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
314         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
315         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
316         unsigned best_subframe[FLAC__MAX_CHANNELS];       /* index into the above workspaces */
317         unsigned best_subframe_mid_side[2];
318         unsigned best_subframe_bits[FLAC__MAX_CHANNELS];  /* size in bits of the best subframe for each channel */
319         unsigned best_subframe_bits_mid_side[2];
320         FLAC__uint32 *abs_residual;                       /* workspace where abs(candidate residual) is stored */
321         FLAC__uint64 *abs_residual_partition_sums;        /* workspace where the sum of abs(candidate residual) for each partition is stored */
322         unsigned *raw_bits_per_partition;                 /* workspace where the sum of silog2(candidate residual) for each partition is stored */
323         FLAC__BitBuffer *frame;                           /* the current frame being worked on */
324         double loose_mid_side_stereo_frames_exact;        /* exact number of frames the encoder will use before trying both independent and mid/side frames again */
325         unsigned loose_mid_side_stereo_frames;            /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
326         unsigned loose_mid_side_stereo_frame_count;       /* number of frames using the current channel assignment */
327         FLAC__ChannelAssignment last_channel_assignment;
328         FLAC__StreamMetadata metadata;
329         unsigned current_sample_number;
330         unsigned current_frame_number;
331         struct MD5Context md5context;
332         FLAC__CPUInfo cpuinfo;
333         unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__real residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
334         void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
335         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[]);
336         void (*local_lpc_compute_residual_from_qlp_coefficients_64bit)(const FLAC__int32 data[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
337         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[]);
338         FLAC__bool use_wide_by_block;          /* use slow 64-bit versions of some functions because of the block size */
339         FLAC__bool use_wide_by_partition;      /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
340         FLAC__bool use_wide_by_order;          /* use slow 64-bit versions of some functions because of the lpc order */
341         FLAC__bool precompute_partition_sums;  /* our initial guess as to whether precomputing the partitions sums will be a speed improvement */
342         FLAC__bool disable_constant_subframes;
343         FLAC__bool disable_fixed_subframes;
344         FLAC__bool disable_verbatim_subframes;
345         FLAC__StreamEncoderWriteCallback write_callback;
346         FLAC__StreamEncoderMetadataCallback metadata_callback;
347         void *client_data;
348         /* unaligned (original) pointers to allocated data */
349         FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
350         FLAC__int32 *integer_signal_mid_side_unaligned[2];
351         FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS];
352         FLAC__real *real_signal_mid_side_unaligned[2];
353         FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
354         FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
355         FLAC__uint32 *abs_residual_unaligned;
356         FLAC__uint64 *abs_residual_partition_sums_unaligned;
357         unsigned *raw_bits_per_partition_unaligned;
358         /*
359          * These fields have been moved here from private function local
360          * declarations merely to save stack space during encoding.
361          */
362         FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
363         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
364         /*
365          * The data for the verify section
366          */
367         struct {
368                 FLAC__StreamDecoder *decoder;
369                 EncoderStateHint state_hint;
370                 FLAC__bool needs_magic_hack;
371                 verify_input_fifo input_fifo;
372                 verify_output output;
373                 struct {
374                         FLAC__uint64 absolute_sample;
375                         unsigned frame_number;
376                         unsigned channel;
377                         unsigned sample;
378                         FLAC__int32 expected;
379                         FLAC__int32 got;
380                 } error_stats;
381         } verify;
382         FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
383 } FLAC__StreamEncoderPrivate;
384
385 /***********************************************************************
386  *
387  * Public static class data
388  *
389  ***********************************************************************/
390
391 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
392         "FLAC__STREAM_ENCODER_OK",
393         "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
394         "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
395         "FLAC__STREAM_ENCODER_INVALID_CALLBACK",
396         "FLAC__STREAM_ENCODER_INVALID_NUMBER_OF_CHANNELS",
397         "FLAC__STREAM_ENCODER_INVALID_BITS_PER_SAMPLE",
398         "FLAC__STREAM_ENCODER_INVALID_SAMPLE_RATE",
399         "FLAC__STREAM_ENCODER_INVALID_BLOCK_SIZE",
400         "FLAC__STREAM_ENCODER_INVALID_MAX_LPC_ORDER",
401         "FLAC__STREAM_ENCODER_INVALID_QLP_COEFF_PRECISION",
402         "FLAC__STREAM_ENCODER_MID_SIDE_CHANNELS_MISMATCH",
403         "FLAC__STREAM_ENCODER_MID_SIDE_SAMPLE_SIZE_MISMATCH",
404         "FLAC__STREAM_ENCODER_ILLEGAL_MID_SIDE_FORCE",
405         "FLAC__STREAM_ENCODER_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
406         "FLAC__STREAM_ENCODER_NOT_STREAMABLE",
407         "FLAC__STREAM_ENCODER_FRAMING_ERROR",
408         "FLAC__STREAM_ENCODER_INVALID_METADATA",
409         "FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING",
410         "FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_WRITING",
411         "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR",
412         "FLAC__STREAM_ENCODER_ALREADY_INITIALIZED",
413         "FLAC__STREAM_ENCODER_UNINITIALIZED"
414 };
415
416 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
417         "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
418         "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
419 };
420
421 /***********************************************************************
422  *
423  * Class constructor/destructor
424  *
425  */
426 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new()
427 {
428         FLAC__StreamEncoder *encoder;
429         unsigned i;
430
431         FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
432
433         encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
434         if(encoder == 0) {
435                 return 0;
436         }
437
438         encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
439         if(encoder->protected_ == 0) {
440                 free(encoder);
441                 return 0;
442         }
443
444         encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
445         if(encoder->private_ == 0) {
446                 free(encoder->protected_);
447                 free(encoder);
448                 return 0;
449         }
450
451         encoder->private_->frame = FLAC__bitbuffer_new();
452         if(encoder->private_->frame == 0) {
453                 free(encoder->private_);
454                 free(encoder->protected_);
455                 free(encoder);
456                 return 0;
457         }
458
459         set_defaults_(encoder);
460
461         encoder->private_->is_being_deleted = false;
462
463         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
464                 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
465                 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
466         }
467         for(i = 0; i < 2; i++) {
468                 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
469                 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
470         }
471         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
472                 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
473                 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
474         }
475         for(i = 0; i < 2; i++) {
476                 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
477                 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
478         }
479
480         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
481                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
482                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
483         }
484         for(i = 0; i < 2; i++) {
485                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
486                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
487         }
488         for(i = 0; i < 2; i++)
489                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
490
491         encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
492
493         return encoder;
494 }
495
496 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
497 {
498         unsigned i;
499
500         FLAC__ASSERT(0 != encoder);
501         FLAC__ASSERT(0 != encoder->protected_);
502         FLAC__ASSERT(0 != encoder->private_);
503         FLAC__ASSERT(0 != encoder->private_->frame);
504
505         encoder->private_->is_being_deleted = true;
506
507         FLAC__stream_encoder_finish(encoder);
508
509         if(0 != encoder->private_->verify.decoder)
510                 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
511
512         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
513                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
514                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
515         }
516         for(i = 0; i < 2; i++) {
517                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
518                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
519         }
520         for(i = 0; i < 2; i++)
521                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
522
523         FLAC__bitbuffer_delete(encoder->private_->frame);
524         free(encoder->private_);
525         free(encoder->protected_);
526         free(encoder);
527 }
528
529 /***********************************************************************
530  *
531  * Public class methods
532  *
533  ***********************************************************************/
534
535 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_init(FLAC__StreamEncoder *encoder)
536 {
537         unsigned i;
538         FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment;
539
540         FLAC__ASSERT(0 != encoder);
541
542         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
543                 return encoder->protected_->state = FLAC__STREAM_ENCODER_ALREADY_INITIALIZED;
544
545         encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
546
547         if(0 == encoder->private_->write_callback || 0 == encoder->private_->metadata_callback)
548                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_CALLBACK;
549
550         if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
551                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_NUMBER_OF_CHANNELS;
552
553         if(encoder->protected_->do_mid_side_stereo && encoder->protected_->channels != 2)
554                 return encoder->protected_->state = FLAC__STREAM_ENCODER_MID_SIDE_CHANNELS_MISMATCH;
555
556         if(encoder->protected_->loose_mid_side_stereo && !encoder->protected_->do_mid_side_stereo)
557                 return encoder->protected_->state = FLAC__STREAM_ENCODER_ILLEGAL_MID_SIDE_FORCE;
558
559         if(encoder->protected_->bits_per_sample >= 32)
560                 encoder->protected_->do_mid_side_stereo = false; /* since we do 32-bit math, the side channel would have 33 bps and overflow */
561
562         if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
563                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_BITS_PER_SAMPLE;
564
565         if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
566                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_SAMPLE_RATE;
567
568         if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
569                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_BLOCK_SIZE;
570
571         if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
572                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_MAX_LPC_ORDER;
573
574         if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
575                 return encoder->protected_->state = FLAC__STREAM_ENCODER_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
576
577         if(encoder->protected_->qlp_coeff_precision == 0) {
578                 if(encoder->protected_->bits_per_sample < 16) {
579                         /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
580                         /* @@@ until then we'll make a guess */
581                         encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
582                 }
583                 else if(encoder->protected_->bits_per_sample == 16) {
584                         if(encoder->protected_->blocksize <= 192)
585                                 encoder->protected_->qlp_coeff_precision = 7;
586                         else if(encoder->protected_->blocksize <= 384)
587                                 encoder->protected_->qlp_coeff_precision = 8;
588                         else if(encoder->protected_->blocksize <= 576)
589                                 encoder->protected_->qlp_coeff_precision = 9;
590                         else if(encoder->protected_->blocksize <= 1152)
591                                 encoder->protected_->qlp_coeff_precision = 10;
592                         else if(encoder->protected_->blocksize <= 2304)
593                                 encoder->protected_->qlp_coeff_precision = 11;
594                         else if(encoder->protected_->blocksize <= 4608)
595                                 encoder->protected_->qlp_coeff_precision = 12;
596                         else
597                                 encoder->protected_->qlp_coeff_precision = 13;
598                 }
599                 else {
600                         if(encoder->protected_->blocksize <= 384)
601                                 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
602                         else if(encoder->protected_->blocksize <= 1152)
603                                 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
604                         else
605                                 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
606                 }
607                 FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
608         }
609         else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
610                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_QLP_COEFF_PRECISION;
611
612         if(encoder->protected_->streamable_subset) {
613                 if(
614                         encoder->protected_->blocksize != 192 &&
615                         encoder->protected_->blocksize != 576 &&
616                         encoder->protected_->blocksize != 1152 &&
617                         encoder->protected_->blocksize != 2304 &&
618                         encoder->protected_->blocksize != 4608 &&
619                         encoder->protected_->blocksize != 256 &&
620                         encoder->protected_->blocksize != 512 &&
621                         encoder->protected_->blocksize != 1024 &&
622                         encoder->protected_->blocksize != 2048 &&
623                         encoder->protected_->blocksize != 4096 &&
624                         encoder->protected_->blocksize != 8192 &&
625                         encoder->protected_->blocksize != 16384
626                 )
627                         return encoder->protected_->state = FLAC__STREAM_ENCODER_NOT_STREAMABLE;
628                 if(
629                         encoder->protected_->sample_rate != 8000 &&
630                         encoder->protected_->sample_rate != 16000 &&
631                         encoder->protected_->sample_rate != 22050 &&
632                         encoder->protected_->sample_rate != 24000 &&
633                         encoder->protected_->sample_rate != 32000 &&
634                         encoder->protected_->sample_rate != 44100 &&
635                         encoder->protected_->sample_rate != 48000 &&
636                         encoder->protected_->sample_rate != 96000
637                 )
638                         return encoder->protected_->state = FLAC__STREAM_ENCODER_NOT_STREAMABLE;
639                 if(
640                         encoder->protected_->bits_per_sample != 8 &&
641                         encoder->protected_->bits_per_sample != 12 &&
642                         encoder->protected_->bits_per_sample != 16 &&
643                         encoder->protected_->bits_per_sample != 20 &&
644                         encoder->protected_->bits_per_sample != 24
645                 )
646                         return encoder->protected_->state = FLAC__STREAM_ENCODER_NOT_STREAMABLE;
647                 if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
648                         return encoder->protected_->state = FLAC__STREAM_ENCODER_NOT_STREAMABLE;
649         }
650
651         if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
652                 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
653         if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
654                 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
655
656         /* validate metadata */
657         if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
658                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_METADATA;
659         metadata_has_seektable = false;
660         metadata_has_vorbis_comment = false;
661         for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
662                 if(encoder->protected_->metadata[i]->type >= FLAC__METADATA_TYPE_UNDEFINED)
663                         return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_METADATA;
664                 else if(encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_STREAMINFO)
665                         return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_METADATA;
666                 else if(encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
667                         if(metadata_has_seektable) /* only one is allowed */
668                                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_METADATA;
669                         metadata_has_seektable = true;
670                         if(!FLAC__format_seektable_is_legal(&encoder->protected_->metadata[i]->data.seek_table))
671                                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_METADATA;
672                 }
673                 else if(encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
674                         if(metadata_has_vorbis_comment) /* only one is allowed */
675                                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_METADATA;
676                         metadata_has_vorbis_comment = true;
677                 }
678                 else if(encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_CUESHEET) {
679                         if(!FLAC__format_cuesheet_is_legal(&encoder->protected_->metadata[i]->data.cue_sheet, /*check_cd_da_subset=*/false, /*violation=*/0))
680                                 return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_METADATA;
681                 }
682         }
683
684         encoder->private_->input_capacity = 0;
685         for(i = 0; i < encoder->protected_->channels; i++) {
686                 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
687                 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
688         }
689         for(i = 0; i < 2; i++) {
690                 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
691                 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
692         }
693         for(i = 0; i < encoder->protected_->channels; i++) {
694                 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
695                 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
696                 encoder->private_->best_subframe[i] = 0;
697         }
698         for(i = 0; i < 2; i++) {
699                 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
700                 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
701                 encoder->private_->best_subframe_mid_side[i] = 0;
702         }
703         encoder->private_->abs_residual_unaligned = encoder->private_->abs_residual = 0;
704         encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
705         encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
706         encoder->private_->loose_mid_side_stereo_frames_exact = (double)encoder->protected_->sample_rate * 0.4 / (double)encoder->protected_->blocksize;
707         encoder->private_->loose_mid_side_stereo_frames = (unsigned)(encoder->private_->loose_mid_side_stereo_frames_exact + 0.5);
708         if(encoder->private_->loose_mid_side_stereo_frames == 0)
709                 encoder->private_->loose_mid_side_stereo_frames = 1;
710         encoder->private_->loose_mid_side_stereo_frame_count = 0;
711         encoder->private_->current_sample_number = 0;
712         encoder->private_->current_frame_number = 0;
713
714         encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
715         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? */
716         encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
717
718         /*
719          * get the CPU info and set the function pointers
720          */
721         FLAC__cpu_info(&encoder->private_->cpuinfo);
722         /* first default to the non-asm routines */
723         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
724         encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
725         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
726         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
727         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
728         /* now override with asm where appropriate */
729 #ifndef FLAC__NO_ASM
730         if(encoder->private_->cpuinfo.use_asm) {
731 #ifdef FLAC__CPU_IA32
732                 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
733 #ifdef FLAC__HAS_NASM
734                 if(0 && encoder->private_->cpuinfo.data.ia32.sse) {
735                         if(encoder->protected_->max_lpc_order < 4)
736                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
737                         else if(encoder->protected_->max_lpc_order < 8)
738                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
739                         else if(encoder->protected_->max_lpc_order < 12)
740                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
741                         else
742                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
743                 }
744                 else if(encoder->private_->cpuinfo.data.ia32._3dnow)
745                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
746                 else
747                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
748                 if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
749                         encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
750                 if(encoder->private_->cpuinfo.data.ia32.mmx) {
751                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
752                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
753                 }
754                 else {
755                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
756                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
757                 }
758 #endif
759 #endif
760         }
761 #endif
762         /* finally override based on wide-ness if necessary */
763         if(encoder->private_->use_wide_by_block) {
764                 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
765         }
766
767         /* we require precompute_partition_sums if do_escape_coding because of their intertwined nature */
768         encoder->private_->precompute_partition_sums = (encoder->protected_->max_residual_partition_order > encoder->protected_->min_residual_partition_order) || encoder->protected_->do_escape_coding;
769
770         if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
771                 /* the above function sets the state for us in case of an error */
772                 return encoder->protected_->state;
773         }
774
775         if(!FLAC__bitbuffer_init(encoder->private_->frame))
776                 return encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
777
778         /*
779          * Set up the verify stuff if necessary
780          */
781         if(encoder->protected_->verify) {
782                 /*
783                  * First, set up the fifo which will hold the
784                  * original signal to compare against
785                  */
786                 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize;
787                 for(i = 0; i < encoder->protected_->channels; i++) {
788                         if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder->private_->verify.input_fifo.size)))
789                                 return encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
790                 }
791                 encoder->private_->verify.input_fifo.tail = 0;
792
793                 /*
794                  * Now set up a stream decoder for verification
795                  */
796                 encoder->private_->verify.decoder = FLAC__stream_decoder_new();
797                 if(0 == encoder->private_->verify.decoder)
798                         return encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
799
800                 FLAC__stream_decoder_set_read_callback(encoder->private_->verify.decoder, verify_read_callback_);
801                 FLAC__stream_decoder_set_write_callback(encoder->private_->verify.decoder, verify_write_callback_);
802                 FLAC__stream_decoder_set_metadata_callback(encoder->private_->verify.decoder, verify_metadata_callback_);
803                 FLAC__stream_decoder_set_error_callback(encoder->private_->verify.decoder, verify_error_callback_);
804                 FLAC__stream_decoder_set_client_data(encoder->private_->verify.decoder, encoder);
805                 if(FLAC__stream_decoder_init(encoder->private_->verify.decoder) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA)
806                         return encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
807         }
808         encoder->private_->verify.error_stats.absolute_sample = 0;
809         encoder->private_->verify.error_stats.frame_number = 0;
810         encoder->private_->verify.error_stats.channel = 0;
811         encoder->private_->verify.error_stats.sample = 0;
812         encoder->private_->verify.error_stats.expected = 0;
813         encoder->private_->verify.error_stats.got = 0;
814
815         /*
816          * write the stream header
817          */
818         if(encoder->protected_->verify)
819                 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
820         if(!FLAC__bitbuffer_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN))
821                 return encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
822         if(!write_bitbuffer_(encoder, 0)) {
823                 /* the above function sets the state for us in case of an error */
824                 return encoder->protected_->state;
825         }
826
827         /*
828          * write the STREAMINFO metadata block
829          */
830         if(encoder->protected_->verify)
831                 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
832         encoder->private_->metadata.type = FLAC__METADATA_TYPE_STREAMINFO;
833         encoder->private_->metadata.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
834         encoder->private_->metadata.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
835         encoder->private_->metadata.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
836         encoder->private_->metadata.data.stream_info.max_blocksize = encoder->protected_->blocksize;
837         encoder->private_->metadata.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
838         encoder->private_->metadata.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
839         encoder->private_->metadata.data.stream_info.sample_rate = encoder->protected_->sample_rate;
840         encoder->private_->metadata.data.stream_info.channels = encoder->protected_->channels;
841         encoder->private_->metadata.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
842         encoder->private_->metadata.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
843         memset(encoder->private_->metadata.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
844         MD5Init(&encoder->private_->md5context);
845         if(!FLAC__bitbuffer_clear(encoder->private_->frame))
846                 return encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
847         if(!FLAC__add_metadata_block(&encoder->private_->metadata, encoder->private_->frame))
848                 return encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
849         if(!write_bitbuffer_(encoder, 0)) {
850                 /* the above function sets the state for us in case of an error */
851                 return encoder->protected_->state;
852         }
853
854         /*
855          * Now that the STREAMINFO block is written, we can init this to an
856          * absurdly-high value...
857          */
858         encoder->private_->metadata.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
859         /* ... and clear this to 0 */
860         encoder->private_->metadata.data.stream_info.total_samples = 0;
861
862         /*
863          * Check to see if the supplied metadata contains a VORBIS_COMMENT;
864          * if not, we will write an empty one (FLAC__add_metadata_block()
865          * automatically supplies the vendor string).
866          */
867         if(!metadata_has_vorbis_comment) {
868                 FLAC__StreamMetadata vorbis_comment;
869                 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
870                 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
871                 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
872                 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
873                 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
874                 vorbis_comment.data.vorbis_comment.num_comments = 0;
875                 vorbis_comment.data.vorbis_comment.comments = 0;
876                 if(!FLAC__bitbuffer_clear(encoder->private_->frame))
877                         return encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
878                 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame))
879                         return encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
880                 if(!write_bitbuffer_(encoder, 0)) {
881                         /* the above function sets the state for us in case of an error */
882                         return encoder->protected_->state;
883                 }
884         }
885
886         /*
887          * write the user's metadata blocks
888          */
889         for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
890                 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
891                 if(!FLAC__bitbuffer_clear(encoder->private_->frame))
892                         return encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
893                 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame))
894                         return encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
895                 if(!write_bitbuffer_(encoder, 0)) {
896                         /* the above function sets the state for us in case of an error */
897                         return encoder->protected_->state;
898                 }
899         }
900
901         if(encoder->protected_->verify)
902                 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
903
904         return encoder->protected_->state;
905 }
906
907 FLAC_API void FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
908 {
909         FLAC__ASSERT(0 != encoder);
910
911         if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
912                 return;
913
914         if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
915                 if(encoder->private_->current_sample_number != 0) {
916                         encoder->protected_->blocksize = encoder->private_->current_sample_number;
917                         process_frame_(encoder, true); /* true => is last frame */
918                 }
919         }
920
921         MD5Final(encoder->private_->metadata.data.stream_info.md5sum, &encoder->private_->md5context);
922
923         if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
924                 encoder->private_->metadata_callback(encoder, &encoder->private_->metadata, encoder->private_->client_data);
925         }
926
927         if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder)
928                 FLAC__stream_decoder_finish(encoder->private_->verify.decoder);
929
930         free_(encoder);
931         set_defaults_(encoder);
932
933         encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
934 }
935
936 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
937 {
938         FLAC__ASSERT(0 != encoder);
939         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
940                 return false;
941         encoder->protected_->verify = value;
942         return true;
943 }
944
945 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
946 {
947         FLAC__ASSERT(0 != encoder);
948         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
949                 return false;
950         encoder->protected_->streamable_subset = value;
951         return true;
952 }
953
954 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
955 {
956         FLAC__ASSERT(0 != encoder);
957         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
958                 return false;
959         encoder->protected_->do_mid_side_stereo = value;
960         return true;
961 }
962
963 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
964 {
965         FLAC__ASSERT(0 != encoder);
966         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
967                 return false;
968         encoder->protected_->loose_mid_side_stereo = value;
969         return true;
970 }
971
972 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
973 {
974         FLAC__ASSERT(0 != encoder);
975         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
976                 return false;
977         encoder->protected_->channels = value;
978         return true;
979 }
980
981 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
982 {
983         FLAC__ASSERT(0 != encoder);
984         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
985                 return false;
986         encoder->protected_->bits_per_sample = value;
987         return true;
988 }
989
990 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
991 {
992         FLAC__ASSERT(0 != encoder);
993         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
994                 return false;
995         encoder->protected_->sample_rate = value;
996         return true;
997 }
998
999 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1000 {
1001         FLAC__ASSERT(0 != encoder);
1002         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1003                 return false;
1004         encoder->protected_->blocksize = value;
1005         return true;
1006 }
1007
1008 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1009 {
1010         FLAC__ASSERT(0 != encoder);
1011         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1012                 return false;
1013         encoder->protected_->max_lpc_order = value;
1014         return true;
1015 }
1016
1017 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1018 {
1019         FLAC__ASSERT(0 != encoder);
1020         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1021                 return false;
1022         encoder->protected_->qlp_coeff_precision = value;
1023         return true;
1024 }
1025
1026 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1027 {
1028         FLAC__ASSERT(0 != encoder);
1029         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1030                 return false;
1031         encoder->protected_->do_qlp_coeff_prec_search = value;
1032         return true;
1033 }
1034
1035 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1036 {
1037         FLAC__ASSERT(0 != encoder);
1038         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1039                 return false;
1040 #if 0
1041         /*@@@ deprecated: */
1042         encoder->protected_->do_escape_coding = value;
1043 #else
1044         (void)value;
1045 #endif
1046         return true;
1047 }
1048
1049 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1050 {
1051         FLAC__ASSERT(0 != encoder);
1052         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1053                 return false;
1054         encoder->protected_->do_exhaustive_model_search = value;
1055         return true;
1056 }
1057
1058 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1059 {
1060         FLAC__ASSERT(0 != encoder);
1061         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1062                 return false;
1063         encoder->protected_->min_residual_partition_order = value;
1064         return true;
1065 }
1066
1067 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1068 {
1069         FLAC__ASSERT(0 != encoder);
1070         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1071                 return false;
1072         encoder->protected_->max_residual_partition_order = value;
1073         return true;
1074 }
1075
1076 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1077 {
1078         FLAC__ASSERT(0 != encoder);
1079         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1080                 return false;
1081 #if 0
1082         /*@@@ deprecated: */
1083         encoder->protected_->rice_parameter_search_dist = value;
1084 #else
1085         (void)value;
1086 #endif
1087         return true;
1088 }
1089
1090 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1091 {
1092         FLAC__ASSERT(0 != encoder);
1093         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1094                 return false;
1095         encoder->protected_->total_samples_estimate = value;
1096         return true;
1097 }
1098
1099 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1100 {
1101         FLAC__ASSERT(0 != encoder);
1102         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1103                 return false;
1104         encoder->protected_->metadata = metadata;
1105         encoder->protected_->num_metadata_blocks = num_blocks;
1106         return true;
1107 }
1108
1109 FLAC_API FLAC__bool FLAC__stream_encoder_set_write_callback(FLAC__StreamEncoder *encoder, FLAC__StreamEncoderWriteCallback value)
1110 {
1111         FLAC__ASSERT(0 != encoder);
1112         FLAC__ASSERT(0 != value);
1113         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1114                 return false;
1115         encoder->private_->write_callback = value;
1116         return true;
1117 }
1118
1119 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata_callback(FLAC__StreamEncoder *encoder, FLAC__StreamEncoderMetadataCallback value)
1120 {
1121         FLAC__ASSERT(0 != encoder);
1122         FLAC__ASSERT(0 != value);
1123         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1124                 return false;
1125         encoder->private_->metadata_callback = value;
1126         return true;
1127 }
1128
1129 FLAC_API FLAC__bool FLAC__stream_encoder_set_client_data(FLAC__StreamEncoder *encoder, void *value)
1130 {
1131         FLAC__ASSERT(0 != encoder);
1132         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1133                 return false;
1134         encoder->private_->client_data = value;
1135         return true;
1136 }
1137
1138 /*
1139  * These three functions are not static, but not publically exposed in
1140  * include/FLAC/ either.  They are used by the test suite.
1141  */
1142 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1143 {
1144         FLAC__ASSERT(0 != encoder);
1145         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1146                 return false;
1147         encoder->private_->disable_constant_subframes = value;
1148         return true;
1149 }
1150
1151 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1152 {
1153         FLAC__ASSERT(0 != encoder);
1154         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1155                 return false;
1156         encoder->private_->disable_fixed_subframes = value;
1157         return true;
1158 }
1159
1160 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1161 {
1162         FLAC__ASSERT(0 != encoder);
1163         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1164                 return false;
1165         encoder->private_->disable_verbatim_subframes = value;
1166         return true;
1167 }
1168
1169 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1170 {
1171         FLAC__ASSERT(0 != encoder);
1172         return encoder->protected_->state;
1173 }
1174
1175 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1176 {
1177         FLAC__ASSERT(0 != encoder);
1178         if(encoder->protected_->verify)
1179                 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1180         else
1181                 return FLAC__STREAM_DECODER_UNINITIALIZED;
1182 }
1183
1184 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1185 {
1186         if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1187                 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1188         else
1189                 return FLAC__StreamDecoderStateString[FLAC__stream_decoder_get_state(encoder->private_->verify.decoder)];
1190 }
1191
1192 FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got)
1193 {
1194         FLAC__ASSERT(0 != encoder);
1195         if(0 != absolute_sample)
1196                 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1197         if(0 != frame_number)
1198                 *frame_number = encoder->private_->verify.error_stats.frame_number;
1199         if(0 != channel)
1200                 *channel = encoder->private_->verify.error_stats.channel;
1201         if(0 != sample)
1202                 *sample = encoder->private_->verify.error_stats.sample;
1203         if(0 != expected)
1204                 *expected = encoder->private_->verify.error_stats.expected;
1205         if(0 != got)
1206                 *got = encoder->private_->verify.error_stats.got;
1207 }
1208
1209 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1210 {
1211         FLAC__ASSERT(0 != encoder);
1212         return encoder->protected_->verify;
1213 }
1214
1215 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1216 {
1217         FLAC__ASSERT(0 != encoder);
1218         return encoder->protected_->streamable_subset;
1219 }
1220
1221 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1222 {
1223         FLAC__ASSERT(0 != encoder);
1224         return encoder->protected_->do_mid_side_stereo;
1225 }
1226
1227 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1228 {
1229         FLAC__ASSERT(0 != encoder);
1230         return encoder->protected_->loose_mid_side_stereo;
1231 }
1232
1233 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1234 {
1235         FLAC__ASSERT(0 != encoder);
1236         return encoder->protected_->channels;
1237 }
1238
1239 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1240 {
1241         FLAC__ASSERT(0 != encoder);
1242         return encoder->protected_->bits_per_sample;
1243 }
1244
1245 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1246 {
1247         FLAC__ASSERT(0 != encoder);
1248         return encoder->protected_->sample_rate;
1249 }
1250
1251 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1252 {
1253         FLAC__ASSERT(0 != encoder);
1254         return encoder->protected_->blocksize;
1255 }
1256
1257 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1258 {
1259         FLAC__ASSERT(0 != encoder);
1260         return encoder->protected_->max_lpc_order;
1261 }
1262
1263 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1264 {
1265         FLAC__ASSERT(0 != encoder);
1266         return encoder->protected_->qlp_coeff_precision;
1267 }
1268
1269 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1270 {
1271         FLAC__ASSERT(0 != encoder);
1272         return encoder->protected_->do_qlp_coeff_prec_search;
1273 }
1274
1275 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1276 {
1277         FLAC__ASSERT(0 != encoder);
1278         return encoder->protected_->do_escape_coding;
1279 }
1280
1281 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1282 {
1283         FLAC__ASSERT(0 != encoder);
1284         return encoder->protected_->do_exhaustive_model_search;
1285 }
1286
1287 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1288 {
1289         FLAC__ASSERT(0 != encoder);
1290         return encoder->protected_->min_residual_partition_order;
1291 }
1292
1293 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1294 {
1295         FLAC__ASSERT(0 != encoder);
1296         return encoder->protected_->max_residual_partition_order;
1297 }
1298
1299 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1300 {
1301         FLAC__ASSERT(0 != encoder);
1302         return encoder->protected_->rice_parameter_search_dist;
1303 }
1304
1305 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1306 {
1307         FLAC__ASSERT(0 != encoder);
1308         return encoder->protected_->total_samples_estimate;
1309 }
1310
1311 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1312 {
1313         unsigned i, j, channel;
1314         FLAC__int32 x, mid, side;
1315         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1316
1317         FLAC__ASSERT(0 != encoder);
1318         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1319
1320         j = 0;
1321         if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1322                 do {
1323                         if(encoder->protected_->verify)
1324                                 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1325
1326                         for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1327                                 x = mid = side = buffer[0][j];
1328                                 encoder->private_->integer_signal[0][i] = x;
1329                                 encoder->private_->real_signal[0][i] = (FLAC__real)x;
1330                                 x = buffer[1][j];
1331                                 encoder->private_->integer_signal[1][i] = x;
1332                                 encoder->private_->real_signal[1][i] = (FLAC__real)x;
1333                                 mid += x;
1334                                 side -= x;
1335                                 mid >>= 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
1336                                 encoder->private_->integer_signal_mid_side[1][i] = side;
1337                                 encoder->private_->integer_signal_mid_side[0][i] = mid;
1338                                 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
1339                                 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
1340                                 encoder->private_->current_sample_number++;
1341                         }
1342                         if(i == blocksize) {
1343                                 if(!process_frame_(encoder, false)) /* false => not last frame */
1344                                         return false;
1345                         }
1346                 } while(j < samples);
1347         }
1348         else {
1349                 do {
1350                         if(encoder->protected_->verify)
1351                                 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1352
1353                         for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1354                                 for(channel = 0; channel < channels; channel++) {
1355                                         x = buffer[channel][j];
1356                                         encoder->private_->integer_signal[channel][i] = x;
1357                                         encoder->private_->real_signal[channel][i] = (FLAC__real)x;
1358                                 }
1359                                 encoder->private_->current_sample_number++;
1360                         }
1361                         if(i == blocksize) {
1362                                 if(!process_frame_(encoder, false)) /* false => not last frame */
1363                                         return false;
1364                         }
1365                 } while(j < samples);
1366         }
1367
1368         return true;
1369 }
1370
1371 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
1372 {
1373         unsigned i, j, k, channel;
1374         FLAC__int32 x, mid, side;
1375         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1376
1377         FLAC__ASSERT(0 != encoder);
1378         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1379
1380         j = k = 0;
1381         if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1382                 do {
1383                         if(encoder->protected_->verify)
1384                                 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1385
1386                         for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1387                                 x = mid = side = buffer[k++];
1388                                 encoder->private_->integer_signal[0][i] = x;
1389                                 encoder->private_->real_signal[0][i] = (FLAC__real)x;
1390                                 x = buffer[k++];
1391                                 encoder->private_->integer_signal[1][i] = x;
1392                                 encoder->private_->real_signal[1][i] = (FLAC__real)x;
1393                                 mid += x;
1394                                 side -= x;
1395                                 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
1396                                 encoder->private_->integer_signal_mid_side[1][i] = side;
1397                                 encoder->private_->integer_signal_mid_side[0][i] = mid;
1398                                 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
1399                                 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
1400                                 encoder->private_->current_sample_number++;
1401                         }
1402                         if(i == blocksize) {
1403                                 if(!process_frame_(encoder, false)) /* false => not last frame */
1404                                         return false;
1405                         }
1406                 } while(j < samples);
1407         }
1408         else {
1409                 do {
1410                         if(encoder->protected_->verify)
1411                                 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1412
1413                         for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1414                                 for(channel = 0; channel < channels; channel++) {
1415                                         x = buffer[k++];
1416                                         encoder->private_->integer_signal[channel][i] = x;
1417                                         encoder->private_->real_signal[channel][i] = (FLAC__real)x;
1418                                 }
1419                                 encoder->private_->current_sample_number++;
1420                         }
1421                         if(i == blocksize) {
1422                                 if(!process_frame_(encoder, false)) /* false => not last frame */
1423                                         return false;
1424                         }
1425                 } while(j < samples);
1426         }
1427
1428         return true;
1429 }
1430
1431 /***********************************************************************
1432  *
1433  * Private class methods
1434  *
1435  ***********************************************************************/
1436
1437 void set_defaults_(FLAC__StreamEncoder *encoder)
1438 {
1439         FLAC__ASSERT(0 != encoder);
1440
1441         encoder->protected_->verify = false;
1442         encoder->protected_->streamable_subset = true;
1443         encoder->protected_->do_mid_side_stereo = false;
1444         encoder->protected_->loose_mid_side_stereo = false;
1445         encoder->protected_->channels = 2;
1446         encoder->protected_->bits_per_sample = 16;
1447         encoder->protected_->sample_rate = 44100;
1448         encoder->protected_->blocksize = 1152;
1449         encoder->protected_->max_lpc_order = 0;
1450         encoder->protected_->qlp_coeff_precision = 0;
1451         encoder->protected_->do_qlp_coeff_prec_search = false;
1452         encoder->protected_->do_exhaustive_model_search = false;
1453         encoder->protected_->do_escape_coding = false;
1454         encoder->protected_->min_residual_partition_order = 0;
1455         encoder->protected_->max_residual_partition_order = 0;
1456         encoder->protected_->rice_parameter_search_dist = 0;
1457         encoder->protected_->total_samples_estimate = 0;
1458         encoder->protected_->metadata = 0;
1459         encoder->protected_->num_metadata_blocks = 0;
1460
1461         encoder->private_->disable_constant_subframes = false;
1462         encoder->private_->disable_fixed_subframes = false;
1463         encoder->private_->disable_verbatim_subframes = false;
1464         encoder->private_->write_callback = 0;
1465         encoder->private_->metadata_callback = 0;
1466         encoder->private_->client_data = 0;
1467 }
1468
1469 void free_(FLAC__StreamEncoder *encoder)
1470 {
1471         unsigned i, channel;
1472
1473         FLAC__ASSERT(0 != encoder);
1474         for(i = 0; i < encoder->protected_->channels; i++) {
1475                 if(0 != encoder->private_->integer_signal_unaligned[i]) {
1476                         free(encoder->private_->integer_signal_unaligned[i]);
1477                         encoder->private_->integer_signal_unaligned[i] = 0;
1478                 }
1479                 if(0 != encoder->private_->real_signal_unaligned[i]) {
1480                         free(encoder->private_->real_signal_unaligned[i]);
1481                         encoder->private_->real_signal_unaligned[i] = 0;
1482                 }
1483         }
1484         for(i = 0; i < 2; i++) {
1485                 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
1486                         free(encoder->private_->integer_signal_mid_side_unaligned[i]);
1487                         encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
1488                 }
1489                 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
1490                         free(encoder->private_->real_signal_mid_side_unaligned[i]);
1491                         encoder->private_->real_signal_mid_side_unaligned[i] = 0;
1492                 }
1493         }
1494         for(channel = 0; channel < encoder->protected_->channels; channel++) {
1495                 for(i = 0; i < 2; i++) {
1496                         if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
1497                                 free(encoder->private_->residual_workspace_unaligned[channel][i]);
1498                                 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
1499                         }
1500                 }
1501         }
1502         for(channel = 0; channel < 2; channel++) {
1503                 for(i = 0; i < 2; i++) {
1504                         if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
1505                                 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
1506                                 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
1507                         }
1508                 }
1509         }
1510         if(0 != encoder->private_->abs_residual_unaligned) {
1511                 free(encoder->private_->abs_residual_unaligned);
1512                 encoder->private_->abs_residual_unaligned = 0;
1513         }
1514         if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
1515                 free(encoder->private_->abs_residual_partition_sums_unaligned);
1516                 encoder->private_->abs_residual_partition_sums_unaligned = 0;
1517         }
1518         if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
1519                 free(encoder->private_->raw_bits_per_partition_unaligned);
1520                 encoder->private_->raw_bits_per_partition_unaligned = 0;
1521         }
1522         if(encoder->protected_->verify) {
1523                 for(i = 0; i < encoder->protected_->channels; i++) {
1524                         if(0 != encoder->private_->verify.input_fifo.data[i]) {
1525                                 free(encoder->private_->verify.input_fifo.data[i]);
1526                                 encoder->private_->verify.input_fifo.data[i] = 0;
1527                         }
1528                 }
1529         }
1530         FLAC__bitbuffer_free(encoder->private_->frame);
1531 }
1532
1533 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_size)
1534 {
1535         FLAC__bool ok;
1536         unsigned i, channel;
1537
1538         FLAC__ASSERT(new_size > 0);
1539         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1540         FLAC__ASSERT(encoder->private_->current_sample_number == 0);
1541
1542         /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
1543         if(new_size <= encoder->private_->input_capacity)
1544                 return true;
1545
1546         ok = true;
1547
1548         /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
1549          * requires that the input arrays (in our case the integer signals)
1550          * have a buffer of up to 3 zeroes in front (at negative indices) for
1551          * alignment purposes; we use 4 to keep the data well-aligned.
1552          */
1553
1554         for(i = 0; ok && i < encoder->protected_->channels; i++) {
1555                 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size+4, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
1556                 ok = ok && FLAC__memory_alloc_aligned_real_array(new_size, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
1557                 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
1558                 encoder->private_->integer_signal[i] += 4;
1559         }
1560         for(i = 0; ok && i < 2; i++) {
1561                 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]);
1562                 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]);
1563                 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
1564                 encoder->private_->integer_signal_mid_side[i] += 4;
1565         }
1566         for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
1567                 for(i = 0; ok && i < 2; i++) {
1568                         ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
1569                 }
1570         }
1571         for(channel = 0; ok && channel < 2; channel++) {
1572                 for(i = 0; ok && i < 2; i++) {
1573                         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]);
1574                 }
1575         }
1576         ok = ok && FLAC__memory_alloc_aligned_uint32_array(new_size, &encoder->private_->abs_residual_unaligned, &encoder->private_->abs_residual);
1577         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 */
1578                 ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_size * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
1579         if(encoder->protected_->do_escape_coding)
1580                 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_size * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
1581
1582         if(ok)
1583                 encoder->private_->input_capacity = new_size;
1584         else
1585                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1586
1587         return ok;
1588 }
1589
1590 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples)
1591 {
1592         const FLAC__byte *buffer;
1593         unsigned bytes;
1594
1595         FLAC__ASSERT(FLAC__bitbuffer_is_byte_aligned(encoder->private_->frame));
1596
1597         FLAC__bitbuffer_get_buffer(encoder->private_->frame, &buffer, &bytes);
1598
1599         if(encoder->protected_->verify) {
1600                 encoder->private_->verify.output.data = buffer;
1601                 encoder->private_->verify.output.bytes = bytes;
1602                 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
1603                         encoder->private_->verify.needs_magic_hack = true;
1604                 }
1605                 else {
1606                         if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
1607                                 FLAC__bitbuffer_release_buffer(encoder->private_->frame);
1608                                 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
1609                                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1610                                 return false;
1611                         }
1612                 }
1613         }
1614
1615         if(encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
1616                 encoder->protected_->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_WRITING;
1617                 return false;
1618         }
1619
1620         FLAC__bitbuffer_release_buffer(encoder->private_->frame);
1621
1622         if(samples > 0) {
1623                 encoder->private_->metadata.data.stream_info.min_framesize = min(bytes, encoder->private_->metadata.data.stream_info.min_framesize);
1624                 encoder->private_->metadata.data.stream_info.max_framesize = max(bytes, encoder->private_->metadata.data.stream_info.max_framesize);
1625         }
1626
1627         return true;
1628 }
1629
1630 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame)
1631 {
1632         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1633
1634         /*
1635          * Accumulate raw signal to the MD5 signature
1636          */
1637         if(!FLAC__MD5Accumulate(&encoder->private_->md5context, (const FLAC__int32 * const *)encoder->private_->integer_signal, encoder->protected_->channels, encoder->protected_->blocksize, (encoder->protected_->bits_per_sample+7) / 8)) {
1638                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1639                 return false;
1640         }
1641
1642         /*
1643          * Process the frame header and subframes into the frame bitbuffer
1644          */
1645         if(!process_subframes_(encoder, is_last_frame)) {
1646                 /* the above function sets the state for us in case of an error */
1647                 return false;
1648         }
1649
1650         /*
1651          * Zero-pad the frame to a byte_boundary
1652          */
1653         if(!FLAC__bitbuffer_zero_pad_to_byte_boundary(encoder->private_->frame)) {
1654                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1655                 return false;
1656         }
1657
1658         /*
1659          * CRC-16 the whole thing
1660          */
1661         FLAC__ASSERT(FLAC__bitbuffer_is_byte_aligned(encoder->private_->frame));
1662         FLAC__bitbuffer_write_raw_uint32(encoder->private_->frame, FLAC__bitbuffer_get_write_crc16(encoder->private_->frame), FLAC__FRAME_FOOTER_CRC_LEN);
1663
1664         /*
1665          * Write it
1666          */
1667         if(!write_bitbuffer_(encoder, encoder->protected_->blocksize)) {
1668                 /* the above function sets the state for us in case of an error */
1669                 return false;
1670         }
1671
1672         /*
1673          * Get ready for the next frame
1674          */
1675         encoder->private_->current_sample_number = 0;
1676         encoder->private_->current_frame_number++;
1677         encoder->private_->metadata.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
1678
1679         return true;
1680 }
1681
1682 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame)
1683 {
1684         FLAC__FrameHeader frame_header;
1685         unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
1686         FLAC__bool do_independent, do_mid_side, precompute_partition_sums;
1687
1688         /*
1689          * Calculate the min,max Rice partition orders
1690          */
1691         if(is_last_frame) {
1692                 max_partition_order = 0;
1693         }
1694         else {
1695                 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
1696                 max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
1697         }
1698         min_partition_order = min(min_partition_order, max_partition_order);
1699
1700         precompute_partition_sums = encoder->private_->precompute_partition_sums && ((max_partition_order > min_partition_order) || encoder->protected_->do_escape_coding);
1701
1702         /*
1703          * Setup the frame
1704          */
1705         if(!FLAC__bitbuffer_clear(encoder->private_->frame)) {
1706                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1707                 return false;
1708         }
1709         frame_header.blocksize = encoder->protected_->blocksize;
1710         frame_header.sample_rate = encoder->protected_->sample_rate;
1711         frame_header.channels = encoder->protected_->channels;
1712         frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
1713         frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
1714         frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
1715         frame_header.number.frame_number = encoder->private_->current_frame_number;
1716
1717         /*
1718          * Figure out what channel assignments to try
1719          */
1720         if(encoder->protected_->do_mid_side_stereo) {
1721                 if(encoder->protected_->loose_mid_side_stereo) {
1722                         if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
1723                                 do_independent = true;
1724                                 do_mid_side = true;
1725                         }
1726                         else {
1727                                 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
1728                                 do_mid_side = !do_independent;
1729                         }
1730                 }
1731                 else {
1732                         do_independent = true;
1733                         do_mid_side = true;
1734                 }
1735         }
1736         else {
1737                 do_independent = true;
1738                 do_mid_side = false;
1739         }
1740
1741         FLAC__ASSERT(do_independent || do_mid_side);
1742
1743         /*
1744          * Check for wasted bits; set effective bps for each subframe
1745          */
1746         if(do_independent) {
1747                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
1748                         const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
1749                         encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
1750                         encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
1751                 }
1752         }
1753         if(do_mid_side) {
1754                 FLAC__ASSERT(encoder->protected_->channels == 2);
1755                 for(channel = 0; channel < 2; channel++) {
1756                         const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
1757                         encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
1758                         encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
1759                 }
1760         }
1761
1762         /*
1763          * First do a normal encoding pass of each independent channel
1764          */
1765         if(do_independent) {
1766                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
1767                         if(!
1768                                 process_subframe_(
1769                                         encoder,
1770                                         min_partition_order,
1771                                         max_partition_order,
1772                                         precompute_partition_sums,
1773                                         &frame_header,
1774                                         encoder->private_->subframe_bps[channel],
1775                                         encoder->private_->integer_signal[channel],
1776                                         encoder->private_->real_signal[channel],
1777                                         encoder->private_->subframe_workspace_ptr[channel],
1778                                         encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
1779                                         encoder->private_->residual_workspace[channel],
1780                                         encoder->private_->best_subframe+channel,
1781                                         encoder->private_->best_subframe_bits+channel
1782                                 )
1783                         )
1784                                 return false;
1785                 }
1786         }
1787
1788         /*
1789          * Now do mid and side channels if requested
1790          */
1791         if(do_mid_side) {
1792                 FLAC__ASSERT(encoder->protected_->channels == 2);
1793
1794                 for(channel = 0; channel < 2; channel++) {
1795                         if(!
1796                                 process_subframe_(
1797                                         encoder,
1798                                         min_partition_order,
1799                                         max_partition_order,
1800                                         precompute_partition_sums,
1801                                         &frame_header,
1802                                         encoder->private_->subframe_bps_mid_side[channel],
1803                                         encoder->private_->integer_signal_mid_side[channel],
1804                                         encoder->private_->real_signal_mid_side[channel],
1805                                         encoder->private_->subframe_workspace_ptr_mid_side[channel],
1806                                         encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
1807                                         encoder->private_->residual_workspace_mid_side[channel],
1808                                         encoder->private_->best_subframe_mid_side+channel,
1809                                         encoder->private_->best_subframe_bits_mid_side+channel
1810                                 )
1811                         )
1812                                 return false;
1813                 }
1814         }
1815
1816         /*
1817          * Compose the frame bitbuffer
1818          */
1819         if(do_mid_side) {
1820                 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
1821                 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
1822                 FLAC__ChannelAssignment channel_assignment;
1823
1824                 FLAC__ASSERT(encoder->protected_->channels == 2);
1825
1826                 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
1827                         channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
1828                 }
1829                 else {
1830                         unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
1831                         unsigned min_bits;
1832                         FLAC__ChannelAssignment ca;
1833
1834                         FLAC__ASSERT(do_independent && do_mid_side);
1835
1836                         /* We have to figure out which channel assignent results in the smallest frame */
1837                         bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits         [1];
1838                         bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE  ] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits_mid_side[1];
1839                         bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits         [1] + encoder->private_->best_subframe_bits_mid_side[1];
1840                         bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE   ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
1841
1842                         for(channel_assignment = (FLAC__ChannelAssignment)0, min_bits = bits[0], ca = (FLAC__ChannelAssignment)1; (int)ca <= 3; ca = (FLAC__ChannelAssignment)((int)ca + 1)) {
1843                                 if(bits[ca] < min_bits) {
1844                                         min_bits = bits[ca];
1845                                         channel_assignment = ca;
1846                                 }
1847                         }
1848                 }
1849
1850                 frame_header.channel_assignment = channel_assignment;
1851
1852                 if(!FLAC__frame_add_header(&frame_header, encoder->protected_->streamable_subset, is_last_frame, encoder->private_->frame)) {
1853                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1854                         return false;
1855                 }
1856
1857                 switch(channel_assignment) {
1858                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1859                                 left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
1860                                 right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
1861                                 break;
1862                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1863                                 left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
1864                                 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
1865                                 break;
1866                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1867                                 left_subframe  = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
1868                                 right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
1869                                 break;
1870                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1871                                 left_subframe  = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
1872                                 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
1873                                 break;
1874                         default:
1875                                 FLAC__ASSERT(0);
1876                 }
1877
1878                 switch(channel_assignment) {
1879                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1880                                 left_bps  = encoder->private_->subframe_bps         [0];
1881                                 right_bps = encoder->private_->subframe_bps         [1];
1882                                 break;
1883                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1884                                 left_bps  = encoder->private_->subframe_bps         [0];
1885                                 right_bps = encoder->private_->subframe_bps_mid_side[1];
1886                                 break;
1887                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1888                                 left_bps  = encoder->private_->subframe_bps_mid_side[1];
1889                                 right_bps = encoder->private_->subframe_bps         [1];
1890                                 break;
1891                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1892                                 left_bps  = encoder->private_->subframe_bps_mid_side[0];
1893                                 right_bps = encoder->private_->subframe_bps_mid_side[1];
1894                                 break;
1895                         default:
1896                                 FLAC__ASSERT(0);
1897                 }
1898
1899                 /* note that encoder_add_subframe_ sets the state for us in case of an error */
1900                 if(!add_subframe_(encoder, &frame_header, left_bps , left_subframe , encoder->private_->frame))
1901                         return false;
1902                 if(!add_subframe_(encoder, &frame_header, right_bps, right_subframe, encoder->private_->frame))
1903                         return false;
1904         }
1905         else {
1906                 if(!FLAC__frame_add_header(&frame_header, encoder->protected_->streamable_subset, is_last_frame, encoder->private_->frame)) {
1907                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1908                         return false;
1909                 }
1910
1911                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
1912                         if(!add_subframe_(encoder, &frame_header, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame)) {
1913                                 /* the above function sets the state for us in case of an error */
1914                                 return false;
1915                         }
1916                 }
1917         }
1918
1919         if(encoder->protected_->loose_mid_side_stereo) {
1920                 encoder->private_->loose_mid_side_stereo_frame_count++;
1921                 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
1922                         encoder->private_->loose_mid_side_stereo_frame_count = 0;
1923         }
1924
1925         encoder->private_->last_channel_assignment = frame_header.channel_assignment;
1926
1927         return true;
1928 }
1929
1930 FLAC__bool process_subframe_(
1931         FLAC__StreamEncoder *encoder,
1932         unsigned min_partition_order,
1933         unsigned max_partition_order,
1934         FLAC__bool precompute_partition_sums,
1935         const FLAC__FrameHeader *frame_header,
1936         unsigned subframe_bps,
1937         const FLAC__int32 integer_signal[],
1938         const FLAC__real real_signal[],
1939         FLAC__Subframe *subframe[2],
1940         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
1941         FLAC__int32 *residual[2],
1942         unsigned *best_subframe,
1943         unsigned *best_bits
1944 )
1945 {
1946         FLAC__real fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
1947         FLAC__real lpc_residual_bits_per_sample;
1948         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 */
1949         FLAC__real lpc_error[FLAC__MAX_LPC_ORDER];
1950         unsigned min_lpc_order, max_lpc_order, lpc_order;
1951         unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
1952         unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
1953         unsigned rice_parameter;
1954         unsigned _candidate_bits, _best_bits;
1955         unsigned _best_subframe;
1956
1957         /* verbatim subframe is the baseline against which we measure other compressed subframes */
1958         _best_subframe = 0;
1959         if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
1960                 _best_bits = UINT_MAX;
1961         else
1962                 _best_bits = evaluate_verbatim_subframe_(integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
1963
1964         if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
1965                 unsigned signal_is_constant = false;
1966                 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);
1967                 /* check for constant subframe */
1968                 if(!encoder->private_->disable_constant_subframes && fixed_residual_bits_per_sample[1] == 0.0) {
1969                         /* the above means integer_signal+FLAC__MAX_FIXED_ORDER is constant, now we just have to check the warmup samples */
1970                         unsigned i;
1971                         signal_is_constant = true;
1972                         for(i = 1; i <= FLAC__MAX_FIXED_ORDER; i++) {
1973                                 if(integer_signal[0] != integer_signal[i]) {
1974                                         signal_is_constant = false;
1975                                         break;
1976                                 }
1977                         }
1978                 }
1979                 if(signal_is_constant) {
1980                         _candidate_bits = evaluate_constant_subframe_(integer_signal[0], subframe_bps, subframe[!_best_subframe]);
1981                         if(_candidate_bits < _best_bits) {
1982                                 _best_subframe = !_best_subframe;
1983                                 _best_bits = _candidate_bits;
1984                         }
1985                 }
1986                 else {
1987                         if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
1988                                 /* encode fixed */
1989                                 if(encoder->protected_->do_exhaustive_model_search) {
1990                                         min_fixed_order = 0;
1991                                         max_fixed_order = FLAC__MAX_FIXED_ORDER;
1992                                 }
1993                                 else {
1994                                         min_fixed_order = max_fixed_order = guess_fixed_order;
1995                                 }
1996                                 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
1997                                         if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__real)subframe_bps)
1998                                                 continue; /* don't even try */
1999                                         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 */
2000 #ifndef FLAC__SYMMETRIC_RICE
2001                                         rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
2002 #endif
2003                                         if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2004 #ifdef DEBUG_VERBOSE
2005                                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2006 #endif
2007                                                 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2008                                         }
2009                                         _candidate_bits =
2010                                                 evaluate_fixed_subframe_(
2011                                                         encoder,
2012                                                         integer_signal,
2013                                                         residual[!_best_subframe],
2014                                                         encoder->private_->abs_residual,
2015                                                         encoder->private_->abs_residual_partition_sums,
2016                                                         encoder->private_->raw_bits_per_partition,
2017                                                         frame_header->blocksize,
2018                                                         subframe_bps,
2019                                                         fixed_order,
2020                                                         rice_parameter,
2021                                                         min_partition_order,
2022                                                         max_partition_order,
2023                                                         precompute_partition_sums,
2024                                                         encoder->protected_->do_escape_coding,
2025                                                         encoder->protected_->rice_parameter_search_dist,
2026                                                         subframe[!_best_subframe],
2027                                                         partitioned_rice_contents[!_best_subframe]
2028                                                 );
2029                                         if(_candidate_bits < _best_bits) {
2030                                                 _best_subframe = !_best_subframe;
2031                                                 _best_bits = _candidate_bits;
2032                                         }
2033                                 }
2034                         }
2035
2036                         /* encode lpc */
2037                         if(encoder->protected_->max_lpc_order > 0) {
2038                                 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
2039                                         max_lpc_order = frame_header->blocksize-1;
2040                                 else
2041                                         max_lpc_order = encoder->protected_->max_lpc_order;
2042                                 if(max_lpc_order > 0) {
2043                                         encoder->private_->local_lpc_compute_autocorrelation(real_signal, frame_header->blocksize, max_lpc_order+1, autoc);
2044                                         /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
2045                                         if(autoc[0] != 0.0) {
2046                                                 FLAC__lpc_compute_lp_coefficients(autoc, max_lpc_order, encoder->private_->lp_coeff, lpc_error);
2047                                                 if(encoder->protected_->do_exhaustive_model_search) {
2048                                                         min_lpc_order = 1;
2049                                                 }
2050                                                 else {
2051                                                         unsigned guess_lpc_order = FLAC__lpc_compute_best_order(lpc_error, max_lpc_order, frame_header->blocksize, subframe_bps);
2052                                                         min_lpc_order = max_lpc_order = guess_lpc_order;
2053                                                 }
2054                                                 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
2055                                                         lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
2056                                                         if(lpc_residual_bits_per_sample >= (FLAC__real)subframe_bps)
2057                                                                 continue; /* don't even try */
2058                                                         rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
2059 #ifndef FLAC__SYMMETRIC_RICE
2060                                                         rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
2061 #endif
2062                                                         if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2063 #ifdef DEBUG_VERBOSE
2064                                                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2065 #endif
2066                                                                 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2067                                                         }
2068                                                         if(encoder->protected_->do_qlp_coeff_prec_search) {
2069                                                                 min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
2070                                                                 /* ensure a 32-bit datapath throughout for 16bps or less */
2071                                                                 if(subframe_bps <= 16)
2072                                                                         max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
2073                                                                 else
2074                                                                         max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
2075                                                         }
2076                                                         else {
2077                                                                 min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
2078                                                         }
2079                                                         for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
2080                                                                 _candidate_bits =
2081                                                                         evaluate_lpc_subframe_(
2082                                                                                 encoder,
2083                                                                                 integer_signal,
2084                                                                                 residual[!_best_subframe],
2085                                                                                 encoder->private_->abs_residual,
2086                                                                                 encoder->private_->abs_residual_partition_sums,
2087                                                                                 encoder->private_->raw_bits_per_partition,
2088                                                                                 encoder->private_->lp_coeff[lpc_order-1],
2089                                                                                 frame_header->blocksize,
2090                                                                                 subframe_bps,
2091                                                                                 lpc_order,
2092                                                                                 qlp_coeff_precision,
2093                                                                                 rice_parameter,
2094                                                                                 min_partition_order,
2095                                                                                 max_partition_order,
2096                                                                                 precompute_partition_sums,
2097                                                                                 encoder->protected_->do_escape_coding,
2098                                                                                 encoder->protected_->rice_parameter_search_dist,
2099                                                                                 subframe[!_best_subframe],
2100                                                                                 partitioned_rice_contents[!_best_subframe]
2101                                                                         );
2102                                                                 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
2103                                                                         if(_candidate_bits < _best_bits) {
2104                                                                                 _best_subframe = !_best_subframe;
2105                                                                                 _best_bits = _candidate_bits;
2106                                                                         }
2107                                                                 }
2108                                                         }
2109                                                 }
2110                                         }
2111                                 }
2112                         }
2113                 }
2114         }
2115
2116         /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
2117         if(_best_bits == UINT_MAX) {
2118                 FLAC__ASSERT(_best_subframe == 0);
2119                 _best_bits = evaluate_verbatim_subframe_(integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
2120         }
2121
2122         *best_subframe = _best_subframe;
2123         *best_bits = _best_bits;
2124
2125         return true;
2126 }
2127
2128 FLAC__bool add_subframe_(
2129         FLAC__StreamEncoder *encoder,
2130         const FLAC__FrameHeader *frame_header,
2131         unsigned subframe_bps,
2132         const FLAC__Subframe *subframe,
2133         FLAC__BitBuffer *frame
2134 )
2135 {
2136         switch(subframe->type) {
2137                 case FLAC__SUBFRAME_TYPE_CONSTANT:
2138                         if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
2139                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING;
2140                                 return false;
2141                         }
2142                         break;
2143                 case FLAC__SUBFRAME_TYPE_FIXED:
2144                         if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), frame_header->blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
2145                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING;
2146                                 return false;
2147                         }
2148                         break;
2149                 case FLAC__SUBFRAME_TYPE_LPC:
2150                         if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), frame_header->blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
2151                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING;
2152                                 return false;
2153                         }
2154                         break;
2155                 case FLAC__SUBFRAME_TYPE_VERBATIM:
2156                         if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), frame_header->blocksize, subframe_bps, subframe->wasted_bits, frame)) {
2157                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING;
2158                                 return false;
2159                         }
2160                         break;
2161                 default:
2162                         FLAC__ASSERT(0);
2163         }
2164
2165         return true;
2166 }
2167
2168 unsigned evaluate_constant_subframe_(
2169         const FLAC__int32 signal,
2170         unsigned subframe_bps,
2171         FLAC__Subframe *subframe
2172 )
2173 {
2174         subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
2175         subframe->data.constant.value = signal;
2176
2177         return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe_bps;
2178 }
2179
2180 unsigned evaluate_fixed_subframe_(
2181         FLAC__StreamEncoder *encoder,
2182         const FLAC__int32 signal[],
2183         FLAC__int32 residual[],
2184         FLAC__uint32 abs_residual[],
2185         FLAC__uint64 abs_residual_partition_sums[],
2186         unsigned raw_bits_per_partition[],
2187         unsigned blocksize,
2188         unsigned subframe_bps,
2189         unsigned order,
2190         unsigned rice_parameter,
2191         unsigned min_partition_order,
2192         unsigned max_partition_order,
2193         FLAC__bool precompute_partition_sums,
2194         FLAC__bool do_escape_coding,
2195         unsigned rice_parameter_search_dist,
2196         FLAC__Subframe *subframe,
2197         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
2198 )
2199 {
2200         unsigned i, residual_bits;
2201         const unsigned residual_samples = blocksize - order;
2202
2203         FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
2204
2205         subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
2206
2207         subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
2208         subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
2209         subframe->data.fixed.residual = residual;
2210
2211         residual_bits =
2212                 find_best_partition_order_(
2213                         encoder->private_,
2214                         residual,
2215                         abs_residual,
2216                         abs_residual_partition_sums,
2217                         raw_bits_per_partition,
2218                         residual_samples,
2219                         order,
2220                         rice_parameter,
2221                         min_partition_order,
2222                         max_partition_order,
2223                         precompute_partition_sums,
2224                         do_escape_coding,
2225                         rice_parameter_search_dist,
2226                         &subframe->data.fixed.entropy_coding_method.data.partitioned_rice
2227                 );
2228
2229         subframe->data.fixed.order = order;
2230         for(i = 0; i < order; i++)
2231                 subframe->data.fixed.warmup[i] = signal[i];
2232
2233         return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (order * subframe_bps) + residual_bits;
2234 }
2235
2236 unsigned evaluate_lpc_subframe_(
2237         FLAC__StreamEncoder *encoder,
2238         const FLAC__int32 signal[],
2239         FLAC__int32 residual[],
2240         FLAC__uint32 abs_residual[],
2241         FLAC__uint64 abs_residual_partition_sums[],
2242         unsigned raw_bits_per_partition[],
2243         const FLAC__real lp_coeff[],
2244         unsigned blocksize,
2245         unsigned subframe_bps,
2246         unsigned order,
2247         unsigned qlp_coeff_precision,
2248         unsigned rice_parameter,
2249         unsigned min_partition_order,
2250         unsigned max_partition_order,
2251         FLAC__bool precompute_partition_sums,
2252         FLAC__bool do_escape_coding,
2253         unsigned rice_parameter_search_dist,
2254         FLAC__Subframe *subframe,
2255         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
2256 )
2257 {
2258         FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
2259         unsigned i, residual_bits;
2260         int quantization, ret;
2261         const unsigned residual_samples = blocksize - order;
2262
2263         /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
2264         if(subframe_bps <= 16) {
2265                 FLAC__ASSERT(order > 0);
2266                 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
2267                 qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
2268         }
2269
2270         ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
2271         if(ret != 0)
2272                 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
2273
2274         if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
2275                 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
2276                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
2277                 else
2278                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
2279         else
2280                 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
2281
2282         subframe->type = FLAC__SUBFRAME_TYPE_LPC;
2283
2284         subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
2285         subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
2286         subframe->data.lpc.residual = residual;
2287
2288         residual_bits =
2289                 find_best_partition_order_(
2290                         encoder->private_,
2291                         residual,
2292                         abs_residual,
2293                         abs_residual_partition_sums,
2294                         raw_bits_per_partition,
2295                         residual_samples,
2296                         order,
2297                         rice_parameter,
2298                         min_partition_order,
2299                         max_partition_order,
2300                         precompute_partition_sums,
2301                         do_escape_coding,
2302                         rice_parameter_search_dist,
2303                         &subframe->data.fixed.entropy_coding_method.data.partitioned_rice
2304                 );
2305
2306         subframe->data.lpc.order = order;
2307         subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
2308         subframe->data.lpc.quantization_level = quantization;
2309         memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
2310         for(i = 0; i < order; i++)
2311                 subframe->data.lpc.warmup[i] = signal[i];
2312
2313         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;
2314 }
2315
2316 unsigned evaluate_verbatim_subframe_(
2317         const FLAC__int32 signal[],
2318         unsigned blocksize,
2319         unsigned subframe_bps,
2320         FLAC__Subframe *subframe
2321 )
2322 {
2323         subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
2324
2325         subframe->data.verbatim.data = signal;
2326
2327         return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (blocksize * subframe_bps);
2328 }
2329
2330 unsigned find_best_partition_order_(
2331         FLAC__StreamEncoderPrivate *private_,
2332         const FLAC__int32 residual[],
2333         FLAC__uint32 abs_residual[],
2334         FLAC__uint64 abs_residual_partition_sums[],
2335         unsigned raw_bits_per_partition[],
2336         unsigned residual_samples,
2337         unsigned predictor_order,
2338         unsigned rice_parameter,
2339         unsigned min_partition_order,
2340         unsigned max_partition_order,
2341         FLAC__bool precompute_partition_sums,
2342         FLAC__bool do_escape_coding,
2343         unsigned rice_parameter_search_dist,
2344         FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
2345 )
2346 {
2347         FLAC__int32 r;
2348         unsigned residual_bits, best_residual_bits = 0;
2349         unsigned residual_sample;
2350         unsigned best_parameters_index = 0;
2351         const unsigned blocksize = residual_samples + predictor_order;
2352
2353         /* compute abs(residual) for use later */
2354         for(residual_sample = 0; residual_sample < residual_samples; residual_sample++) {
2355                 r = residual[residual_sample];
2356                 abs_residual[residual_sample] = (FLAC__uint32)(r<0? -r : r);
2357         }
2358
2359         max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
2360         min_partition_order = min(min_partition_order, max_partition_order);
2361
2362         if(precompute_partition_sums) {
2363                 int partition_order;
2364                 unsigned sum;
2365
2366                 precompute_partition_info_sums_(abs_residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order);
2367
2368                 if(do_escape_coding)
2369                         precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
2370
2371                 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
2372 #ifdef DONT_ESTIMATE_RICE_BITS
2373                         if(!
2374                                 set_partitioned_rice_with_precompute_(
2375                                         residual,
2376                                         abs_residual_partition_sums+sum,
2377                                         raw_bits_per_partition+sum,
2378                                         residual_samples,
2379                                         predictor_order,
2380                                         rice_parameter,
2381                                         rice_parameter_search_dist,
2382                                         (unsigned)partition_order,
2383                                         do_escape_coding,
2384                                         &private_->partitioned_rice_contents_extra[!best_parameters_index],
2385                                         &residual_bits
2386                                 )
2387                         )
2388 #else
2389                         if(!
2390                                 set_partitioned_rice_with_precompute_(
2391                                         abs_residual,
2392                                         abs_residual_partition_sums+sum,
2393                                         raw_bits_per_partition+sum,
2394                                         residual_samples,
2395                                         predictor_order,
2396                                         rice_parameter,
2397                                         rice_parameter_search_dist,
2398                                         (unsigned)partition_order,
2399                                         do_escape_coding,
2400                                         &private_->partitioned_rice_contents_extra[!best_parameters_index],
2401                                         &residual_bits
2402                                 )
2403                         )
2404 #endif
2405                         {
2406                                 FLAC__ASSERT(best_residual_bits != 0);
2407                                 break;
2408                         }
2409                         sum += 1u << partition_order;
2410                         if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
2411                                 best_residual_bits = residual_bits;
2412                                 best_parameters_index = !best_parameters_index;
2413                                 best_partitioned_rice->order = partition_order;
2414                         }
2415                 }
2416         }
2417         else {
2418                 unsigned partition_order;
2419                 for(partition_order = min_partition_order; partition_order <= max_partition_order; partition_order++) {
2420 #ifdef DONT_ESTIMATE_RICE_BITS
2421                         if(!
2422                                 set_partitioned_rice_(
2423                                         abs_residual,
2424                                         residual,
2425                                         residual_samples,
2426                                         predictor_order,
2427                                         rice_parameter,
2428                                         rice_parameter_search_dist,
2429                                         partition_order,
2430                                         &private_->partitioned_rice_contents_extra[!best_parameters_index],
2431                                         &residual_bits
2432                                 )
2433                         )
2434 #else
2435                         if(!
2436                                 set_partitioned_rice_(
2437                                         abs_residual,
2438                                         residual_samples,
2439                                         predictor_order,
2440                                         rice_parameter,
2441                                         rice_parameter_search_dist,
2442                                         partition_order,
2443                                         &private_->partitioned_rice_contents_extra[!best_parameters_index],
2444                                         &residual_bits
2445                                 )
2446                         )
2447 #endif
2448                         {
2449                                 FLAC__ASSERT(best_residual_bits != 0);
2450                                 break;
2451                         }
2452                         if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
2453                                 best_residual_bits = residual_bits;
2454                                 best_parameters_index = !best_parameters_index;
2455                                 best_partitioned_rice->order = partition_order;
2456                         }
2457                 }
2458         }
2459
2460         /*
2461          * We are allowed to de-const the pointer based on our special knowledge;
2462          * it is const to the outside world.
2463          */
2464         {
2465                 FLAC__EntropyCodingMethod_PartitionedRiceContents* best_partitioned_rice_contents = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_partitioned_rice->contents;
2466                 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(best_partitioned_rice_contents, max(6, best_partitioned_rice->order));
2467                 memcpy(best_partitioned_rice_contents->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
2468                 memcpy(best_partitioned_rice_contents->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
2469         }
2470
2471         return best_residual_bits;
2472 }
2473
2474 void precompute_partition_info_sums_(
2475         const FLAC__uint32 abs_residual[],
2476         FLAC__uint64 abs_residual_partition_sums[],
2477         unsigned residual_samples,
2478         unsigned predictor_order,
2479         unsigned min_partition_order,
2480         unsigned max_partition_order
2481 )
2482 {
2483         int partition_order;
2484         unsigned from_partition, to_partition = 0;
2485         const unsigned blocksize = residual_samples + predictor_order;
2486
2487         /* first do max_partition_order */
2488         for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
2489                 FLAC__uint64 abs_residual_partition_sum;
2490                 FLAC__uint32 abs_r;
2491                 unsigned partition, partition_sample, partition_samples, residual_sample;
2492                 const unsigned partitions = 1u << partition_order;
2493                 const unsigned default_partition_samples = blocksize >> partition_order;
2494
2495                 FLAC__ASSERT(default_partition_samples > predictor_order);
2496
2497                 for(partition = residual_sample = 0; partition < partitions; partition++) {
2498                         partition_samples = default_partition_samples;
2499                         if(partition == 0)
2500                                 partition_samples -= predictor_order;
2501                         abs_residual_partition_sum = 0;
2502                         for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
2503                                 abs_r = abs_residual[residual_sample];
2504                                 abs_residual_partition_sum += abs_r;
2505                                 residual_sample++;
2506                         }
2507                         abs_residual_partition_sums[partition] = abs_residual_partition_sum;
2508                 }
2509                 to_partition = partitions;
2510                 break;
2511         }
2512
2513         /* now merge partitions for lower orders */
2514         for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
2515                 FLAC__uint64 s;
2516                 unsigned i;
2517                 const unsigned partitions = 1u << partition_order;
2518                 for(i = 0; i < partitions; i++) {
2519                         s = abs_residual_partition_sums[from_partition];
2520                         from_partition++;
2521                         abs_residual_partition_sums[to_partition] = s + abs_residual_partition_sums[from_partition];
2522                         from_partition++;
2523                         to_partition++;
2524                 }
2525         }
2526 }
2527
2528 void precompute_partition_info_escapes_(
2529         const FLAC__int32 residual[],
2530         unsigned raw_bits_per_partition[],
2531         unsigned residual_samples,
2532         unsigned predictor_order,
2533         unsigned min_partition_order,
2534         unsigned max_partition_order
2535 )
2536 {
2537         int partition_order;
2538         unsigned from_partition, to_partition = 0;
2539         const unsigned blocksize = residual_samples + predictor_order;
2540
2541         /* first do max_partition_order */
2542         for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
2543                 FLAC__int32 r, residual_partition_min, residual_partition_max;
2544                 unsigned silog2_min, silog2_max;
2545                 unsigned partition, partition_sample, partition_samples, residual_sample;
2546                 const unsigned partitions = 1u << partition_order;
2547                 const unsigned default_partition_samples = blocksize >> partition_order;
2548
2549                 FLAC__ASSERT(default_partition_samples > predictor_order);
2550
2551                 for(partition = residual_sample = 0; partition < partitions; partition++) {
2552                         partition_samples = default_partition_samples;
2553                         if(partition == 0)
2554                                 partition_samples -= predictor_order;
2555                         residual_partition_min = residual_partition_max = 0;
2556                         for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
2557                                 r = residual[residual_sample];
2558                                 if(r < residual_partition_min)
2559                                         residual_partition_min = r;
2560                                 else if(r > residual_partition_max)
2561                                         residual_partition_max = r;
2562                                 residual_sample++;
2563                         }
2564                         silog2_min = FLAC__bitmath_silog2(residual_partition_min);
2565                         silog2_max = FLAC__bitmath_silog2(residual_partition_max);
2566                         raw_bits_per_partition[partition] = max(silog2_min, silog2_max);
2567                 }
2568                 to_partition = partitions;
2569                 break;
2570         }
2571
2572         /* now merge partitions for lower orders */
2573         for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
2574                 unsigned m;
2575                 unsigned i;
2576                 const unsigned partitions = 1u << partition_order;
2577                 for(i = 0; i < partitions; i++) {
2578                         m = raw_bits_per_partition[from_partition];
2579                         from_partition++;
2580                         raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
2581                         from_partition++;
2582                         to_partition++;
2583                 }
2584         }
2585 }
2586
2587 #ifdef VARIABLE_RICE_BITS
2588 #undef VARIABLE_RICE_BITS
2589 #endif
2590 #ifndef DONT_ESTIMATE_RICE_BITS
2591 #define VARIABLE_RICE_BITS(value, parameter) ((value) >> (parameter))
2592 #endif
2593
2594 #ifdef DONT_ESTIMATE_RICE_BITS
2595 FLAC__bool set_partitioned_rice_(
2596         const FLAC__uint32 abs_residual[],
2597         const FLAC__int32 residual[],
2598         const unsigned residual_samples,
2599         const unsigned predictor_order,
2600         const unsigned suggested_rice_parameter,
2601         const unsigned rice_parameter_search_dist,
2602         const unsigned partition_order,
2603         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
2604         unsigned *bits
2605 )
2606 #else
2607 FLAC__bool set_partitioned_rice_(
2608         const FLAC__uint32 abs_residual[],
2609         const unsigned residual_samples,
2610         const unsigned predictor_order,
2611         const unsigned suggested_rice_parameter,
2612         const unsigned rice_parameter_search_dist,
2613         const unsigned partition_order,
2614         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
2615         unsigned *bits
2616 )
2617 #endif
2618 {
2619         unsigned rice_parameter, partition_bits;
2620 #ifndef NO_RICE_SEARCH
2621         unsigned best_partition_bits;
2622         unsigned min_rice_parameter, max_rice_parameter, best_rice_parameter = 0;
2623 #endif
2624         unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
2625         unsigned *parameters;
2626
2627         FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
2628
2629         FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
2630         parameters = partitioned_rice_contents->parameters;
2631
2632         if(partition_order == 0) {
2633                 unsigned i;
2634
2635 #ifndef NO_RICE_SEARCH
2636                 if(rice_parameter_search_dist) {
2637                         if(suggested_rice_parameter < rice_parameter_search_dist)
2638                                 min_rice_parameter = 0;
2639                         else
2640                                 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
2641                         max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
2642                         if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2643 #ifdef DEBUG_VERBOSE
2644                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @2\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2645 #endif
2646                                 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2647                         }
2648                 }
2649                 else
2650                         min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
2651
2652                 best_partition_bits = 0xffffffff;
2653                 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
2654 #endif
2655 #ifdef VARIABLE_RICE_BITS
2656 #ifdef FLAC__SYMMETRIC_RICE
2657                         partition_bits = (2+rice_parameter) * residual_samples;
2658 #else
2659                         const unsigned rice_parameter_estimate = rice_parameter-1;
2660                         partition_bits = (1+rice_parameter) * residual_samples;
2661 #endif
2662 #else
2663                         partition_bits = 0;
2664 #endif
2665                         partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
2666                         for(i = 0; i < residual_samples; i++) {
2667 #ifdef VARIABLE_RICE_BITS
2668 #ifdef FLAC__SYMMETRIC_RICE
2669                                 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter);
2670 #else
2671                                 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter_estimate);
2672 #endif
2673 #else
2674                                 partition_bits += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter); /* NOTE: we will need to pass in residual[] in addition to abs_residual[] */
2675 #endif
2676                         }
2677 #ifndef NO_RICE_SEARCH
2678                         if(partition_bits < best_partition_bits) {
2679                                 best_rice_parameter = rice_parameter;
2680                                 best_partition_bits = partition_bits;
2681                         }
2682                 }
2683 #endif
2684                 parameters[0] = best_rice_parameter;
2685                 bits_ += best_partition_bits;
2686         }
2687         else {
2688                 unsigned partition, residual_sample, save_residual_sample, partition_sample;
2689                 unsigned partition_samples;
2690                 FLAC__uint64 mean, k;
2691                 const unsigned partitions = 1u << partition_order;
2692                 for(partition = residual_sample = 0; partition < partitions; partition++) {
2693                         partition_samples = (residual_samples+predictor_order) >> partition_order;
2694                         if(partition == 0) {
2695                                 if(partition_samples <= predictor_order)
2696                                         return false;
2697                                 else
2698                                         partition_samples -= predictor_order;
2699                         }
2700                         mean = 0;
2701                         save_residual_sample = residual_sample;
2702                         for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++)
2703                                 mean += abs_residual[residual_sample];
2704                         residual_sample = save_residual_sample;
2705 #ifdef FLAC__SYMMETRIC_RICE
2706                         mean += partition_samples >> 1; /* for rounding effect */
2707                         mean /= partition_samples;
2708
2709                         /* calc rice_parameter = floor(log2(mean)) */
2710                         rice_parameter = 0;
2711                         mean>>=1;
2712                         while(mean) {
2713                                 rice_parameter++;
2714                                 mean >>= 1;
2715                         }
2716 #else
2717                         /* calc rice_parameter ala LOCO-I */
2718                         for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
2719                                 ;
2720 #endif
2721                         if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2722 #ifdef DEBUG_VERBOSE
2723                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @3\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2724 #endif
2725                                 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2726                         }
2727
2728 #ifndef NO_RICE_SEARCH
2729                         if(rice_parameter_search_dist) {
2730                                 if(rice_parameter < rice_parameter_search_dist)
2731                                         min_rice_parameter = 0;
2732                                 else
2733                                         min_rice_parameter = rice_parameter - rice_parameter_search_dist;
2734                                 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
2735                                 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2736 #ifdef DEBUG_VERBOSE
2737                                         fprintf(stderr, "clipping rice_parameter (%u -> %u) @4\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2738 #endif
2739                                         max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2740                                 }
2741                         }
2742                         else
2743                                 min_rice_parameter = max_rice_parameter = rice_parameter;
2744
2745                         best_partition_bits = 0xffffffff;
2746                         for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
2747 #endif
2748 #ifdef VARIABLE_RICE_BITS
2749 #ifdef FLAC__SYMMETRIC_RICE
2750                                 partition_bits = (2+rice_parameter) * partition_samples;
2751 #else
2752                                 const unsigned rice_parameter_estimate = rice_parameter-1;
2753                                 partition_bits = (1+rice_parameter) * partition_samples;
2754 #endif
2755 #else
2756                                 partition_bits = 0;
2757 #endif
2758                                 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
2759                                 save_residual_sample = residual_sample;
2760                                 for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++) {
2761 #ifdef VARIABLE_RICE_BITS
2762 #ifdef FLAC__SYMMETRIC_RICE
2763                                         partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter);
2764 #else
2765                                         partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter_estimate);
2766 #endif
2767 #else
2768                                         partition_bits += FLAC__bitbuffer_rice_bits(residual[residual_sample], rice_parameter); /* NOTE: we will need to pass in residual[] in addition to abs_residual[] */
2769 #endif
2770                                 }
2771 #ifndef NO_RICE_SEARCH
2772                                 if(rice_parameter != max_rice_parameter)
2773                                         residual_sample = save_residual_sample;
2774                                 if(partition_bits < best_partition_bits) {
2775                                         best_rice_parameter = rice_parameter;
2776                                         best_partition_bits = partition_bits;
2777                                 }
2778                         }
2779 #endif
2780                         parameters[partition] = best_rice_parameter;
2781                         bits_ += best_partition_bits;
2782                 }
2783         }
2784
2785         *bits = bits_;
2786         return true;
2787 }
2788
2789 #ifdef DONT_ESTIMATE_RICE_BITS
2790 FLAC__bool set_partitioned_rice_with_precompute_(
2791         const FLAC__int32 residual[],
2792         const FLAC__uint64 abs_residual_partition_sums[],
2793         const unsigned raw_bits_per_partition[],
2794         const unsigned residual_samples,
2795         const unsigned predictor_order,
2796         const unsigned suggested_rice_parameter,
2797         const unsigned rice_parameter_search_dist,
2798         const unsigned partition_order,
2799         const FLAC__bool search_for_escapes,
2800         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
2801         unsigned *bits
2802 )
2803 #else
2804 FLAC__bool set_partitioned_rice_with_precompute_(
2805         const FLAC__uint32 abs_residual[],
2806         const FLAC__uint64 abs_residual_partition_sums[],
2807         const unsigned raw_bits_per_partition[],
2808         const unsigned residual_samples,
2809         const unsigned predictor_order,
2810         const unsigned suggested_rice_parameter,
2811         const unsigned rice_parameter_search_dist,
2812         const unsigned partition_order,
2813         const FLAC__bool search_for_escapes,
2814         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
2815         unsigned *bits
2816 )
2817 #endif
2818 {
2819         unsigned rice_parameter, partition_bits;
2820 #ifndef NO_RICE_SEARCH
2821         unsigned best_partition_bits;
2822         unsigned min_rice_parameter, max_rice_parameter, best_rice_parameter = 0;
2823 #endif
2824         unsigned flat_bits;
2825         unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
2826         unsigned *parameters, *raw_bits;
2827
2828         FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
2829
2830         FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
2831         parameters = partitioned_rice_contents->parameters;
2832         raw_bits = partitioned_rice_contents->raw_bits;
2833
2834         if(partition_order == 0) {
2835                 unsigned i;
2836
2837 #ifndef NO_RICE_SEARCH
2838                 if(rice_parameter_search_dist) {
2839                         if(suggested_rice_parameter < rice_parameter_search_dist)
2840                                 min_rice_parameter = 0;
2841                         else
2842                                 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
2843                         max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
2844                         if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2845 #ifdef DEBUG_VERBOSE
2846                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2847 #endif
2848                                 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2849                         }
2850                 }
2851                 else
2852                         min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
2853
2854                 best_partition_bits = 0xffffffff;
2855                 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
2856 #endif
2857 #ifdef VARIABLE_RICE_BITS
2858 #ifdef FLAC__SYMMETRIC_RICE
2859                         partition_bits = (2+rice_parameter) * residual_samples;
2860 #else
2861                         const unsigned rice_parameter_estimate = rice_parameter-1;
2862                         partition_bits = (1+rice_parameter) * residual_samples;
2863 #endif
2864 #else
2865                         partition_bits = 0;
2866 #endif
2867                         partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
2868                         for(i = 0; i < residual_samples; i++) {
2869 #ifdef VARIABLE_RICE_BITS
2870 #ifdef FLAC__SYMMETRIC_RICE
2871                                 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter);
2872 #else
2873                                 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter_estimate);
2874 #endif
2875 #else
2876                                 partition_bits += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
2877 #endif
2878                         }
2879 #ifndef NO_RICE_SEARCH
2880                         if(partition_bits < best_partition_bits) {
2881                                 best_rice_parameter = rice_parameter;
2882                                 best_partition_bits = partition_bits;
2883                         }
2884                 }
2885 #endif
2886                 if(search_for_escapes) {
2887                         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;
2888                         if(flat_bits <= best_partition_bits) {
2889                                 raw_bits[0] = raw_bits_per_partition[0];
2890                                 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
2891                                 best_partition_bits = flat_bits;
2892                         }
2893                 }
2894                 parameters[0] = best_rice_parameter;
2895                 bits_ += best_partition_bits;
2896         }
2897         else {
2898                 unsigned partition, residual_sample, save_residual_sample, partition_sample;
2899                 unsigned partition_samples;
2900                 FLAC__uint64 mean, k;
2901                 const unsigned partitions = 1u << partition_order;
2902                 for(partition = residual_sample = 0; partition < partitions; partition++) {
2903                         partition_samples = (residual_samples+predictor_order) >> partition_order;
2904                         if(partition == 0) {
2905                                 if(partition_samples <= predictor_order)
2906                                         return false;
2907                                 else
2908                                         partition_samples -= predictor_order;
2909                         }
2910                         mean = abs_residual_partition_sums[partition];
2911 #ifdef FLAC__SYMMETRIC_RICE
2912                         mean += partition_samples >> 1; /* for rounding effect */
2913                         mean /= partition_samples;
2914
2915                         /* calc rice_parameter = floor(log2(mean)) */
2916                         rice_parameter = 0;
2917                         mean>>=1;
2918                         while(mean) {
2919                                 rice_parameter++;
2920                                 mean >>= 1;
2921                         }
2922 #else
2923                         /* calc rice_parameter ala LOCO-I */
2924                         for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
2925                                 ;
2926 #endif
2927                         if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2928 #ifdef DEBUG_VERBOSE
2929                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2930 #endif
2931                                 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2932                         }
2933
2934 #ifndef NO_RICE_SEARCH
2935                         if(rice_parameter_search_dist) {
2936                                 if(rice_parameter < rice_parameter_search_dist)
2937                                         min_rice_parameter = 0;
2938                                 else
2939                                         min_rice_parameter = rice_parameter - rice_parameter_search_dist;
2940                                 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
2941                                 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2942 #ifdef DEBUG_VERBOSE
2943                                         fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2944 #endif
2945                                         max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2946                                 }
2947                         }
2948                         else
2949                                 min_rice_parameter = max_rice_parameter = rice_parameter;
2950
2951                         best_partition_bits = 0xffffffff;
2952                         for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
2953 #endif
2954 #ifdef VARIABLE_RICE_BITS
2955 #ifdef FLAC__SYMMETRIC_RICE
2956                                 partition_bits = (2+rice_parameter) * partition_samples;
2957 #else
2958                                 const unsigned rice_parameter_estimate = rice_parameter-1;
2959                                 partition_bits = (1+rice_parameter) * partition_samples;
2960 #endif
2961 #else
2962                                 partition_bits = 0;
2963 #endif
2964                                 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
2965                                 save_residual_sample = residual_sample;
2966                                 for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++) {
2967 #ifdef VARIABLE_RICE_BITS
2968 #ifdef FLAC__SYMMETRIC_RICE
2969                                         partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter);
2970 #else
2971                                         partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter_estimate);
2972 #endif
2973 #else
2974                                         partition_bits += FLAC__bitbuffer_rice_bits(residual[residual_sample], rice_parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
2975 #endif
2976                                 }
2977 #ifndef NO_RICE_SEARCH
2978                                 if(rice_parameter != max_rice_parameter)
2979                                         residual_sample = save_residual_sample;
2980                                 if(partition_bits < best_partition_bits) {
2981                                         best_rice_parameter = rice_parameter;
2982                                         best_partition_bits = partition_bits;
2983                                 }
2984                         }
2985 #endif
2986                         if(search_for_escapes) {
2987                                 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;
2988                                 if(flat_bits <= best_partition_bits) {
2989                                         raw_bits[partition] = raw_bits_per_partition[partition];
2990                                         best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
2991                                         best_partition_bits = flat_bits;
2992                                 }
2993                         }
2994                         parameters[partition] = best_rice_parameter;
2995                         bits_ += best_partition_bits;
2996                 }
2997         }
2998
2999         *bits = bits_;
3000         return true;
3001 }
3002
3003 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
3004 {
3005         unsigned i, shift;
3006         FLAC__int32 x = 0;
3007
3008         for(i = 0; i < samples && !(x&1); i++)
3009                 x |= signal[i];
3010
3011         if(x == 0) {
3012                 shift = 0;
3013         }
3014         else {
3015                 for(shift = 0; !(x&1); shift++)
3016                         x >>= 1;
3017         }
3018
3019         if(shift > 0) {
3020                 for(i = 0; i < samples; i++)
3021                          signal[i] >>= shift;
3022         }
3023
3024         return shift;
3025 }
3026
3027 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
3028 {
3029         unsigned channel;
3030
3031         for(channel = 0; channel < channels; channel++)
3032                 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
3033
3034         fifo->tail += wide_samples;
3035
3036         FLAC__ASSERT(fifo->tail <= fifo->size);
3037 }
3038
3039 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
3040 {
3041         unsigned channel;
3042         unsigned sample, wide_sample;
3043         unsigned tail = fifo->tail;
3044
3045         sample = input_offset * channels;
3046         for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
3047                 for(channel = 0; channel < channels; channel++)
3048                         fifo->data[channel][tail] = input[sample++];
3049                 tail++;
3050         }
3051         fifo->tail = tail;
3052
3053         FLAC__ASSERT(fifo->tail <= fifo->size);
3054 }
3055
3056 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
3057 {
3058         FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
3059         const unsigned encoded_bytes = encoder->private_->verify.output.bytes;
3060         (void)decoder;
3061
3062         if(encoder->private_->verify.needs_magic_hack) {
3063                 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
3064                 *bytes = FLAC__STREAM_SYNC_LENGTH;
3065                 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
3066                 encoder->private_->verify.needs_magic_hack = false;
3067         }
3068         else {
3069                 if(encoded_bytes == 0) {
3070                         /*
3071                          * If we get here, a FIFO underflow has occurred,
3072                          * which means there is a bug somewhere.
3073                          */
3074                         FLAC__ASSERT(0);
3075                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
3076                 }
3077                 else if(encoded_bytes < *bytes)
3078                         *bytes = encoded_bytes;
3079                 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
3080                 encoder->private_->verify.output.data += *bytes;
3081                 encoder->private_->verify.output.bytes -= *bytes;
3082         }
3083
3084         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
3085 }
3086
3087 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
3088 {
3089         FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
3090         unsigned channel;
3091         const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
3092         const unsigned blocksize = frame->header.blocksize;
3093         const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
3094
3095         for(channel = 0; channel < channels; channel++) {
3096                 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
3097                         unsigned i, sample = 0;
3098                         FLAC__int32 expect = 0, got = 0;
3099
3100                         for(i = 0; i < blocksize; i++) {
3101                                 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
3102                                         sample = i;
3103                                         expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
3104                                         got = (FLAC__int32)buffer[channel][i];
3105                                         break;
3106                                 }
3107                         }
3108                         FLAC__ASSERT(i < blocksize);
3109                         FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
3110                         encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
3111                         encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
3112                         encoder->private_->verify.error_stats.channel = channel;
3113                         encoder->private_->verify.error_stats.sample = sample;
3114                         encoder->private_->verify.error_stats.expected = expect;
3115                         encoder->private_->verify.error_stats.got = got;
3116                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
3117                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
3118                 }
3119         }
3120         /* dequeue the frame from the fifo */
3121         for(channel = 0; channel < channels; channel++) {
3122                 memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail - blocksize);
3123         }
3124         encoder->private_->verify.input_fifo.tail -= blocksize;
3125         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
3126 }
3127
3128 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
3129 {
3130         (void)decoder, (void)metadata, (void)client_data;
3131 }
3132
3133 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
3134 {
3135         FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
3136         (void)decoder, (void)status;
3137         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
3138 }