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