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