flac-leaks
[platform/upstream/flac.git] / src / libFLAC / stream_encoder.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * - Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *
11  * - Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  *
15  * - Neither the name of the Xiph.org Foundation nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #if HAVE_CONFIG_H
33 #  include <config.h>
34 #endif
35
36 #if defined _MSC_VER || defined __MINGW32__
37 #include <io.h> /* for _setmode() */
38 #include <fcntl.h> /* for _O_BINARY */
39 #endif
40 #if defined __CYGWIN__ || defined __EMX__
41 #include <io.h> /* for setmode(), O_BINARY */
42 #include <fcntl.h> /* for _O_BINARY */
43 #endif
44 #include <limits.h>
45 #include <stdio.h>
46 #include <stdlib.h> /* for malloc() */
47 #include <string.h> /* for memcpy() */
48 #include <sys/types.h> /* for off_t */
49 #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
50 #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
51 #define fseeko fseek
52 #define ftello ftell
53 #endif
54 #endif
55 #include "FLAC/assert.h"
56 #include "FLAC/stream_decoder.h"
57 #include "share/alloc.h"
58 #include "protected/stream_encoder.h"
59 #include "private/bitwriter.h"
60 #include "private/bitmath.h"
61 #include "private/crc.h"
62 #include "private/cpu.h"
63 #include "private/fixed.h"
64 #include "private/format.h"
65 #include "private/lpc.h"
66 #include "private/md5.h"
67 #include "private/memory.h"
68 #if FLAC__HAS_OGG
69 #include "private/ogg_helper.h"
70 #include "private/ogg_mapping.h"
71 #endif
72 #include "private/stream_encoder_framing.h"
73 #include "private/window.h"
74
75 #ifndef FLaC__INLINE
76 #define FLaC__INLINE
77 #endif
78
79 #ifdef min
80 #undef min
81 #endif
82 #define min(x,y) ((x)<(y)?(x):(y))
83
84 #ifdef max
85 #undef max
86 #endif
87 #define max(x,y) ((x)>(y)?(x):(y))
88
89 /* Exact Rice codeword length calculation is off by default.  The simple
90  * (and fast) estimation (of how many bits a residual value will be
91  * encoded with) in this encoder is very good, almost always yielding
92  * compression within 0.1% of exact calculation.
93  */
94 #undef EXACT_RICE_BITS_CALCULATION
95 /* Rice parameter searching is off by default.  The simple (and fast)
96  * parameter estimation in this encoder is very good, almost always
97  * yielding compression within 0.1% of the optimal parameters.
98  */
99 #undef ENABLE_RICE_PARAMETER_SEARCH 
100
101
102 typedef struct {
103         FLAC__int32 *data[FLAC__MAX_CHANNELS];
104         unsigned size; /* of each data[] in samples */
105         unsigned tail;
106 } verify_input_fifo;
107
108 typedef struct {
109         const FLAC__byte *data;
110         unsigned capacity;
111         unsigned bytes;
112 } verify_output;
113
114 typedef enum {
115         ENCODER_IN_MAGIC = 0,
116         ENCODER_IN_METADATA = 1,
117         ENCODER_IN_AUDIO = 2
118 } EncoderStateHint;
119
120 static struct CompressionLevels {
121         FLAC__bool do_mid_side_stereo;
122         FLAC__bool loose_mid_side_stereo;
123         unsigned max_lpc_order;
124         unsigned qlp_coeff_precision;
125         FLAC__bool do_qlp_coeff_prec_search;
126         FLAC__bool do_escape_coding;
127         FLAC__bool do_exhaustive_model_search;
128         unsigned min_residual_partition_order;
129         unsigned max_residual_partition_order;
130         unsigned rice_parameter_search_dist;
131 } compression_levels_[] = {
132         { false, false,  0, 0, false, false, false, 0, 3, 0 },
133         { true , true ,  0, 0, false, false, false, 0, 3, 0 },
134         { true , false,  0, 0, false, false, false, 0, 3, 0 },
135         { false, false,  6, 0, false, false, false, 0, 4, 0 },
136         { true , true ,  8, 0, false, false, false, 0, 4, 0 },
137         { true , false,  8, 0, false, false, false, 0, 5, 0 },
138         { true , false,  8, 0, false, false, false, 0, 6, 0 },
139         { true , false,  8, 0, false, false, true , 0, 6, 0 },
140         { true , false, 12, 0, false, false, true , 0, 6, 0 }
141 };
142
143
144 /***********************************************************************
145  *
146  * Private class method prototypes
147  *
148  ***********************************************************************/
149
150 static void set_defaults_(FLAC__StreamEncoder *encoder);
151 static void free_(FLAC__StreamEncoder *encoder);
152 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
153 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
154 static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
155 static void update_metadata_(const FLAC__StreamEncoder *encoder);
156 #if FLAC__HAS_OGG
157 static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
158 #endif
159 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
160 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
161
162 static FLAC__bool process_subframe_(
163         FLAC__StreamEncoder *encoder,
164         unsigned min_partition_order,
165         unsigned max_partition_order,
166         const FLAC__FrameHeader *frame_header,
167         unsigned subframe_bps,
168         const FLAC__int32 integer_signal[],
169         FLAC__Subframe *subframe[2],
170         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
171         FLAC__int32 *residual[2],
172         unsigned *best_subframe,
173         unsigned *best_bits
174 );
175
176 static FLAC__bool add_subframe_(
177         FLAC__StreamEncoder *encoder,
178         unsigned blocksize,
179         unsigned subframe_bps,
180         const FLAC__Subframe *subframe,
181         FLAC__BitWriter *frame
182 );
183
184 static unsigned evaluate_constant_subframe_(
185         FLAC__StreamEncoder *encoder,
186         const FLAC__int32 signal,
187         unsigned blocksize,
188         unsigned subframe_bps,
189         FLAC__Subframe *subframe
190 );
191
192 static unsigned evaluate_fixed_subframe_(
193         FLAC__StreamEncoder *encoder,
194         const FLAC__int32 signal[],
195         FLAC__int32 residual[],
196         FLAC__uint64 abs_residual_partition_sums[],
197         unsigned raw_bits_per_partition[],
198         unsigned blocksize,
199         unsigned subframe_bps,
200         unsigned order,
201         unsigned rice_parameter,
202         unsigned rice_parameter_limit,
203         unsigned min_partition_order,
204         unsigned max_partition_order,
205         FLAC__bool do_escape_coding,
206         unsigned rice_parameter_search_dist,
207         FLAC__Subframe *subframe,
208         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
209 );
210
211 #ifndef FLAC__INTEGER_ONLY_LIBRARY
212 static unsigned evaluate_lpc_subframe_(
213         FLAC__StreamEncoder *encoder,
214         const FLAC__int32 signal[],
215         FLAC__int32 residual[],
216         FLAC__uint64 abs_residual_partition_sums[],
217         unsigned raw_bits_per_partition[],
218         const FLAC__real lp_coeff[],
219         unsigned blocksize,
220         unsigned subframe_bps,
221         unsigned order,
222         unsigned qlp_coeff_precision,
223         unsigned rice_parameter,
224         unsigned rice_parameter_limit,
225         unsigned min_partition_order,
226         unsigned max_partition_order,
227         FLAC__bool do_escape_coding,
228         unsigned rice_parameter_search_dist,
229         FLAC__Subframe *subframe,
230         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
231 );
232 #endif
233
234 static unsigned evaluate_verbatim_subframe_(
235         FLAC__StreamEncoder *encoder, 
236         const FLAC__int32 signal[],
237         unsigned blocksize,
238         unsigned subframe_bps,
239         FLAC__Subframe *subframe
240 );
241
242 static unsigned find_best_partition_order_(
243         struct FLAC__StreamEncoderPrivate *private_,
244         const FLAC__int32 residual[],
245         FLAC__uint64 abs_residual_partition_sums[],
246         unsigned raw_bits_per_partition[],
247         unsigned residual_samples,
248         unsigned predictor_order,
249         unsigned rice_parameter,
250         unsigned rice_parameter_limit,
251         unsigned min_partition_order,
252         unsigned max_partition_order,
253         unsigned bps,
254         FLAC__bool do_escape_coding,
255         unsigned rice_parameter_search_dist,
256         FLAC__EntropyCodingMethod *best_ecm
257 );
258
259 static void precompute_partition_info_sums_(
260         const FLAC__int32 residual[],
261         FLAC__uint64 abs_residual_partition_sums[],
262         unsigned residual_samples,
263         unsigned predictor_order,
264         unsigned min_partition_order,
265         unsigned max_partition_order,
266         unsigned bps
267 );
268
269 static void precompute_partition_info_escapes_(
270         const FLAC__int32 residual[],
271         unsigned raw_bits_per_partition[],
272         unsigned residual_samples,
273         unsigned predictor_order,
274         unsigned min_partition_order,
275         unsigned max_partition_order
276 );
277
278 static FLAC__bool set_partitioned_rice_(
279 #ifdef EXACT_RICE_BITS_CALCULATION
280         const FLAC__int32 residual[],
281 #endif
282         const FLAC__uint64 abs_residual_partition_sums[],
283         const unsigned raw_bits_per_partition[],
284         const unsigned residual_samples,
285         const unsigned predictor_order,
286         const unsigned suggested_rice_parameter,
287         const unsigned rice_parameter_limit,
288         const unsigned rice_parameter_search_dist,
289         const unsigned partition_order,
290         const FLAC__bool search_for_escapes,
291         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
292         unsigned *bits
293 );
294
295 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
296
297 /* verify-related routines: */
298 static void append_to_verify_fifo_(
299         verify_input_fifo *fifo,
300         const FLAC__int32 * const input[],
301         unsigned input_offset,
302         unsigned channels,
303         unsigned wide_samples
304 );
305
306 static void append_to_verify_fifo_interleaved_(
307         verify_input_fifo *fifo,
308         const FLAC__int32 input[],
309         unsigned input_offset,
310         unsigned channels,
311         unsigned wide_samples
312 );
313
314 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
315 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
316 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
317 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
318
319 static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
320 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
321 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
322 static FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
323 static FILE *get_binary_stdout_(void);
324
325
326 /***********************************************************************
327  *
328  * Private class data
329  *
330  ***********************************************************************/
331
332 typedef struct FLAC__StreamEncoderPrivate {
333         unsigned input_capacity;                          /* current size (in samples) of the signal and residual buffers */
334         FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS];  /* the integer version of the input signal */
335         FLAC__int32 *integer_signal_mid_side[2];          /* the integer version of the mid-side input signal (stereo only) */
336 #ifndef FLAC__INTEGER_ONLY_LIBRARY
337         FLAC__real *real_signal[FLAC__MAX_CHANNELS];      /* (@@@ currently unused) the floating-point version of the input signal */
338         FLAC__real *real_signal_mid_side[2];              /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
339         FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
340         FLAC__real *windowed_signal;                      /* the integer_signal[] * current window[] */
341 #endif
342         unsigned subframe_bps[FLAC__MAX_CHANNELS];        /* the effective bits per sample of the input signal (stream bps - wasted bits) */
343         unsigned subframe_bps_mid_side[2];                /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
344         FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
345         FLAC__int32 *residual_workspace_mid_side[2][2];
346         FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
347         FLAC__Subframe subframe_workspace_mid_side[2][2];
348         FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
349         FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
350         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
351         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
352         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
353         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
354         unsigned best_subframe[FLAC__MAX_CHANNELS];       /* index (0 or 1) into 2nd dimension of the above workspaces */
355         unsigned best_subframe_mid_side[2];
356         unsigned best_subframe_bits[FLAC__MAX_CHANNELS];  /* size in bits of the best subframe for each channel */
357         unsigned best_subframe_bits_mid_side[2];
358         FLAC__uint64 *abs_residual_partition_sums;        /* workspace where the sum of abs(candidate residual) for each partition is stored */
359         unsigned *raw_bits_per_partition;                 /* workspace where the sum of silog2(candidate residual) for each partition is stored */
360         FLAC__BitWriter *frame;                           /* the current frame being worked on */
361         unsigned loose_mid_side_stereo_frames;            /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
362         unsigned loose_mid_side_stereo_frame_count;       /* number of frames using the current channel assignment */
363         FLAC__ChannelAssignment last_channel_assignment;
364         FLAC__StreamMetadata streaminfo;                  /* scratchpad for STREAMINFO as it is built */
365         FLAC__StreamMetadata_SeekTable *seek_table;       /* pointer into encoder->protected_->metadata_ where the seek table is */
366         unsigned current_sample_number;
367         unsigned current_frame_number;
368         FLAC__MD5Context md5context;
369         FLAC__CPUInfo cpuinfo;
370 #ifndef FLAC__INTEGER_ONLY_LIBRARY
371         unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
372 #else
373         unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
374 #endif
375 #ifndef FLAC__INTEGER_ONLY_LIBRARY
376         void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
377         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[]);
378         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[]);
379         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[]);
380 #endif
381         FLAC__bool use_wide_by_block;          /* use slow 64-bit versions of some functions because of the block size */
382         FLAC__bool use_wide_by_partition;      /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
383         FLAC__bool use_wide_by_order;          /* use slow 64-bit versions of some functions because of the lpc order */
384         FLAC__bool disable_constant_subframes;
385         FLAC__bool disable_fixed_subframes;
386         FLAC__bool disable_verbatim_subframes;
387 #if FLAC__HAS_OGG
388         FLAC__bool is_ogg;
389 #endif
390         FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
391         FLAC__StreamEncoderSeekCallback seek_callback;
392         FLAC__StreamEncoderTellCallback tell_callback;
393         FLAC__StreamEncoderWriteCallback write_callback;
394         FLAC__StreamEncoderMetadataCallback metadata_callback;
395         FLAC__StreamEncoderProgressCallback progress_callback;
396         void *client_data;
397         unsigned first_seekpoint_to_check;
398         FILE *file;                            /* only used when encoding to a file */
399         FLAC__uint64 bytes_written;
400         FLAC__uint64 samples_written;
401         unsigned frames_written;
402         unsigned total_frames_estimate;
403         /* unaligned (original) pointers to allocated data */
404         FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
405         FLAC__int32 *integer_signal_mid_side_unaligned[2];
406 #ifndef FLAC__INTEGER_ONLY_LIBRARY
407         FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
408         FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
409         FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
410         FLAC__real *windowed_signal_unaligned;
411 #endif
412         FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
413         FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
414         FLAC__uint64 *abs_residual_partition_sums_unaligned;
415         unsigned *raw_bits_per_partition_unaligned;
416         /*
417          * These fields have been moved here from private function local
418          * declarations merely to save stack space during encoding.
419          */
420 #ifndef FLAC__INTEGER_ONLY_LIBRARY
421         FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
422 #endif
423         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
424         /*
425          * The data for the verify section
426          */
427         struct {
428                 FLAC__StreamDecoder *decoder;
429                 EncoderStateHint state_hint;
430                 FLAC__bool needs_magic_hack;
431                 verify_input_fifo input_fifo;
432                 verify_output output;
433                 struct {
434                         FLAC__uint64 absolute_sample;
435                         unsigned frame_number;
436                         unsigned channel;
437                         unsigned sample;
438                         FLAC__int32 expected;
439                         FLAC__int32 got;
440                 } error_stats;
441         } verify;
442         FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
443 } FLAC__StreamEncoderPrivate;
444
445 /***********************************************************************
446  *
447  * Public static class data
448  *
449  ***********************************************************************/
450
451 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
452         "FLAC__STREAM_ENCODER_OK",
453         "FLAC__STREAM_ENCODER_UNINITIALIZED",
454         "FLAC__STREAM_ENCODER_OGG_ERROR",
455         "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
456         "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
457         "FLAC__STREAM_ENCODER_CLIENT_ERROR",
458         "FLAC__STREAM_ENCODER_IO_ERROR",
459         "FLAC__STREAM_ENCODER_FRAMING_ERROR",
460         "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
461 };
462
463 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
464         "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
465         "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
466         "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
467         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
468         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
469         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
470         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
471         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
472         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
473         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
474         "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
475         "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
476         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
477         "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
478 };
479
480 FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
481         "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
482         "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
483         "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
484         "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
485 };
486
487 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
488         "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
489         "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
490 };
491
492 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
493         "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
494         "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
495         "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
496 };
497
498 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
499         "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
500         "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
501         "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
502 };
503
504 /* Number of samples that will be overread to watch for end of stream.  By
505  * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
506  * always try to read blocksize+1 samples before encoding a block, so that
507  * even if the stream has a total sample count that is an integral multiple
508  * of the blocksize, we will still notice when we are encoding the last
509  * block.  This is needed, for example, to correctly set the end-of-stream
510  * marker in Ogg FLAC.
511  *
512  * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
513  * not really any reason to change it.
514  */
515 static const unsigned OVERREAD_ = 1;
516
517 /***********************************************************************
518  *
519  * Class constructor/destructor
520  *
521  */
522 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
523 {
524         FLAC__StreamEncoder *encoder;
525         unsigned i;
526
527         FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
528
529         encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
530         if(encoder == 0) {
531                 return 0;
532         }
533
534         encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
535         if(encoder->protected_ == 0) {
536                 free(encoder);
537                 return 0;
538         }
539
540         encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
541         if(encoder->private_ == 0) {
542                 free(encoder->protected_);
543                 free(encoder);
544                 return 0;
545         }
546
547         encoder->private_->frame = FLAC__bitwriter_new();
548         if(encoder->private_->frame == 0) {
549                 free(encoder->private_);
550                 free(encoder->protected_);
551                 free(encoder);
552                 return 0;
553         }
554
555         encoder->private_->file = 0;
556
557         set_defaults_(encoder);
558
559         encoder->private_->is_being_deleted = false;
560
561         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
562                 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
563                 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
564         }
565         for(i = 0; i < 2; i++) {
566                 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
567                 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
568         }
569         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
570                 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
571                 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
572         }
573         for(i = 0; i < 2; i++) {
574                 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
575                 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
576         }
577
578         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
579                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
580                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
581         }
582         for(i = 0; i < 2; i++) {
583                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
584                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
585         }
586         for(i = 0; i < 2; i++)
587                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
588
589         encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
590
591         return encoder;
592 }
593
594 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
595 {
596         unsigned i;
597
598         FLAC__ASSERT(0 != encoder);
599         FLAC__ASSERT(0 != encoder->protected_);
600         FLAC__ASSERT(0 != encoder->private_);
601         FLAC__ASSERT(0 != encoder->private_->frame);
602
603         encoder->private_->is_being_deleted = true;
604
605         (void)FLAC__stream_encoder_finish(encoder);
606
607         if(0 != encoder->private_->verify.decoder)
608                 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
609
610         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
611                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
612                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
613         }
614         for(i = 0; i < 2; i++) {
615                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
616                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
617         }
618         for(i = 0; i < 2; i++)
619                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
620
621         FLAC__bitwriter_delete(encoder->private_->frame);
622         free(encoder->private_);
623         free(encoder->protected_);
624         free(encoder);
625 }
626
627 /***********************************************************************
628  *
629  * Public class methods
630  *
631  ***********************************************************************/
632
633 static FLAC__StreamEncoderInitStatus init_stream_internal_(
634         FLAC__StreamEncoder *encoder,
635         FLAC__StreamEncoderReadCallback read_callback,
636         FLAC__StreamEncoderWriteCallback write_callback,
637         FLAC__StreamEncoderSeekCallback seek_callback,
638         FLAC__StreamEncoderTellCallback tell_callback,
639         FLAC__StreamEncoderMetadataCallback metadata_callback,
640         void *client_data,
641         FLAC__bool is_ogg
642 )
643 {
644         unsigned i;
645         FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
646
647         FLAC__ASSERT(0 != encoder);
648
649         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
650                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
651
652 #if !FLAC__HAS_OGG
653         if(is_ogg)
654                 return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
655 #endif
656
657         if(0 == write_callback || (seek_callback && 0 == tell_callback))
658                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
659
660         if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
661                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
662
663         if(encoder->protected_->channels != 2) {
664                 encoder->protected_->do_mid_side_stereo = false;
665                 encoder->protected_->loose_mid_side_stereo = false;
666         }
667         else if(!encoder->protected_->do_mid_side_stereo)
668                 encoder->protected_->loose_mid_side_stereo = false;
669
670         if(encoder->protected_->bits_per_sample >= 32)
671                 encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
672
673         if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
674                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
675
676         if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
677                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
678
679         if(encoder->protected_->blocksize == 0) {
680                 if(encoder->protected_->max_lpc_order == 0)
681                         encoder->protected_->blocksize = 1152;
682                 else
683                         encoder->protected_->blocksize = 4096;
684         }
685
686         if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
687                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
688
689         if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
690                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
691
692         if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
693                 return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
694
695         if(encoder->protected_->qlp_coeff_precision == 0) {
696                 if(encoder->protected_->bits_per_sample < 16) {
697                         /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
698                         /* @@@ until then we'll make a guess */
699                         encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
700                 }
701                 else if(encoder->protected_->bits_per_sample == 16) {
702                         if(encoder->protected_->blocksize <= 192)
703                                 encoder->protected_->qlp_coeff_precision = 7;
704                         else if(encoder->protected_->blocksize <= 384)
705                                 encoder->protected_->qlp_coeff_precision = 8;
706                         else if(encoder->protected_->blocksize <= 576)
707                                 encoder->protected_->qlp_coeff_precision = 9;
708                         else if(encoder->protected_->blocksize <= 1152)
709                                 encoder->protected_->qlp_coeff_precision = 10;
710                         else if(encoder->protected_->blocksize <= 2304)
711                                 encoder->protected_->qlp_coeff_precision = 11;
712                         else if(encoder->protected_->blocksize <= 4608)
713                                 encoder->protected_->qlp_coeff_precision = 12;
714                         else
715                                 encoder->protected_->qlp_coeff_precision = 13;
716                 }
717                 else {
718                         if(encoder->protected_->blocksize <= 384)
719                                 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
720                         else if(encoder->protected_->blocksize <= 1152)
721                                 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
722                         else
723                                 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
724                 }
725                 FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
726         }
727         else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
728                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
729
730         if(encoder->protected_->streamable_subset) {
731                 if(
732                         encoder->protected_->blocksize != 192 &&
733                         encoder->protected_->blocksize != 576 &&
734                         encoder->protected_->blocksize != 1152 &&
735                         encoder->protected_->blocksize != 2304 &&
736                         encoder->protected_->blocksize != 4608 &&
737                         encoder->protected_->blocksize != 256 &&
738                         encoder->protected_->blocksize != 512 &&
739                         encoder->protected_->blocksize != 1024 &&
740                         encoder->protected_->blocksize != 2048 &&
741                         encoder->protected_->blocksize != 4096 &&
742                         encoder->protected_->blocksize != 8192 &&
743                         encoder->protected_->blocksize != 16384
744                 )
745                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
746                 if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
747                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
748                 if(
749                         encoder->protected_->bits_per_sample != 8 &&
750                         encoder->protected_->bits_per_sample != 12 &&
751                         encoder->protected_->bits_per_sample != 16 &&
752                         encoder->protected_->bits_per_sample != 20 &&
753                         encoder->protected_->bits_per_sample != 24
754                 )
755                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
756                 if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
757                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
758                 if(
759                         encoder->protected_->sample_rate <= 48000 &&
760                         (
761                                 encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
762                                 encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
763                         )
764                 ) {
765                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
766                 }
767         }
768
769         if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
770                 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
771         if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
772                 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
773
774 #if FLAC__HAS_OGG
775         /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
776         if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
777                 unsigned i;
778                 for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
779                         if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
780                                 FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
781                                 for( ; i > 0; i--)
782                                         encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
783                                 encoder->protected_->metadata[0] = vc;
784                                 break;
785                         }
786                 }
787         }
788 #endif
789         /* keep track of any SEEKTABLE block */
790         if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
791                 unsigned i;
792                 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
793                         if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
794                                 encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
795                                 break; /* take only the first one */
796                         }
797                 }
798         }
799
800         /* validate metadata */
801         if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
802                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
803         metadata_has_seektable = false;
804         metadata_has_vorbis_comment = false;
805         metadata_picture_has_type1 = false;
806         metadata_picture_has_type2 = false;
807         for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
808                 const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
809                 if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
810                         return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
811                 else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
812                         if(metadata_has_seektable) /* only one is allowed */
813                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
814                         metadata_has_seektable = true;
815                         if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
816                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
817                 }
818                 else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
819                         if(metadata_has_vorbis_comment) /* only one is allowed */
820                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
821                         metadata_has_vorbis_comment = true;
822                 }
823                 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
824                         if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
825                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
826                 }
827                 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
828                         if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
829                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
830                         if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
831                                 if(metadata_picture_has_type1) /* there should only be 1 per stream */
832                                         return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
833                                 metadata_picture_has_type1 = true;
834                                 /* standard icon must be 32x32 pixel PNG */
835                                 if(
836                                         m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD && 
837                                         (
838                                                 (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
839                                                 m->data.picture.width != 32 ||
840                                                 m->data.picture.height != 32
841                                         )
842                                 )
843                                         return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
844                         }
845                         else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
846                                 if(metadata_picture_has_type2) /* there should only be 1 per stream */
847                                         return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
848                                 metadata_picture_has_type2 = true;
849                         }
850                 }
851         }
852
853         encoder->private_->input_capacity = 0;
854         for(i = 0; i < encoder->protected_->channels; i++) {
855                 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
856 #ifndef FLAC__INTEGER_ONLY_LIBRARY
857                 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
858 #endif
859         }
860         for(i = 0; i < 2; i++) {
861                 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
862 #ifndef FLAC__INTEGER_ONLY_LIBRARY
863                 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
864 #endif
865         }
866 #ifndef FLAC__INTEGER_ONLY_LIBRARY
867         for(i = 0; i < encoder->protected_->num_apodizations; i++)
868                 encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
869         encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
870 #endif
871         for(i = 0; i < encoder->protected_->channels; i++) {
872                 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
873                 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
874                 encoder->private_->best_subframe[i] = 0;
875         }
876         for(i = 0; i < 2; i++) {
877                 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
878                 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
879                 encoder->private_->best_subframe_mid_side[i] = 0;
880         }
881         encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
882         encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
883 #ifndef FLAC__INTEGER_ONLY_LIBRARY
884         encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
885 #else
886         /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
887         /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
888         FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
889         FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
890         FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
891         FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
892         encoder->private_->loose_mid_side_stereo_frames = (unsigned)FLAC__fixedpoint_trunc((((FLAC__uint64)(encoder->protected_->sample_rate) * (FLAC__uint64)(26214)) << 16) / (encoder->protected_->blocksize<<16) + FLAC__FP_ONE_HALF);
893 #endif
894         if(encoder->private_->loose_mid_side_stereo_frames == 0)
895                 encoder->private_->loose_mid_side_stereo_frames = 1;
896         encoder->private_->loose_mid_side_stereo_frame_count = 0;
897         encoder->private_->current_sample_number = 0;
898         encoder->private_->current_frame_number = 0;
899
900         encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
901         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? */
902         encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
903
904         /*
905          * get the CPU info and set the function pointers
906          */
907         FLAC__cpu_info(&encoder->private_->cpuinfo);
908         /* first default to the non-asm routines */
909 #ifndef FLAC__INTEGER_ONLY_LIBRARY
910         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
911 #endif
912         encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
913 #ifndef FLAC__INTEGER_ONLY_LIBRARY
914         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
915         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
916         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
917 #endif
918         /* now override with asm where appropriate */
919 #ifndef FLAC__INTEGER_ONLY_LIBRARY
920 # ifndef FLAC__NO_ASM
921         if(encoder->private_->cpuinfo.use_asm) {
922 #  ifdef FLAC__CPU_IA32
923                 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
924 #   ifdef FLAC__HAS_NASM
925                 if(encoder->private_->cpuinfo.data.ia32.sse) {
926                         if(encoder->protected_->max_lpc_order < 4)
927                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
928                         else if(encoder->protected_->max_lpc_order < 8)
929                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
930                         else if(encoder->protected_->max_lpc_order < 12)
931                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
932                         else
933                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
934                 }
935                 else if(encoder->private_->cpuinfo.data.ia32._3dnow)
936                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
937                 else
938                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
939                 if(encoder->private_->cpuinfo.data.ia32.mmx) {
940                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
941                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
942                 }
943                 else {
944                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
945                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
946                 }
947                 if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
948                         encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
949 #   endif /* FLAC__HAS_NASM */
950 #  endif /* FLAC__CPU_IA32 */
951         }
952 # endif /* !FLAC__NO_ASM */
953 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
954         /* finally override based on wide-ness if necessary */
955         if(encoder->private_->use_wide_by_block) {
956                 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
957         }
958
959         /* set state to OK; from here on, errors are fatal and we'll override the state then */
960         encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
961
962 #if FLAC__HAS_OGG
963         encoder->private_->is_ogg = is_ogg;
964         if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
965                 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
966                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
967         }
968 #endif
969
970         encoder->private_->read_callback = read_callback;
971         encoder->private_->write_callback = write_callback;
972         encoder->private_->seek_callback = seek_callback;
973         encoder->private_->tell_callback = tell_callback;
974         encoder->private_->metadata_callback = metadata_callback;
975         encoder->private_->client_data = client_data;
976
977         if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
978                 /* the above function sets the state for us in case of an error */
979                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
980         }
981
982         if(!FLAC__bitwriter_init(encoder->private_->frame)) {
983                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
984                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
985         }
986
987         /*
988          * Set up the verify stuff if necessary
989          */
990         if(encoder->protected_->verify) {
991                 /*
992                  * First, set up the fifo which will hold the
993                  * original signal to compare against
994                  */
995                 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
996                 for(i = 0; i < encoder->protected_->channels; i++) {
997                         if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)safe_malloc_mul_2op_(sizeof(FLAC__int32), /*times*/encoder->private_->verify.input_fifo.size))) {
998                                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
999                                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1000                         }
1001                 }
1002                 encoder->private_->verify.input_fifo.tail = 0;
1003
1004                 /*
1005                  * Now set up a stream decoder for verification
1006                  */
1007                 if(0 == encoder->private_->verify.decoder) {
1008             encoder->private_->verify.decoder = FLAC__stream_decoder_new();
1009             if(0 == encoder->private_->verify.decoder) {
1010                             encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1011                             return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1012             }
1013                 }
1014
1015                 if(FLAC__stream_decoder_init_stream(encoder->private_->verify.decoder, verify_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, verify_write_callback_, verify_metadata_callback_, verify_error_callback_, /*client_data=*/encoder) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
1016                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1017                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1018                 }
1019         }
1020         encoder->private_->verify.error_stats.absolute_sample = 0;
1021         encoder->private_->verify.error_stats.frame_number = 0;
1022         encoder->private_->verify.error_stats.channel = 0;
1023         encoder->private_->verify.error_stats.sample = 0;
1024         encoder->private_->verify.error_stats.expected = 0;
1025         encoder->private_->verify.error_stats.got = 0;
1026
1027         /*
1028          * These must be done before we write any metadata, because that
1029          * calls the write_callback, which uses these values.
1030          */
1031         encoder->private_->first_seekpoint_to_check = 0;
1032         encoder->private_->samples_written = 0;
1033         encoder->protected_->streaminfo_offset = 0;
1034         encoder->protected_->seektable_offset = 0;
1035         encoder->protected_->audio_offset = 0;
1036
1037         /*
1038          * write the stream header
1039          */
1040         if(encoder->protected_->verify)
1041                 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1042         if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1043                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1044                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1045         }
1046         if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1047                 /* the above function sets the state for us in case of an error */
1048                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1049         }
1050
1051         /*
1052          * write the STREAMINFO metadata block
1053          */
1054         if(encoder->protected_->verify)
1055                 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1056         encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1057         encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1058         encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1059         encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1060         encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1061         encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1062         encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1063         encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1064         encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1065         encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1066         encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1067         memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1068         if(encoder->protected_->do_md5)
1069                 FLAC__MD5Init(&encoder->private_->md5context);
1070         if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1071                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1072                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1073         }
1074         if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1075                 /* the above function sets the state for us in case of an error */
1076                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1077         }
1078
1079         /*
1080          * Now that the STREAMINFO block is written, we can init this to an
1081          * absurdly-high value...
1082          */
1083         encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1084         /* ... and clear this to 0 */
1085         encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1086
1087         /*
1088          * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1089          * if not, we will write an empty one (FLAC__add_metadata_block()
1090          * automatically supplies the vendor string).
1091          *
1092          * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1093          * the STREAMINFO.  (In the case that metadata_has_vorbis_comment is
1094          * true it will have already insured that the metadata list is properly
1095          * ordered.)
1096          */
1097         if(!metadata_has_vorbis_comment) {
1098                 FLAC__StreamMetadata vorbis_comment;
1099                 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1100                 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1101                 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1102                 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1103                 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1104                 vorbis_comment.data.vorbis_comment.num_comments = 0;
1105                 vorbis_comment.data.vorbis_comment.comments = 0;
1106                 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1107                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1108                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1109                 }
1110                 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1111                         /* the above function sets the state for us in case of an error */
1112                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1113                 }
1114         }
1115
1116         /*
1117          * write the user's metadata blocks
1118          */
1119         for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1120                 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1121                 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1122                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1123                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1124                 }
1125                 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1126                         /* the above function sets the state for us in case of an error */
1127                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1128                 }
1129         }
1130
1131         /* now that all the metadata is written, we save the stream offset */
1132         if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &encoder->protected_->audio_offset, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) { /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
1133                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1134                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1135         }
1136
1137         if(encoder->protected_->verify)
1138                 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1139
1140         return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1141 }
1142
1143 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1144         FLAC__StreamEncoder *encoder,
1145         FLAC__StreamEncoderWriteCallback write_callback,
1146         FLAC__StreamEncoderSeekCallback seek_callback,
1147         FLAC__StreamEncoderTellCallback tell_callback,
1148         FLAC__StreamEncoderMetadataCallback metadata_callback,
1149         void *client_data
1150 )
1151 {
1152         return init_stream_internal_(
1153                 encoder,
1154                 /*read_callback=*/0,
1155                 write_callback,
1156                 seek_callback,
1157                 tell_callback,
1158                 metadata_callback,
1159                 client_data,
1160                 /*is_ogg=*/false
1161         );
1162 }
1163
1164 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1165         FLAC__StreamEncoder *encoder,
1166         FLAC__StreamEncoderReadCallback read_callback,
1167         FLAC__StreamEncoderWriteCallback write_callback,
1168         FLAC__StreamEncoderSeekCallback seek_callback,
1169         FLAC__StreamEncoderTellCallback tell_callback,
1170         FLAC__StreamEncoderMetadataCallback metadata_callback,
1171         void *client_data
1172 )
1173 {
1174         return init_stream_internal_(
1175                 encoder,
1176                 read_callback,
1177                 write_callback,
1178                 seek_callback,
1179                 tell_callback,
1180                 metadata_callback,
1181                 client_data,
1182                 /*is_ogg=*/true
1183         );
1184 }
1185  
1186 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1187         FLAC__StreamEncoder *encoder,
1188         FILE *file,
1189         FLAC__StreamEncoderProgressCallback progress_callback,
1190         void *client_data,
1191         FLAC__bool is_ogg
1192 )
1193 {
1194         FLAC__StreamEncoderInitStatus init_status;
1195
1196         FLAC__ASSERT(0 != encoder);
1197         FLAC__ASSERT(0 != file);
1198
1199         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1200                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1201
1202         /* double protection */
1203         if(file == 0) {
1204                 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1205                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1206         }
1207
1208         /*
1209          * To make sure that our file does not go unclosed after an error, we
1210          * must assign the FILE pointer before any further error can occur in
1211          * this routine.
1212          */
1213         if(file == stdout)
1214                 file = get_binary_stdout_(); /* just to be safe */
1215
1216         encoder->private_->file = file;
1217
1218         encoder->private_->progress_callback = progress_callback;
1219         encoder->private_->bytes_written = 0;
1220         encoder->private_->samples_written = 0;
1221         encoder->private_->frames_written = 0;
1222
1223         init_status = init_stream_internal_(
1224                 encoder,
1225                 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1226                 file_write_callback_,
1227                 encoder->private_->file == stdout? 0 : file_seek_callback_,
1228                 encoder->private_->file == stdout? 0 : file_tell_callback_,
1229                 /*metadata_callback=*/0,
1230                 client_data,
1231                 is_ogg
1232         );
1233         if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1234                 /* the above function sets the state for us in case of an error */
1235                 return init_status;
1236         }
1237
1238         {
1239                 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1240
1241                 FLAC__ASSERT(blocksize != 0);
1242                 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1243         }
1244
1245         return init_status;
1246 }
1247  
1248 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1249         FLAC__StreamEncoder *encoder,
1250         FILE *file,
1251         FLAC__StreamEncoderProgressCallback progress_callback,
1252         void *client_data
1253 )
1254 {
1255         return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1256 }
1257  
1258 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1259         FLAC__StreamEncoder *encoder,
1260         FILE *file,
1261         FLAC__StreamEncoderProgressCallback progress_callback,
1262         void *client_data
1263 )
1264 {
1265         return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1266 }
1267
1268 static FLAC__StreamEncoderInitStatus init_file_internal_(
1269         FLAC__StreamEncoder *encoder,
1270         const char *filename,
1271         FLAC__StreamEncoderProgressCallback progress_callback,
1272         void *client_data,
1273         FLAC__bool is_ogg
1274 )
1275 {
1276         FILE *file;
1277
1278         FLAC__ASSERT(0 != encoder);
1279
1280         /*
1281          * To make sure that our file does not go unclosed after an error, we
1282          * have to do the same entrance checks here that are later performed
1283          * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1284          */
1285         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1286                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1287
1288         file = filename? fopen(filename, "w+be") : stdout;
1289
1290         if(file == 0) {
1291                 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1292                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1293         }
1294
1295         return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1296 }
1297
1298 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1299         FLAC__StreamEncoder *encoder,
1300         const char *filename,
1301         FLAC__StreamEncoderProgressCallback progress_callback,
1302         void *client_data
1303 )
1304 {
1305         return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1306 }
1307
1308 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1309         FLAC__StreamEncoder *encoder,
1310         const char *filename,
1311         FLAC__StreamEncoderProgressCallback progress_callback,
1312         void *client_data
1313 )
1314 {
1315         return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1316 }
1317
1318 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1319 {
1320         FLAC__bool error = false;
1321
1322         FLAC__ASSERT(0 != encoder);
1323         FLAC__ASSERT(0 != encoder->private_);
1324         FLAC__ASSERT(0 != encoder->protected_);
1325
1326         if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1327                 return true;
1328
1329         if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1330                 if(encoder->private_->current_sample_number != 0) {
1331                         const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1332                         encoder->protected_->blocksize = encoder->private_->current_sample_number;
1333                         if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1334                                 error = true;
1335                 }
1336         }
1337
1338         if(encoder->protected_->do_md5)
1339                 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1340
1341         if(!encoder->private_->is_being_deleted) {
1342                 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1343                         if(encoder->private_->seek_callback) {
1344 #if FLAC__HAS_OGG
1345                                 if(encoder->private_->is_ogg)
1346                                         update_ogg_metadata_(encoder);
1347                                 else
1348 #endif
1349                                 update_metadata_(encoder);
1350
1351                                 /* check if an error occurred while updating metadata */
1352                                 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1353                                         error = true;
1354                         }
1355                         if(encoder->private_->metadata_callback)
1356                                 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1357                 }
1358
1359                 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1360                         if(!error)
1361                                 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1362                         error = true;
1363                 }
1364         }
1365
1366         if(0 != encoder->private_->file) {
1367                 if(encoder->private_->file != stdout)
1368                         fclose(encoder->private_->file);
1369                 encoder->private_->file = 0;
1370         }
1371
1372 #if FLAC__HAS_OGG
1373         if(encoder->private_->is_ogg)
1374                 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1375 #endif
1376
1377         free_(encoder);
1378         set_defaults_(encoder);
1379
1380         if(!error)
1381                 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1382
1383         return !error;
1384 }
1385
1386 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1387 {
1388         FLAC__ASSERT(0 != encoder);
1389         FLAC__ASSERT(0 != encoder->private_);
1390         FLAC__ASSERT(0 != encoder->protected_);
1391         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1392                 return false;
1393 #if FLAC__HAS_OGG
1394         /* can't check encoder->private_->is_ogg since that's not set until init time */
1395         FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1396         return true;
1397 #else
1398         (void)value;
1399         return false;
1400 #endif
1401 }
1402
1403 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1404 {
1405         FLAC__ASSERT(0 != encoder);
1406         FLAC__ASSERT(0 != encoder->private_);
1407         FLAC__ASSERT(0 != encoder->protected_);
1408         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1409                 return false;
1410 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1411         encoder->protected_->verify = value;
1412 #endif
1413         return true;
1414 }
1415
1416 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1417 {
1418         FLAC__ASSERT(0 != encoder);
1419         FLAC__ASSERT(0 != encoder->private_);
1420         FLAC__ASSERT(0 != encoder->protected_);
1421         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1422                 return false;
1423         encoder->protected_->streamable_subset = value;
1424         return true;
1425 }
1426
1427 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
1428 {
1429         FLAC__ASSERT(0 != encoder);
1430         FLAC__ASSERT(0 != encoder->private_);
1431         FLAC__ASSERT(0 != encoder->protected_);
1432         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1433                 return false;
1434         encoder->protected_->do_md5 = value;
1435         return true;
1436 }
1437
1438 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1439 {
1440         FLAC__ASSERT(0 != encoder);
1441         FLAC__ASSERT(0 != encoder->private_);
1442         FLAC__ASSERT(0 != encoder->protected_);
1443         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1444                 return false;
1445         encoder->protected_->channels = value;
1446         return true;
1447 }
1448
1449 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1450 {
1451         FLAC__ASSERT(0 != encoder);
1452         FLAC__ASSERT(0 != encoder->private_);
1453         FLAC__ASSERT(0 != encoder->protected_);
1454         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1455                 return false;
1456         encoder->protected_->bits_per_sample = value;
1457         return true;
1458 }
1459
1460 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1461 {
1462         FLAC__ASSERT(0 != encoder);
1463         FLAC__ASSERT(0 != encoder->private_);
1464         FLAC__ASSERT(0 != encoder->protected_);
1465         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1466                 return false;
1467         encoder->protected_->sample_rate = value;
1468         return true;
1469 }
1470
1471 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1472 {
1473         FLAC__bool ok = true;
1474         FLAC__ASSERT(0 != encoder);
1475         FLAC__ASSERT(0 != encoder->private_);
1476         FLAC__ASSERT(0 != encoder->protected_);
1477         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1478                 return false;
1479         if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1480                 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1481         ok &= FLAC__stream_encoder_set_do_mid_side_stereo          (encoder, compression_levels_[value].do_mid_side_stereo);
1482         ok &= FLAC__stream_encoder_set_loose_mid_side_stereo       (encoder, compression_levels_[value].loose_mid_side_stereo);
1483 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1484 #if 0
1485         /* was: */
1486         ok &= FLAC__stream_encoder_set_apodization                 (encoder, compression_levels_[value].apodization);
1487         /* but it's too hard to specify the string in a locale-specific way */
1488 #else
1489         encoder->protected_->num_apodizations = 1;
1490         encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1491         encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1492 #endif
1493 #endif
1494         ok &= FLAC__stream_encoder_set_max_lpc_order               (encoder, compression_levels_[value].max_lpc_order);
1495         ok &= FLAC__stream_encoder_set_qlp_coeff_precision         (encoder, compression_levels_[value].qlp_coeff_precision);
1496         ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search    (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1497         ok &= FLAC__stream_encoder_set_do_escape_coding            (encoder, compression_levels_[value].do_escape_coding);
1498         ok &= FLAC__stream_encoder_set_do_exhaustive_model_search  (encoder, compression_levels_[value].do_exhaustive_model_search);
1499         ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1500         ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1501         ok &= FLAC__stream_encoder_set_rice_parameter_search_dist  (encoder, compression_levels_[value].rice_parameter_search_dist);
1502         return ok;
1503 }
1504
1505 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1506 {
1507         FLAC__ASSERT(0 != encoder);
1508         FLAC__ASSERT(0 != encoder->private_);
1509         FLAC__ASSERT(0 != encoder->protected_);
1510         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1511                 return false;
1512         encoder->protected_->blocksize = value;
1513         return true;
1514 }
1515
1516 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1517 {
1518         FLAC__ASSERT(0 != encoder);
1519         FLAC__ASSERT(0 != encoder->private_);
1520         FLAC__ASSERT(0 != encoder->protected_);
1521         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1522                 return false;
1523         encoder->protected_->do_mid_side_stereo = value;
1524         return true;
1525 }
1526
1527 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1528 {
1529         FLAC__ASSERT(0 != encoder);
1530         FLAC__ASSERT(0 != encoder->private_);
1531         FLAC__ASSERT(0 != encoder->protected_);
1532         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1533                 return false;
1534         encoder->protected_->loose_mid_side_stereo = value;
1535         return true;
1536 }
1537
1538 /*@@@@add to tests*/
1539 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1540 {
1541         FLAC__ASSERT(0 != encoder);
1542         FLAC__ASSERT(0 != encoder->private_);
1543         FLAC__ASSERT(0 != encoder->protected_);
1544         FLAC__ASSERT(0 != specification);
1545         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1546                 return false;
1547 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1548         (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1549 #else
1550         encoder->protected_->num_apodizations = 0;
1551         while(1) {
1552                 const char *s = strchr(specification, ';');
1553                 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1554                 if     (n==8  && 0 == strncmp("bartlett"     , specification, n))
1555                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1556                 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1557                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1558                 else if(n==8  && 0 == strncmp("blackman"     , specification, n))
1559                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1560                 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1561                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1562                 else if(n==6  && 0 == strncmp("connes"       , specification, n))
1563                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1564                 else if(n==7  && 0 == strncmp("flattop"      , specification, n))
1565                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1566                 else if(n>7   && 0 == strncmp("gauss("       , specification, 6)) {
1567                         FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1568                         if (stddev > 0.0 && stddev <= 0.5) {
1569                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1570                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1571                         }
1572                 }
1573                 else if(n==7  && 0 == strncmp("hamming"      , specification, n))
1574                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1575                 else if(n==4  && 0 == strncmp("hann"         , specification, n))
1576                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1577                 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1578                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1579                 else if(n==7  && 0 == strncmp("nuttall"      , specification, n))
1580                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1581                 else if(n==9  && 0 == strncmp("rectangle"    , specification, n))
1582                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1583                 else if(n==8  && 0 == strncmp("triangle"     , specification, n))
1584                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1585                 else if(n>7   && 0 == strncmp("tukey("       , specification, 6)) {
1586                         FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1587                         if (p >= 0.0 && p <= 1.0) {
1588                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1589                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1590                         }
1591                 }
1592                 else if(n==5  && 0 == strncmp("welch"        , specification, n))
1593                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1594                 if (encoder->protected_->num_apodizations == 32)
1595                         break;
1596                 if (s)
1597                         specification = s+1;
1598                 else
1599                         break;
1600         }
1601         if(encoder->protected_->num_apodizations == 0) {
1602                 encoder->protected_->num_apodizations = 1;
1603                 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1604                 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1605         }
1606 #endif
1607         return true;
1608 }
1609
1610 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1611 {
1612         FLAC__ASSERT(0 != encoder);
1613         FLAC__ASSERT(0 != encoder->private_);
1614         FLAC__ASSERT(0 != encoder->protected_);
1615         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1616                 return false;
1617         encoder->protected_->max_lpc_order = value;
1618         return true;
1619 }
1620
1621 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1622 {
1623         FLAC__ASSERT(0 != encoder);
1624         FLAC__ASSERT(0 != encoder->private_);
1625         FLAC__ASSERT(0 != encoder->protected_);
1626         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1627                 return false;
1628         encoder->protected_->qlp_coeff_precision = value;
1629         return true;
1630 }
1631
1632 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1633 {
1634         FLAC__ASSERT(0 != encoder);
1635         FLAC__ASSERT(0 != encoder->private_);
1636         FLAC__ASSERT(0 != encoder->protected_);
1637         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1638                 return false;
1639         encoder->protected_->do_qlp_coeff_prec_search = value;
1640         return true;
1641 }
1642
1643 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1644 {
1645         FLAC__ASSERT(0 != encoder);
1646         FLAC__ASSERT(0 != encoder->private_);
1647         FLAC__ASSERT(0 != encoder->protected_);
1648         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1649                 return false;
1650 #if 0
1651         /*@@@ deprecated: */
1652         encoder->protected_->do_escape_coding = value;
1653 #else
1654         (void)value;
1655 #endif
1656         return true;
1657 }
1658
1659 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1660 {
1661         FLAC__ASSERT(0 != encoder);
1662         FLAC__ASSERT(0 != encoder->private_);
1663         FLAC__ASSERT(0 != encoder->protected_);
1664         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1665                 return false;
1666         encoder->protected_->do_exhaustive_model_search = value;
1667         return true;
1668 }
1669
1670 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1671 {
1672         FLAC__ASSERT(0 != encoder);
1673         FLAC__ASSERT(0 != encoder->private_);
1674         FLAC__ASSERT(0 != encoder->protected_);
1675         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1676                 return false;
1677         encoder->protected_->min_residual_partition_order = value;
1678         return true;
1679 }
1680
1681 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1682 {
1683         FLAC__ASSERT(0 != encoder);
1684         FLAC__ASSERT(0 != encoder->private_);
1685         FLAC__ASSERT(0 != encoder->protected_);
1686         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1687                 return false;
1688         encoder->protected_->max_residual_partition_order = value;
1689         return true;
1690 }
1691
1692 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1693 {
1694         FLAC__ASSERT(0 != encoder);
1695         FLAC__ASSERT(0 != encoder->private_);
1696         FLAC__ASSERT(0 != encoder->protected_);
1697         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1698                 return false;
1699 #if 0
1700         /*@@@ deprecated: */
1701         encoder->protected_->rice_parameter_search_dist = value;
1702 #else
1703         (void)value;
1704 #endif
1705         return true;
1706 }
1707
1708 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1709 {
1710         FLAC__ASSERT(0 != encoder);
1711         FLAC__ASSERT(0 != encoder->private_);
1712         FLAC__ASSERT(0 != encoder->protected_);
1713         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1714                 return false;
1715         encoder->protected_->total_samples_estimate = value;
1716         return true;
1717 }
1718
1719 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1720 {
1721         FLAC__ASSERT(0 != encoder);
1722         FLAC__ASSERT(0 != encoder->private_);
1723         FLAC__ASSERT(0 != encoder->protected_);
1724         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1725                 return false;
1726         if(0 == metadata)
1727                 num_blocks = 0;
1728         if(0 == num_blocks)
1729                 metadata = 0;
1730         /* realloc() does not do exactly what we want so... */
1731         if(encoder->protected_->metadata) {
1732                 free(encoder->protected_->metadata);
1733                 encoder->protected_->metadata = 0;
1734                 encoder->protected_->num_metadata_blocks = 0;
1735         }
1736         if(num_blocks) {
1737                 FLAC__StreamMetadata **m;
1738                 if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
1739                         return false;
1740                 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1741                 encoder->protected_->metadata = m;
1742                 encoder->protected_->num_metadata_blocks = num_blocks;
1743         }
1744 #if FLAC__HAS_OGG
1745         if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1746                 return false;
1747 #endif
1748         return true;
1749 }
1750
1751 /*
1752  * These three functions are not static, but not publically exposed in
1753  * include/FLAC/ either.  They are used by the test suite.
1754  */
1755 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1756 {
1757         FLAC__ASSERT(0 != encoder);
1758         FLAC__ASSERT(0 != encoder->private_);
1759         FLAC__ASSERT(0 != encoder->protected_);
1760         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1761                 return false;
1762         encoder->private_->disable_constant_subframes = value;
1763         return true;
1764 }
1765
1766 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1767 {
1768         FLAC__ASSERT(0 != encoder);
1769         FLAC__ASSERT(0 != encoder->private_);
1770         FLAC__ASSERT(0 != encoder->protected_);
1771         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1772                 return false;
1773         encoder->private_->disable_fixed_subframes = value;
1774         return true;
1775 }
1776
1777 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1778 {
1779         FLAC__ASSERT(0 != encoder);
1780         FLAC__ASSERT(0 != encoder->private_);
1781         FLAC__ASSERT(0 != encoder->protected_);
1782         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1783                 return false;
1784         encoder->private_->disable_verbatim_subframes = value;
1785         return true;
1786 }
1787
1788 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1789 {
1790         FLAC__ASSERT(0 != encoder);
1791         FLAC__ASSERT(0 != encoder->private_);
1792         FLAC__ASSERT(0 != encoder->protected_);
1793         return encoder->protected_->state;
1794 }
1795
1796 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1797 {
1798         FLAC__ASSERT(0 != encoder);
1799         FLAC__ASSERT(0 != encoder->private_);
1800         FLAC__ASSERT(0 != encoder->protected_);
1801         if(encoder->protected_->verify)
1802                 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1803         else
1804                 return FLAC__STREAM_DECODER_UNINITIALIZED;
1805 }
1806
1807 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1808 {
1809         FLAC__ASSERT(0 != encoder);
1810         FLAC__ASSERT(0 != encoder->private_);
1811         FLAC__ASSERT(0 != encoder->protected_);
1812         if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1813                 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1814         else
1815                 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1816 }
1817
1818 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)
1819 {
1820         FLAC__ASSERT(0 != encoder);
1821         FLAC__ASSERT(0 != encoder->private_);
1822         FLAC__ASSERT(0 != encoder->protected_);
1823         if(0 != absolute_sample)
1824                 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1825         if(0 != frame_number)
1826                 *frame_number = encoder->private_->verify.error_stats.frame_number;
1827         if(0 != channel)
1828                 *channel = encoder->private_->verify.error_stats.channel;
1829         if(0 != sample)
1830                 *sample = encoder->private_->verify.error_stats.sample;
1831         if(0 != expected)
1832                 *expected = encoder->private_->verify.error_stats.expected;
1833         if(0 != got)
1834                 *got = encoder->private_->verify.error_stats.got;
1835 }
1836
1837 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1838 {
1839         FLAC__ASSERT(0 != encoder);
1840         FLAC__ASSERT(0 != encoder->private_);
1841         FLAC__ASSERT(0 != encoder->protected_);
1842         return encoder->protected_->verify;
1843 }
1844
1845 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1846 {
1847         FLAC__ASSERT(0 != encoder);
1848         FLAC__ASSERT(0 != encoder->private_);
1849         FLAC__ASSERT(0 != encoder->protected_);
1850         return encoder->protected_->streamable_subset;
1851 }
1852
1853 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
1854 {
1855         FLAC__ASSERT(0 != encoder);
1856         FLAC__ASSERT(0 != encoder->private_);
1857         FLAC__ASSERT(0 != encoder->protected_);
1858         return encoder->protected_->do_md5;
1859 }
1860
1861 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1862 {
1863         FLAC__ASSERT(0 != encoder);
1864         FLAC__ASSERT(0 != encoder->private_);
1865         FLAC__ASSERT(0 != encoder->protected_);
1866         return encoder->protected_->channels;
1867 }
1868
1869 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1870 {
1871         FLAC__ASSERT(0 != encoder);
1872         FLAC__ASSERT(0 != encoder->private_);
1873         FLAC__ASSERT(0 != encoder->protected_);
1874         return encoder->protected_->bits_per_sample;
1875 }
1876
1877 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1878 {
1879         FLAC__ASSERT(0 != encoder);
1880         FLAC__ASSERT(0 != encoder->private_);
1881         FLAC__ASSERT(0 != encoder->protected_);
1882         return encoder->protected_->sample_rate;
1883 }
1884
1885 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1886 {
1887         FLAC__ASSERT(0 != encoder);
1888         FLAC__ASSERT(0 != encoder->private_);
1889         FLAC__ASSERT(0 != encoder->protected_);
1890         return encoder->protected_->blocksize;
1891 }
1892
1893 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1894 {
1895         FLAC__ASSERT(0 != encoder);
1896         FLAC__ASSERT(0 != encoder->private_);
1897         FLAC__ASSERT(0 != encoder->protected_);
1898         return encoder->protected_->do_mid_side_stereo;
1899 }
1900
1901 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1902 {
1903         FLAC__ASSERT(0 != encoder);
1904         FLAC__ASSERT(0 != encoder->private_);
1905         FLAC__ASSERT(0 != encoder->protected_);
1906         return encoder->protected_->loose_mid_side_stereo;
1907 }
1908
1909 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1910 {
1911         FLAC__ASSERT(0 != encoder);
1912         FLAC__ASSERT(0 != encoder->private_);
1913         FLAC__ASSERT(0 != encoder->protected_);
1914         return encoder->protected_->max_lpc_order;
1915 }
1916
1917 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1918 {
1919         FLAC__ASSERT(0 != encoder);
1920         FLAC__ASSERT(0 != encoder->private_);
1921         FLAC__ASSERT(0 != encoder->protected_);
1922         return encoder->protected_->qlp_coeff_precision;
1923 }
1924
1925 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1926 {
1927         FLAC__ASSERT(0 != encoder);
1928         FLAC__ASSERT(0 != encoder->private_);
1929         FLAC__ASSERT(0 != encoder->protected_);
1930         return encoder->protected_->do_qlp_coeff_prec_search;
1931 }
1932
1933 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1934 {
1935         FLAC__ASSERT(0 != encoder);
1936         FLAC__ASSERT(0 != encoder->private_);
1937         FLAC__ASSERT(0 != encoder->protected_);
1938         return encoder->protected_->do_escape_coding;
1939 }
1940
1941 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1942 {
1943         FLAC__ASSERT(0 != encoder);
1944         FLAC__ASSERT(0 != encoder->private_);
1945         FLAC__ASSERT(0 != encoder->protected_);
1946         return encoder->protected_->do_exhaustive_model_search;
1947 }
1948
1949 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1950 {
1951         FLAC__ASSERT(0 != encoder);
1952         FLAC__ASSERT(0 != encoder->private_);
1953         FLAC__ASSERT(0 != encoder->protected_);
1954         return encoder->protected_->min_residual_partition_order;
1955 }
1956
1957 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1958 {
1959         FLAC__ASSERT(0 != encoder);
1960         FLAC__ASSERT(0 != encoder->private_);
1961         FLAC__ASSERT(0 != encoder->protected_);
1962         return encoder->protected_->max_residual_partition_order;
1963 }
1964
1965 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1966 {
1967         FLAC__ASSERT(0 != encoder);
1968         FLAC__ASSERT(0 != encoder->private_);
1969         FLAC__ASSERT(0 != encoder->protected_);
1970         return encoder->protected_->rice_parameter_search_dist;
1971 }
1972
1973 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1974 {
1975         FLAC__ASSERT(0 != encoder);
1976         FLAC__ASSERT(0 != encoder->private_);
1977         FLAC__ASSERT(0 != encoder->protected_);
1978         return encoder->protected_->total_samples_estimate;
1979 }
1980
1981 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1982 {
1983         unsigned i, j = 0, channel;
1984         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1985
1986         FLAC__ASSERT(0 != encoder);
1987         FLAC__ASSERT(0 != encoder->private_);
1988         FLAC__ASSERT(0 != encoder->protected_);
1989         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1990
1991         do {
1992                 const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
1993
1994                 if(encoder->protected_->verify)
1995                         append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
1996
1997                 for(channel = 0; channel < channels; channel++)
1998                         memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
1999
2000                 if(encoder->protected_->do_mid_side_stereo) {
2001                         FLAC__ASSERT(channels == 2);
2002                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2003                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2004                                 encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
2005                                 encoder->private_->integer_signal_mid_side[0][i] = (buffer[0][j] + buffer[1][j]) >> 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
2006                         }
2007                 }
2008                 else
2009                         j += n;
2010
2011                 encoder->private_->current_sample_number += n;
2012
2013                 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2014                 if(encoder->private_->current_sample_number > blocksize) {
2015                         FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
2016                         FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2017                         if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2018                                 return false;
2019                         /* move unprocessed overread samples to beginnings of arrays */
2020                         for(channel = 0; channel < channels; channel++)
2021                                 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2022                         if(encoder->protected_->do_mid_side_stereo) {
2023                                 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2024                                 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2025                         }
2026                         encoder->private_->current_sample_number = 1;
2027                 }
2028         } while(j < samples);
2029
2030         return true;
2031 }
2032
2033 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2034 {
2035         unsigned i, j, k, channel;
2036         FLAC__int32 x, mid, side;
2037         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2038
2039         FLAC__ASSERT(0 != encoder);
2040         FLAC__ASSERT(0 != encoder->private_);
2041         FLAC__ASSERT(0 != encoder->protected_);
2042         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2043
2044         j = k = 0;
2045         /*
2046          * we have several flavors of the same basic loop, optimized for
2047          * different conditions:
2048          */
2049         if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2050                 /*
2051                  * stereo coding: unroll channel loop
2052                  */
2053                 do {
2054                         if(encoder->protected_->verify)
2055                                 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2056
2057                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2058                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2059                                 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2060                                 x = buffer[k++];
2061                                 encoder->private_->integer_signal[1][i] = x;
2062                                 mid += x;
2063                                 side -= x;
2064                                 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2065                                 encoder->private_->integer_signal_mid_side[1][i] = side;
2066                                 encoder->private_->integer_signal_mid_side[0][i] = mid;
2067                         }
2068                         encoder->private_->current_sample_number = i;
2069                         /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2070                         if(i > blocksize) {
2071                                 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2072                                         return false;
2073                                 /* move unprocessed overread samples to beginnings of arrays */
2074                                 FLAC__ASSERT(i == blocksize+OVERREAD_);
2075                                 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2076                                 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
2077                                 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
2078                                 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2079                                 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2080                                 encoder->private_->current_sample_number = 1;
2081                         }
2082                 } while(j < samples);
2083         }
2084         else {
2085                 /*
2086                  * independent channel coding: buffer each channel in inner loop
2087                  */
2088                 do {
2089                         if(encoder->protected_->verify)
2090                                 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2091
2092                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2093                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2094                                 for(channel = 0; channel < channels; channel++)
2095                                         encoder->private_->integer_signal[channel][i] = buffer[k++];
2096                         }
2097                         encoder->private_->current_sample_number = i;
2098                         /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2099                         if(i > blocksize) {
2100                                 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2101                                         return false;
2102                                 /* move unprocessed overread samples to beginnings of arrays */
2103                                 FLAC__ASSERT(i == blocksize+OVERREAD_);
2104                                 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2105                                 for(channel = 0; channel < channels; channel++)
2106                                         encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2107                                 encoder->private_->current_sample_number = 1;
2108                         }
2109                 } while(j < samples);
2110         }
2111
2112         return true;
2113 }
2114
2115 /***********************************************************************
2116  *
2117  * Private class methods
2118  *
2119  ***********************************************************************/
2120
2121 void set_defaults_(FLAC__StreamEncoder *encoder)
2122 {
2123         FLAC__ASSERT(0 != encoder);
2124
2125 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2126         encoder->protected_->verify = true;
2127 #else
2128         encoder->protected_->verify = false;
2129 #endif
2130         encoder->protected_->streamable_subset = true;
2131         encoder->protected_->do_md5 = true;
2132         encoder->protected_->do_mid_side_stereo = false;
2133         encoder->protected_->loose_mid_side_stereo = false;
2134         encoder->protected_->channels = 2;
2135         encoder->protected_->bits_per_sample = 16;
2136         encoder->protected_->sample_rate = 44100;
2137         encoder->protected_->blocksize = 0;
2138 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2139         encoder->protected_->num_apodizations = 1;
2140         encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2141         encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2142 #endif
2143         encoder->protected_->max_lpc_order = 0;
2144         encoder->protected_->qlp_coeff_precision = 0;
2145         encoder->protected_->do_qlp_coeff_prec_search = false;
2146         encoder->protected_->do_exhaustive_model_search = false;
2147         encoder->protected_->do_escape_coding = false;
2148         encoder->protected_->min_residual_partition_order = 0;
2149         encoder->protected_->max_residual_partition_order = 0;
2150         encoder->protected_->rice_parameter_search_dist = 0;
2151         encoder->protected_->total_samples_estimate = 0;
2152         encoder->protected_->metadata = 0;
2153         encoder->protected_->num_metadata_blocks = 0;
2154
2155         encoder->private_->seek_table = 0;
2156         encoder->private_->disable_constant_subframes = false;
2157         encoder->private_->disable_fixed_subframes = false;
2158         encoder->private_->disable_verbatim_subframes = false;
2159 #if FLAC__HAS_OGG
2160         encoder->private_->is_ogg = false;
2161 #endif
2162         encoder->private_->read_callback = 0;
2163         encoder->private_->write_callback = 0;
2164         encoder->private_->seek_callback = 0;
2165         encoder->private_->tell_callback = 0;
2166         encoder->private_->metadata_callback = 0;
2167         encoder->private_->progress_callback = 0;
2168         encoder->private_->client_data = 0;
2169
2170 #if FLAC__HAS_OGG
2171         FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2172 #endif
2173 }
2174
2175 void free_(FLAC__StreamEncoder *encoder)
2176 {
2177         unsigned i, channel;
2178
2179         FLAC__ASSERT(0 != encoder);
2180         if(encoder->protected_->metadata) {
2181                 free(encoder->protected_->metadata);
2182                 encoder->protected_->metadata = 0;
2183                 encoder->protected_->num_metadata_blocks = 0;
2184         }
2185         for(i = 0; i < encoder->protected_->channels; i++) {
2186                 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2187                         free(encoder->private_->integer_signal_unaligned[i]);
2188                         encoder->private_->integer_signal_unaligned[i] = 0;
2189                 }
2190 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2191                 if(0 != encoder->private_->real_signal_unaligned[i]) {
2192                         free(encoder->private_->real_signal_unaligned[i]);
2193                         encoder->private_->real_signal_unaligned[i] = 0;
2194                 }
2195 #endif
2196         }
2197         for(i = 0; i < 2; i++) {
2198                 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2199                         free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2200                         encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2201                 }
2202 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2203                 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2204                         free(encoder->private_->real_signal_mid_side_unaligned[i]);
2205                         encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2206                 }
2207 #endif
2208         }
2209 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2210         for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2211                 if(0 != encoder->private_->window_unaligned[i]) {
2212                         free(encoder->private_->window_unaligned[i]);
2213                         encoder->private_->window_unaligned[i] = 0;
2214                 }
2215         }
2216         if(0 != encoder->private_->windowed_signal_unaligned) {
2217                 free(encoder->private_->windowed_signal_unaligned);
2218                 encoder->private_->windowed_signal_unaligned = 0;
2219         }
2220 #endif
2221         for(channel = 0; channel < encoder->protected_->channels; channel++) {
2222                 for(i = 0; i < 2; i++) {
2223                         if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2224                                 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2225                                 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2226                         }
2227                 }
2228         }
2229         for(channel = 0; channel < 2; channel++) {
2230                 for(i = 0; i < 2; i++) {
2231                         if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2232                                 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2233                                 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2234                         }
2235                 }
2236         }
2237         if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2238                 free(encoder->private_->abs_residual_partition_sums_unaligned);
2239                 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2240         }
2241         if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2242                 free(encoder->private_->raw_bits_per_partition_unaligned);
2243                 encoder->private_->raw_bits_per_partition_unaligned = 0;
2244         }
2245         if(encoder->protected_->verify) {
2246                 for(i = 0; i < encoder->protected_->channels; i++) {
2247                         if(0 != encoder->private_->verify.input_fifo.data[i]) {
2248                                 free(encoder->private_->verify.input_fifo.data[i]);
2249                                 encoder->private_->verify.input_fifo.data[i] = 0;
2250                         }
2251                 }
2252         }
2253         FLAC__bitwriter_free(encoder->private_->frame);
2254 }
2255
2256 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2257 {
2258         FLAC__bool ok;
2259         unsigned i, channel;
2260
2261         FLAC__ASSERT(new_blocksize > 0);
2262         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2263         FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2264
2265         /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2266         if(new_blocksize <= encoder->private_->input_capacity)
2267                 return true;
2268
2269         ok = true;
2270
2271         /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
2272          * requires that the input arrays (in our case the integer signals)
2273          * have a buffer of up to 3 zeroes in front (at negative indices) for
2274          * alignment purposes; we use 4 in front to keep the data well-aligned.
2275          */
2276
2277         for(i = 0; ok && i < encoder->protected_->channels; i++) {
2278                 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2279                 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2280                 encoder->private_->integer_signal[i] += 4;
2281 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2282 #if 0 /* @@@ currently unused */
2283                 if(encoder->protected_->max_lpc_order > 0)
2284                         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2285 #endif
2286 #endif
2287         }
2288         for(i = 0; ok && i < 2; i++) {
2289                 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_mid_side_unaligned[i], &encoder->private_->integer_signal_mid_side[i]);
2290                 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2291                 encoder->private_->integer_signal_mid_side[i] += 4;
2292 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2293 #if 0 /* @@@ currently unused */
2294                 if(encoder->protected_->max_lpc_order > 0)
2295                         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_mid_side_unaligned[i], &encoder->private_->real_signal_mid_side[i]);
2296 #endif
2297 #endif
2298         }
2299 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2300         if(ok && encoder->protected_->max_lpc_order > 0) {
2301                 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2302                         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2303                 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2304         }
2305 #endif
2306         for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2307                 for(i = 0; ok && i < 2; i++) {
2308                         ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2309                 }
2310         }
2311         for(channel = 0; ok && channel < 2; channel++) {
2312                 for(i = 0; ok && i < 2; i++) {
2313                         ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_mid_side_unaligned[channel][i], &encoder->private_->residual_workspace_mid_side[channel][i]);
2314                 }
2315         }
2316         /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2317         /*@@@ new_blocksize*2 is too pessimistic, but to fix, we need smarter logic because a smaller new_blocksize can actually increase the # of partitions; would require moving this out into a separate function, then checking its capacity against the need of the current blocksize&min/max_partition_order (and maybe predictor order) */
2318         ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2319         if(encoder->protected_->do_escape_coding)
2320                 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2321
2322         /* now adjust the windows if the blocksize has changed */
2323 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2324         if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2325                 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2326                         switch(encoder->protected_->apodizations[i].type) {
2327                                 case FLAC__APODIZATION_BARTLETT:
2328                                         FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2329                                         break;
2330                                 case FLAC__APODIZATION_BARTLETT_HANN:
2331                                         FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2332                                         break;
2333                                 case FLAC__APODIZATION_BLACKMAN:
2334                                         FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2335                                         break;
2336                                 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2337                                         FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2338                                         break;
2339                                 case FLAC__APODIZATION_CONNES:
2340                                         FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2341                                         break;
2342                                 case FLAC__APODIZATION_FLATTOP:
2343                                         FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2344                                         break;
2345                                 case FLAC__APODIZATION_GAUSS:
2346                                         FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2347                                         break;
2348                                 case FLAC__APODIZATION_HAMMING:
2349                                         FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2350                                         break;
2351                                 case FLAC__APODIZATION_HANN:
2352                                         FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2353                                         break;
2354                                 case FLAC__APODIZATION_KAISER_BESSEL:
2355                                         FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2356                                         break;
2357                                 case FLAC__APODIZATION_NUTTALL:
2358                                         FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2359                                         break;
2360                                 case FLAC__APODIZATION_RECTANGLE:
2361                                         FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2362                                         break;
2363                                 case FLAC__APODIZATION_TRIANGLE:
2364                                         FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2365                                         break;
2366                                 case FLAC__APODIZATION_TUKEY:
2367                                         FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2368                                         break;
2369                                 case FLAC__APODIZATION_WELCH:
2370                                         FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2371                                         break;
2372                                 default:
2373                                         FLAC__ASSERT(0);
2374                                         /* double protection */
2375                                         FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2376                                         break;
2377                         }
2378                 }
2379         }
2380 #endif
2381
2382         if(ok)
2383                 encoder->private_->input_capacity = new_blocksize;
2384         else
2385                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2386
2387         return ok;
2388 }
2389
2390 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2391 {
2392         const FLAC__byte *buffer;
2393         size_t bytes;
2394
2395         FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2396
2397         if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2398                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2399                 return false;
2400         }
2401
2402         if(encoder->protected_->verify) {
2403                 encoder->private_->verify.output.data = buffer;
2404                 encoder->private_->verify.output.bytes = bytes;
2405                 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2406                         encoder->private_->verify.needs_magic_hack = true;
2407                 }
2408                 else {
2409                         if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2410                                 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2411                                 FLAC__bitwriter_clear(encoder->private_->frame);
2412                                 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2413                                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2414                                 return false;
2415                         }
2416                 }
2417         }
2418
2419         if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2420                 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2421                 FLAC__bitwriter_clear(encoder->private_->frame);
2422                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2423                 return false;
2424         }
2425
2426         FLAC__bitwriter_release_buffer(encoder->private_->frame);
2427         FLAC__bitwriter_clear(encoder->private_->frame);
2428
2429         if(samples > 0) {
2430                 encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2431                 encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2432         }
2433
2434         return true;
2435 }
2436
2437 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2438 {
2439         FLAC__StreamEncoderWriteStatus status;
2440         FLAC__uint64 output_position = 0;
2441
2442         /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2443         if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2444                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2445                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2446         }
2447
2448         /*
2449          * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2450          */
2451         if(samples == 0) {
2452                 FLAC__MetadataType type = (buffer[0] & 0x7f);
2453                 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2454                         encoder->protected_->streaminfo_offset = output_position;
2455                 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2456                         encoder->protected_->seektable_offset = output_position;
2457         }
2458
2459         /*
2460          * Mark the current seek point if hit (if audio_offset == 0 that
2461          * means we're still writing metadata and haven't hit the first
2462          * frame yet)
2463          */
2464         if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2465                 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2466                 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2467                 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2468                 FLAC__uint64 test_sample;
2469                 unsigned i;
2470                 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2471                         test_sample = encoder->private_->seek_table->points[i].sample_number;
2472                         if(test_sample > frame_last_sample) {
2473                                 break;
2474                         }
2475                         else if(test_sample >= frame_first_sample) {
2476                                 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2477                                 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2478                                 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2479                                 encoder->private_->first_seekpoint_to_check++;
2480                                 /* DO NOT: "break;" and here's why:
2481                                  * The seektable template may contain more than one target
2482                                  * sample for any given frame; we will keep looping, generating
2483                                  * duplicate seekpoints for them, and we'll clean it up later,
2484                                  * just before writing the seektable back to the metadata.
2485                                  */
2486                         }
2487                         else {
2488                                 encoder->private_->first_seekpoint_to_check++;
2489                         }
2490                 }
2491         }
2492
2493 #if FLAC__HAS_OGG
2494         if(encoder->private_->is_ogg) {
2495                 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2496                         &encoder->protected_->ogg_encoder_aspect,
2497                         buffer,
2498                         bytes,
2499                         samples,
2500                         encoder->private_->current_frame_number,
2501                         is_last_block,
2502                         (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2503                         encoder,
2504                         encoder->private_->client_data
2505                 );
2506         }
2507         else
2508 #endif
2509         status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2510
2511         if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2512                 encoder->private_->bytes_written += bytes;
2513                 encoder->private_->samples_written += samples;
2514                 /* we keep a high watermark on the number of frames written because
2515                  * when the encoder goes back to write metadata, 'current_frame'
2516                  * will drop back to 0.
2517                  */
2518                 encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2519         }
2520         else
2521                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2522
2523         return status;
2524 }
2525
2526 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2527 void update_metadata_(const FLAC__StreamEncoder *encoder)
2528 {
2529         FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2530         const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2531         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2532         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2533         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2534         const unsigned bps = metadata->data.stream_info.bits_per_sample;
2535         FLAC__StreamEncoderSeekStatus seek_status;
2536
2537         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2538
2539         /* All this is based on intimate knowledge of the stream header
2540          * layout, but a change to the header format that would break this
2541          * would also break all streams encoded in the previous format.
2542          */
2543
2544         /*
2545          * Write MD5 signature
2546          */
2547         {
2548                 const unsigned md5_offset =
2549                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2550                         (
2551                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2552                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2553                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2554                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2555                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2556                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2557                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2558                                 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2559                         ) / 8;
2560
2561                 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2562                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2563                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2564                         return;
2565                 }
2566                 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2567                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2568                         return;
2569                 }
2570         }
2571
2572         /*
2573          * Write total samples
2574          */
2575         {
2576                 const unsigned total_samples_byte_offset =
2577                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2578                         (
2579                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2580                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2581                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2582                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2583                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2584                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2585                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2586                                 - 4
2587                         ) / 8;
2588
2589                 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2590                 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2591                 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2592                 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2593                 b[4] = (FLAC__byte)(samples & 0xFF);
2594                 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + total_samples_byte_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2595                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2596                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2597                         return;
2598                 }
2599                 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2600                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2601                         return;
2602                 }
2603         }
2604
2605         /*
2606          * Write min/max framesize
2607          */
2608         {
2609                 const unsigned min_framesize_offset =
2610                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2611                         (
2612                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2613                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2614                         ) / 8;
2615
2616                 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2617                 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2618                 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2619                 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2620                 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2621                 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2622                 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + min_framesize_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2623                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2624                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2625                         return;
2626                 }
2627                 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2628                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2629                         return;
2630                 }
2631         }
2632
2633         /*
2634          * Write seektable
2635          */
2636         if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2637                 unsigned i;
2638
2639                 FLAC__format_seektable_sort(encoder->private_->seek_table);
2640
2641                 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2642
2643                 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->seektable_offset + FLAC__STREAM_METADATA_HEADER_LENGTH, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2644                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2645                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2646                         return;
2647                 }
2648
2649                 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2650                         FLAC__uint64 xx;
2651                         unsigned x;
2652                         xx = encoder->private_->seek_table->points[i].sample_number;
2653                         b[7] = (FLAC__byte)xx; xx >>= 8;
2654                         b[6] = (FLAC__byte)xx; xx >>= 8;
2655                         b[5] = (FLAC__byte)xx; xx >>= 8;
2656                         b[4] = (FLAC__byte)xx; xx >>= 8;
2657                         b[3] = (FLAC__byte)xx; xx >>= 8;
2658                         b[2] = (FLAC__byte)xx; xx >>= 8;
2659                         b[1] = (FLAC__byte)xx; xx >>= 8;
2660                         b[0] = (FLAC__byte)xx; xx >>= 8;
2661                         xx = encoder->private_->seek_table->points[i].stream_offset;
2662                         b[15] = (FLAC__byte)xx; xx >>= 8;
2663                         b[14] = (FLAC__byte)xx; xx >>= 8;
2664                         b[13] = (FLAC__byte)xx; xx >>= 8;
2665                         b[12] = (FLAC__byte)xx; xx >>= 8;
2666                         b[11] = (FLAC__byte)xx; xx >>= 8;
2667                         b[10] = (FLAC__byte)xx; xx >>= 8;
2668                         b[9] = (FLAC__byte)xx; xx >>= 8;
2669                         b[8] = (FLAC__byte)xx; xx >>= 8;
2670                         x = encoder->private_->seek_table->points[i].frame_samples;
2671                         b[17] = (FLAC__byte)x; x >>= 8;
2672                         b[16] = (FLAC__byte)x; x >>= 8;
2673                         if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2674                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2675                                 return;
2676                         }
2677                 }
2678         }
2679 }
2680
2681 #if FLAC__HAS_OGG
2682 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2683 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2684 {
2685         /* the # of bytes in the 1st packet that precede the STREAMINFO */
2686         static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2687                 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2688                 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2689                 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2690                 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2691                 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2692                 FLAC__STREAM_SYNC_LENGTH
2693         ;
2694         FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2695         const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2696         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2697         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2698         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2699         ogg_page page;
2700
2701         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2702         FLAC__ASSERT(0 != encoder->private_->seek_callback);
2703
2704         /* Pre-check that client supports seeking, since we don't want the
2705          * ogg_helper code to ever have to deal with this condition.
2706          */
2707         if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2708                 return;
2709
2710         /* All this is based on intimate knowledge of the stream header
2711          * layout, but a change to the header format that would break this
2712          * would also break all streams encoded in the previous format.
2713          */
2714
2715         /**
2716          ** Write STREAMINFO stats
2717          **/
2718         simple_ogg_page__init(&page);
2719         if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2720                 simple_ogg_page__clear(&page);
2721                 return; /* state already set */
2722         }
2723
2724         /*
2725          * Write MD5 signature
2726          */
2727         {
2728                 const unsigned md5_offset =
2729                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2730                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2731                         (
2732                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2733                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2734                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2735                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2736                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2737                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2738                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2739                                 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2740                         ) / 8;
2741
2742                 if(md5_offset + 16 > (unsigned)page.body_len) {
2743                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2744                         simple_ogg_page__clear(&page);
2745                         return;
2746                 }
2747                 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2748         }
2749
2750         /*
2751          * Write total samples
2752          */
2753         {
2754                 const unsigned total_samples_byte_offset =
2755                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2756                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2757                         (
2758                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2759                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2760                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2761                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2762                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2763                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2764                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2765                                 - 4
2766                         ) / 8;
2767
2768                 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2769                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2770                         simple_ogg_page__clear(&page);
2771                         return;
2772                 }
2773                 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2774                 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2775                 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2776                 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2777                 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2778                 b[4] = (FLAC__byte)(samples & 0xFF);
2779                 memcpy(page.body + total_samples_byte_offset, b, 5);
2780         }
2781
2782         /*
2783          * Write min/max framesize
2784          */
2785         {
2786                 const unsigned min_framesize_offset =
2787                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2788                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2789                         (
2790                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2791                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2792                         ) / 8;
2793
2794                 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2795                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2796                         simple_ogg_page__clear(&page);
2797                         return;
2798                 }
2799                 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2800                 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2801                 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2802                 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2803                 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2804                 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2805                 memcpy(page.body + min_framesize_offset, b, 6);
2806         }
2807         if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2808                 simple_ogg_page__clear(&page);
2809                 return; /* state already set */
2810         }
2811         simple_ogg_page__clear(&page);
2812
2813         /*
2814          * Write seektable
2815          */
2816         if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2817                 unsigned i;
2818                 FLAC__byte *p;
2819
2820                 FLAC__format_seektable_sort(encoder->private_->seek_table);
2821
2822                 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2823
2824                 simple_ogg_page__init(&page);
2825                 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2826                         simple_ogg_page__clear(&page);
2827                         return; /* state already set */
2828                 }
2829
2830                 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
2831                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2832                         simple_ogg_page__clear(&page);
2833                         return;
2834                 }
2835
2836                 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
2837                         FLAC__uint64 xx;
2838                         unsigned x;
2839                         xx = encoder->private_->seek_table->points[i].sample_number;
2840                         b[7] = (FLAC__byte)xx; xx >>= 8;
2841                         b[6] = (FLAC__byte)xx; xx >>= 8;
2842                         b[5] = (FLAC__byte)xx; xx >>= 8;
2843                         b[4] = (FLAC__byte)xx; xx >>= 8;
2844                         b[3] = (FLAC__byte)xx; xx >>= 8;
2845                         b[2] = (FLAC__byte)xx; xx >>= 8;
2846                         b[1] = (FLAC__byte)xx; xx >>= 8;
2847                         b[0] = (FLAC__byte)xx; xx >>= 8;
2848                         xx = encoder->private_->seek_table->points[i].stream_offset;
2849                         b[15] = (FLAC__byte)xx; xx >>= 8;
2850                         b[14] = (FLAC__byte)xx; xx >>= 8;
2851                         b[13] = (FLAC__byte)xx; xx >>= 8;
2852                         b[12] = (FLAC__byte)xx; xx >>= 8;
2853                         b[11] = (FLAC__byte)xx; xx >>= 8;
2854                         b[10] = (FLAC__byte)xx; xx >>= 8;
2855                         b[9] = (FLAC__byte)xx; xx >>= 8;
2856                         b[8] = (FLAC__byte)xx; xx >>= 8;
2857                         x = encoder->private_->seek_table->points[i].frame_samples;
2858                         b[17] = (FLAC__byte)x; x >>= 8;
2859                         b[16] = (FLAC__byte)x; x >>= 8;
2860                         memcpy(p, b, 18);
2861                 }
2862
2863                 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2864                         simple_ogg_page__clear(&page);
2865                         return; /* state already set */
2866                 }
2867                 simple_ogg_page__clear(&page);
2868         }
2869 }
2870 #endif
2871
2872 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
2873 {
2874         FLAC__uint16 crc;
2875         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2876
2877         /*
2878          * Accumulate raw signal to the MD5 signature
2879          */
2880         if(encoder->protected_->do_md5 && !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)) {
2881                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2882                 return false;
2883         }
2884
2885         /*
2886          * Process the frame header and subframes into the frame bitbuffer
2887          */
2888         if(!process_subframes_(encoder, is_fractional_block)) {
2889                 /* the above function sets the state for us in case of an error */
2890                 return false;
2891         }
2892
2893         /*
2894          * Zero-pad the frame to a byte_boundary
2895          */
2896         if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
2897                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2898                 return false;
2899         }
2900
2901         /*
2902          * CRC-16 the whole thing
2903          */
2904         FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2905         if(
2906                 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
2907                 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
2908         ) {
2909                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2910                 return false;
2911         }
2912
2913         /*
2914          * Write it
2915          */
2916         if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
2917                 /* the above function sets the state for us in case of an error */
2918                 return false;
2919         }
2920
2921         /*
2922          * Get ready for the next frame
2923          */
2924         encoder->private_->current_sample_number = 0;
2925         encoder->private_->current_frame_number++;
2926         encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
2927
2928         return true;
2929 }
2930
2931 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
2932 {
2933         FLAC__FrameHeader frame_header;
2934         unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
2935         FLAC__bool do_independent, do_mid_side;
2936
2937         /*
2938          * Calculate the min,max Rice partition orders
2939          */
2940         if(is_fractional_block) {
2941                 max_partition_order = 0;
2942         }
2943         else {
2944                 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
2945                 max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
2946         }
2947         min_partition_order = min(min_partition_order, max_partition_order);
2948
2949         /*
2950          * Setup the frame
2951          */
2952         frame_header.blocksize = encoder->protected_->blocksize;
2953         frame_header.sample_rate = encoder->protected_->sample_rate;
2954         frame_header.channels = encoder->protected_->channels;
2955         frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
2956         frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
2957         frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2958         frame_header.number.frame_number = encoder->private_->current_frame_number;
2959
2960         /*
2961          * Figure out what channel assignments to try
2962          */
2963         if(encoder->protected_->do_mid_side_stereo) {
2964                 if(encoder->protected_->loose_mid_side_stereo) {
2965                         if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
2966                                 do_independent = true;
2967                                 do_mid_side = true;
2968                         }
2969                         else {
2970                                 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
2971                                 do_mid_side = !do_independent;
2972                         }
2973                 }
2974                 else {
2975                         do_independent = true;
2976                         do_mid_side = true;
2977                 }
2978         }
2979         else {
2980                 do_independent = true;
2981                 do_mid_side = false;
2982         }
2983
2984         FLAC__ASSERT(do_independent || do_mid_side);
2985
2986         /*
2987          * Check for wasted bits; set effective bps for each subframe
2988          */
2989         if(do_independent) {
2990                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2991                         const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
2992                         encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
2993                         encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
2994                 }
2995         }
2996         if(do_mid_side) {
2997                 FLAC__ASSERT(encoder->protected_->channels == 2);
2998                 for(channel = 0; channel < 2; channel++) {
2999                         const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
3000                         encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
3001                         encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
3002                 }
3003         }
3004
3005         /*
3006          * First do a normal encoding pass of each independent channel
3007          */
3008         if(do_independent) {
3009                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3010                         if(!
3011                                 process_subframe_(
3012                                         encoder,
3013                                         min_partition_order,
3014                                         max_partition_order,
3015                                         &frame_header,
3016                                         encoder->private_->subframe_bps[channel],
3017                                         encoder->private_->integer_signal[channel],
3018                                         encoder->private_->subframe_workspace_ptr[channel],
3019                                         encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3020                                         encoder->private_->residual_workspace[channel],
3021                                         encoder->private_->best_subframe+channel,
3022                                         encoder->private_->best_subframe_bits+channel
3023                                 )
3024                         )
3025                                 return false;
3026                 }
3027         }
3028
3029         /*
3030          * Now do mid and side channels if requested
3031          */
3032         if(do_mid_side) {
3033                 FLAC__ASSERT(encoder->protected_->channels == 2);
3034
3035                 for(channel = 0; channel < 2; channel++) {
3036                         if(!
3037                                 process_subframe_(
3038                                         encoder,
3039                                         min_partition_order,
3040                                         max_partition_order,
3041                                         &frame_header,
3042                                         encoder->private_->subframe_bps_mid_side[channel],
3043                                         encoder->private_->integer_signal_mid_side[channel],
3044                                         encoder->private_->subframe_workspace_ptr_mid_side[channel],
3045                                         encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3046                                         encoder->private_->residual_workspace_mid_side[channel],
3047                                         encoder->private_->best_subframe_mid_side+channel,
3048                                         encoder->private_->best_subframe_bits_mid_side+channel
3049                                 )
3050                         )
3051                                 return false;
3052                 }
3053         }
3054
3055         /*
3056          * Compose the frame bitbuffer
3057          */
3058         if(do_mid_side) {
3059                 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3060                 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3061                 FLAC__ChannelAssignment channel_assignment;
3062
3063                 FLAC__ASSERT(encoder->protected_->channels == 2);
3064
3065                 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3066                         channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3067                 }
3068                 else {
3069                         unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3070                         unsigned min_bits;
3071                         int ca;
3072
3073                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3074                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE   == 1);
3075                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE  == 2);
3076                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE    == 3);
3077                         FLAC__ASSERT(do_independent && do_mid_side);
3078
3079                         /* We have to figure out which channel assignent results in the smallest frame */
3080                         bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits         [1];
3081                         bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE  ] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits_mid_side[1];
3082                         bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits         [1] + encoder->private_->best_subframe_bits_mid_side[1];
3083                         bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE   ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3084
3085                         channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3086                         min_bits = bits[channel_assignment];
3087                         for(ca = 1; ca <= 3; ca++) {
3088                                 if(bits[ca] < min_bits) {
3089                                         min_bits = bits[ca];
3090                                         channel_assignment = (FLAC__ChannelAssignment)ca;
3091                                 }
3092                         }
3093                 }
3094
3095                 frame_header.channel_assignment = channel_assignment;
3096
3097                 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3098                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3099                         return false;
3100                 }
3101
3102                 switch(channel_assignment) {
3103                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3104                                 left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3105                                 right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
3106                                 break;
3107                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3108                                 left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3109                                 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3110                                 break;
3111                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3112                                 left_subframe  = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3113                                 right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
3114                                 break;
3115                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3116                                 left_subframe  = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3117                                 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3118                                 break;
3119                         default:
3120                                 FLAC__ASSERT(0);
3121                 }
3122
3123                 switch(channel_assignment) {
3124                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3125                                 left_bps  = encoder->private_->subframe_bps         [0];
3126                                 right_bps = encoder->private_->subframe_bps         [1];
3127                                 break;
3128                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3129                                 left_bps  = encoder->private_->subframe_bps         [0];
3130                                 right_bps = encoder->private_->subframe_bps_mid_side[1];
3131                                 break;
3132                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3133                                 left_bps  = encoder->private_->subframe_bps_mid_side[1];
3134                                 right_bps = encoder->private_->subframe_bps         [1];
3135                                 break;
3136                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3137                                 left_bps  = encoder->private_->subframe_bps_mid_side[0];
3138                                 right_bps = encoder->private_->subframe_bps_mid_side[1];
3139                                 break;
3140                         default:
3141                                 FLAC__ASSERT(0);
3142                 }
3143
3144                 /* note that encoder_add_subframe_ sets the state for us in case of an error */
3145                 if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3146                         return false;
3147                 if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3148                         return false;
3149         }
3150         else {
3151                 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3152                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3153                         return false;
3154                 }
3155
3156                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3157                         if(!add_subframe_(encoder, frame_header.blocksize, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame)) {
3158                                 /* the above function sets the state for us in case of an error */
3159                                 return false;
3160                         }
3161                 }
3162         }
3163
3164         if(encoder->protected_->loose_mid_side_stereo) {
3165                 encoder->private_->loose_mid_side_stereo_frame_count++;
3166                 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3167                         encoder->private_->loose_mid_side_stereo_frame_count = 0;
3168         }
3169
3170         encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3171
3172         return true;
3173 }
3174
3175 FLAC__bool process_subframe_(
3176         FLAC__StreamEncoder *encoder,
3177         unsigned min_partition_order,
3178         unsigned max_partition_order,
3179         const FLAC__FrameHeader *frame_header,
3180         unsigned subframe_bps,
3181         const FLAC__int32 integer_signal[],
3182         FLAC__Subframe *subframe[2],
3183         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3184         FLAC__int32 *residual[2],
3185         unsigned *best_subframe,
3186         unsigned *best_bits
3187 )
3188 {
3189 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3190         FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3191 #else
3192         FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3193 #endif
3194 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3195         FLAC__double lpc_residual_bits_per_sample;
3196         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 */
3197         FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3198         unsigned min_lpc_order, max_lpc_order, lpc_order;
3199         unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3200 #endif
3201         unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3202         unsigned rice_parameter;
3203         unsigned _candidate_bits, _best_bits;
3204         unsigned _best_subframe;
3205         /* only use RICE2 partitions if stream bps > 16 */
3206         const unsigned rice_parameter_limit = FLAC__stream_encoder_get_bits_per_sample(encoder) > 16? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
3207
3208         FLAC__ASSERT(frame_header->blocksize > 0);
3209
3210         /* verbatim subframe is the baseline against which we measure other compressed subframes */
3211         _best_subframe = 0;
3212         if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3213                 _best_bits = UINT_MAX;
3214         else
3215                 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3216
3217         if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3218                 unsigned signal_is_constant = false;
3219                 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);
3220                 /* check for constant subframe */
3221                 if(
3222                         !encoder->private_->disable_constant_subframes &&
3223 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3224                         fixed_residual_bits_per_sample[1] == 0.0
3225 #else
3226                         fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3227 #endif
3228                 ) {
3229                         /* the above means it's possible all samples are the same value; now double-check it: */
3230                         unsigned i;
3231                         signal_is_constant = true;
3232                         for(i = 1; i < frame_header->blocksize; i++) {
3233                                 if(integer_signal[0] != integer_signal[i]) {
3234                                         signal_is_constant = false;
3235                                         break;
3236                                 }
3237                         }
3238                 }
3239                 if(signal_is_constant) {
3240                         _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3241                         if(_candidate_bits < _best_bits) {
3242                                 _best_subframe = !_best_subframe;
3243                                 _best_bits = _candidate_bits;
3244                         }
3245                 }
3246                 else {
3247                         if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3248                                 /* encode fixed */
3249                                 if(encoder->protected_->do_exhaustive_model_search) {
3250                                         min_fixed_order = 0;
3251                                         max_fixed_order = FLAC__MAX_FIXED_ORDER;
3252                                 }
3253                                 else {
3254                                         min_fixed_order = max_fixed_order = guess_fixed_order;
3255                                 }
3256                                 if(max_fixed_order >= frame_header->blocksize)
3257                                         max_fixed_order = frame_header->blocksize - 1;
3258                                 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3259 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3260                                         if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3261                                                 continue; /* don't even try */
3262                                         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 */
3263 #else
3264                                         if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3265                                                 continue; /* don't even try */
3266                                         rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > FLAC__FP_ZERO)? (unsigned)FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]+FLAC__FP_ONE_HALF) : 0; /* 0.5 is for rounding */
3267 #endif
3268                                         rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3269                                         if(rice_parameter >= rice_parameter_limit) {
3270 #ifdef DEBUG_VERBOSE
3271                                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
3272 #endif
3273                                                 rice_parameter = rice_parameter_limit - 1;
3274                                         }
3275                                         _candidate_bits =
3276                                                 evaluate_fixed_subframe_(
3277                                                         encoder,
3278                                                         integer_signal,
3279                                                         residual[!_best_subframe],
3280                                                         encoder->private_->abs_residual_partition_sums,
3281                                                         encoder->private_->raw_bits_per_partition,
3282                                                         frame_header->blocksize,
3283                                                         subframe_bps,
3284                                                         fixed_order,
3285                                                         rice_parameter,
3286                                                         rice_parameter_limit,
3287                                                         min_partition_order,
3288                                                         max_partition_order,
3289                                                         encoder->protected_->do_escape_coding,
3290                                                         encoder->protected_->rice_parameter_search_dist,
3291                                                         subframe[!_best_subframe],
3292                                                         partitioned_rice_contents[!_best_subframe]
3293                                                 );
3294                                         if(_candidate_bits < _best_bits) {
3295                                                 _best_subframe = !_best_subframe;
3296                                                 _best_bits = _candidate_bits;
3297                                         }
3298                                 }
3299                         }
3300
3301 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3302                         /* encode lpc */
3303                         if(encoder->protected_->max_lpc_order > 0) {
3304                                 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3305                                         max_lpc_order = frame_header->blocksize-1;
3306                                 else
3307                                         max_lpc_order = encoder->protected_->max_lpc_order;
3308                                 if(max_lpc_order > 0) {
3309                                         unsigned a;
3310                                         for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3311                                                 FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3312                                                 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3313                                                 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3314                                                 if(autoc[0] != 0.0) {
3315                                                         FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3316                                                         if(encoder->protected_->do_exhaustive_model_search) {
3317                                                                 min_lpc_order = 1;
3318                                                         }
3319                                                         else {
3320                                                                 const unsigned guess_lpc_order =
3321                                                                         FLAC__lpc_compute_best_order(
3322                                                                                 lpc_error,
3323                                                                                 max_lpc_order,
3324                                                                                 frame_header->blocksize,
3325                                                                                 subframe_bps + (
3326                                                                                         encoder->protected_->do_qlp_coeff_prec_search?
3327                                                                                                 FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
3328                                                                                                 encoder->protected_->qlp_coeff_precision
3329                                                                                 )
3330                                                                         );
3331                                                                 min_lpc_order = max_lpc_order = guess_lpc_order;
3332                                                         }
3333                                                         if(max_lpc_order >= frame_header->blocksize)
3334                                                                 max_lpc_order = frame_header->blocksize - 1;
3335                                                         for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
3336                                                                 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
3337                                                                 if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
3338                                                                         continue; /* don't even try */
3339                                                                 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
3340                                                                 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3341                                                                 if(rice_parameter >= rice_parameter_limit) {
3342 #ifdef DEBUG_VERBOSE
3343                                                                         fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
3344 #endif
3345                                                                         rice_parameter = rice_parameter_limit - 1;
3346                                                                 }
3347                                                                 if(encoder->protected_->do_qlp_coeff_prec_search) {
3348                                                                         min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
3349                                                                         /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
3350                                                                         if(subframe_bps <= 17) {
3351                                                                                 max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
3352                                                                                 max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
3353                                                                         }
3354                                                                         else
3355                                                                                 max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
3356                                                                 }
3357                                                                 else {
3358                                                                         min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
3359                                                                 }
3360                                                                 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
3361                                                                         _candidate_bits =
3362                                                                                 evaluate_lpc_subframe_(
3363                                                                                         encoder,
3364                                                                                         integer_signal,
3365                                                                                         residual[!_best_subframe],
3366                                                                                         encoder->private_->abs_residual_partition_sums,
3367                                                                                         encoder->private_->raw_bits_per_partition,
3368                                                                                         encoder->private_->lp_coeff[lpc_order-1],
3369                                                                                         frame_header->blocksize,
3370                                                                                         subframe_bps,
3371                                                                                         lpc_order,
3372                                                                                         qlp_coeff_precision,
3373                                                                                         rice_parameter,
3374                                                                                         rice_parameter_limit,
3375                                                                                         min_partition_order,
3376                                                                                         max_partition_order,
3377                                                                                         encoder->protected_->do_escape_coding,
3378                                                                                         encoder->protected_->rice_parameter_search_dist,
3379                                                                                         subframe[!_best_subframe],
3380                                                                                         partitioned_rice_contents[!_best_subframe]
3381                                                                                 );
3382                                                                         if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
3383                                                                                 if(_candidate_bits < _best_bits) {
3384                                                                                         _best_subframe = !_best_subframe;
3385                                                                                         _best_bits = _candidate_bits;
3386                                                                                 }
3387                                                                         }
3388                                                                 }
3389                                                         }
3390                                                 }
3391                                         }
3392                                 }
3393                         }
3394 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3395                 }
3396         }
3397
3398         /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3399         if(_best_bits == UINT_MAX) {
3400                 FLAC__ASSERT(_best_subframe == 0);
3401                 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3402         }
3403
3404         *best_subframe = _best_subframe;
3405         *best_bits = _best_bits;
3406
3407         return true;
3408 }
3409
3410 FLAC__bool add_subframe_(
3411         FLAC__StreamEncoder *encoder,
3412         unsigned blocksize,
3413         unsigned subframe_bps,
3414         const FLAC__Subframe *subframe,
3415         FLAC__BitWriter *frame
3416 )
3417 {
3418         switch(subframe->type) {
3419                 case FLAC__SUBFRAME_TYPE_CONSTANT:
3420                         if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3421                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3422                                 return false;
3423                         }
3424                         break;
3425                 case FLAC__SUBFRAME_TYPE_FIXED:
3426                         if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3427                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3428                                 return false;
3429                         }
3430                         break;
3431                 case FLAC__SUBFRAME_TYPE_LPC:
3432                         if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3433                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3434                                 return false;
3435                         }
3436                         break;
3437                 case FLAC__SUBFRAME_TYPE_VERBATIM:
3438                         if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3439                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3440                                 return false;
3441                         }
3442                         break;
3443                 default:
3444                         FLAC__ASSERT(0);
3445         }
3446
3447         return true;
3448 }
3449
3450 #define SPOTCHECK_ESTIMATE 0
3451 #if SPOTCHECK_ESTIMATE
3452 static void spotcheck_subframe_estimate_(
3453         FLAC__StreamEncoder *encoder,
3454         unsigned blocksize,
3455         unsigned subframe_bps,
3456         const FLAC__Subframe *subframe,
3457         unsigned estimate
3458 )
3459 {
3460         FLAC__bool ret;
3461         FLAC__BitWriter *frame = FLAC__bitwriter_new();
3462         if(frame == 0) {
3463                 fprintf(stderr, "EST: can't allocate frame\n");
3464                 return;
3465         }
3466         if(!FLAC__bitwriter_init(frame)) {
3467                 fprintf(stderr, "EST: can't init frame\n");
3468                 return;
3469         }
3470         ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
3471         FLAC__ASSERT(ret);
3472         {
3473                 const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
3474                 if(estimate != actual)
3475                         fprintf(stderr, "EST: bad, frame#%u sub#%%d type=%8s est=%u, actual=%u, delta=%d\n", encoder->private_->current_frame_number, FLAC__SubframeTypeString[subframe->type], estimate, actual, (int)actual-(int)estimate);
3476         }
3477         FLAC__bitwriter_delete(frame);
3478 }
3479 #endif
3480
3481 unsigned evaluate_constant_subframe_(
3482         FLAC__StreamEncoder *encoder,
3483         const FLAC__int32 signal,
3484         unsigned blocksize,
3485         unsigned subframe_bps,
3486         FLAC__Subframe *subframe
3487 )
3488 {
3489         unsigned estimate;
3490         subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3491         subframe->data.constant.value = signal;
3492
3493         estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
3494
3495 #if SPOTCHECK_ESTIMATE
3496         spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3497 #else
3498         (void)encoder, (void)blocksize;
3499 #endif
3500
3501         return estimate;
3502 }
3503
3504 unsigned evaluate_fixed_subframe_(
3505         FLAC__StreamEncoder *encoder,
3506         const FLAC__int32 signal[],
3507         FLAC__int32 residual[],
3508         FLAC__uint64 abs_residual_partition_sums[],
3509         unsigned raw_bits_per_partition[],
3510         unsigned blocksize,
3511         unsigned subframe_bps,
3512         unsigned order,
3513         unsigned rice_parameter,
3514         unsigned rice_parameter_limit,
3515         unsigned min_partition_order,
3516         unsigned max_partition_order,
3517         FLAC__bool do_escape_coding,
3518         unsigned rice_parameter_search_dist,
3519         FLAC__Subframe *subframe,
3520         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3521 )
3522 {
3523         unsigned i, residual_bits, estimate;
3524         const unsigned residual_samples = blocksize - order;
3525
3526         FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3527
3528         subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3529
3530         subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3531         subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3532         subframe->data.fixed.residual = residual;
3533
3534         residual_bits =
3535                 find_best_partition_order_(
3536                         encoder->private_,
3537                         residual,
3538                         abs_residual_partition_sums,
3539                         raw_bits_per_partition,
3540                         residual_samples,
3541                         order,
3542                         rice_parameter,
3543                         rice_parameter_limit,
3544                         min_partition_order,
3545                         max_partition_order,
3546                         subframe_bps,
3547                         do_escape_coding,
3548                         rice_parameter_search_dist,
3549                         &subframe->data.fixed.entropy_coding_method
3550                 );
3551
3552         subframe->data.fixed.order = order;
3553         for(i = 0; i < order; i++)
3554                 subframe->data.fixed.warmup[i] = signal[i];
3555
3556         estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
3557
3558 #if SPOTCHECK_ESTIMATE
3559         spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3560 #endif
3561
3562         return estimate;
3563 }
3564
3565 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3566 unsigned evaluate_lpc_subframe_(
3567         FLAC__StreamEncoder *encoder,
3568         const FLAC__int32 signal[],
3569         FLAC__int32 residual[],
3570         FLAC__uint64 abs_residual_partition_sums[],
3571         unsigned raw_bits_per_partition[],
3572         const FLAC__real lp_coeff[],
3573         unsigned blocksize,
3574         unsigned subframe_bps,
3575         unsigned order,
3576         unsigned qlp_coeff_precision,
3577         unsigned rice_parameter,
3578         unsigned rice_parameter_limit,
3579         unsigned min_partition_order,
3580         unsigned max_partition_order,
3581         FLAC__bool do_escape_coding,
3582         unsigned rice_parameter_search_dist,
3583         FLAC__Subframe *subframe,
3584         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3585 )
3586 {
3587         FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
3588         unsigned i, residual_bits, estimate;
3589         int quantization, ret;
3590         const unsigned residual_samples = blocksize - order;
3591
3592         /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3593         if(subframe_bps <= 16) {
3594                 FLAC__ASSERT(order > 0);
3595                 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3596                 qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3597         }
3598
3599         ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3600         if(ret != 0)
3601                 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3602
3603         if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3604                 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3605                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3606                 else
3607                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3608         else
3609                 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3610
3611         subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3612
3613         subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3614         subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3615         subframe->data.lpc.residual = residual;
3616
3617         residual_bits =
3618                 find_best_partition_order_(
3619                         encoder->private_,
3620                         residual,
3621                         abs_residual_partition_sums,
3622                         raw_bits_per_partition,
3623                         residual_samples,
3624                         order,
3625                         rice_parameter,
3626                         rice_parameter_limit,
3627                         min_partition_order,
3628                         max_partition_order,
3629                         subframe_bps,
3630                         do_escape_coding,
3631                         rice_parameter_search_dist,
3632                         &subframe->data.lpc.entropy_coding_method
3633                 );
3634
3635         subframe->data.lpc.order = order;
3636         subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3637         subframe->data.lpc.quantization_level = quantization;
3638         memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3639         for(i = 0; i < order; i++)
3640                 subframe->data.lpc.warmup[i] = signal[i];
3641
3642         estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits;
3643
3644 #if SPOTCHECK_ESTIMATE
3645         spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3646 #endif
3647
3648         return estimate;
3649 }
3650 #endif
3651
3652 unsigned evaluate_verbatim_subframe_(
3653         FLAC__StreamEncoder *encoder,
3654         const FLAC__int32 signal[],
3655         unsigned blocksize,
3656         unsigned subframe_bps,
3657         FLAC__Subframe *subframe
3658 )
3659 {
3660         unsigned estimate;
3661
3662         subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3663
3664         subframe->data.verbatim.data = signal;
3665
3666         estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
3667
3668 #if SPOTCHECK_ESTIMATE
3669         spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3670 #else
3671         (void)encoder;
3672 #endif
3673
3674         return estimate;
3675 }
3676
3677 unsigned find_best_partition_order_(
3678         FLAC__StreamEncoderPrivate *private_,
3679         const FLAC__int32 residual[],
3680         FLAC__uint64 abs_residual_partition_sums[],
3681         unsigned raw_bits_per_partition[],
3682         unsigned residual_samples,
3683         unsigned predictor_order,
3684         unsigned rice_parameter,
3685         unsigned rice_parameter_limit,
3686         unsigned min_partition_order,
3687         unsigned max_partition_order,
3688         unsigned bps,
3689         FLAC__bool do_escape_coding,
3690         unsigned rice_parameter_search_dist,
3691         FLAC__EntropyCodingMethod *best_ecm
3692 )
3693 {
3694         unsigned residual_bits, best_residual_bits = 0;
3695         unsigned best_parameters_index = 0;
3696         unsigned best_partition_order = 0;
3697         const unsigned blocksize = residual_samples + predictor_order;
3698
3699         max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3700         min_partition_order = min(min_partition_order, max_partition_order);
3701
3702         precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
3703
3704         if(do_escape_coding)
3705                 precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3706
3707         {
3708                 int partition_order;
3709                 unsigned sum;
3710
3711                 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3712                         if(!
3713                                 set_partitioned_rice_(
3714 #ifdef EXACT_RICE_BITS_CALCULATION
3715                                         residual,
3716 #endif
3717                                         abs_residual_partition_sums+sum,
3718                                         raw_bits_per_partition+sum,
3719                                         residual_samples,
3720                                         predictor_order,
3721                                         rice_parameter,
3722                                         rice_parameter_limit,
3723                                         rice_parameter_search_dist,
3724                                         (unsigned)partition_order,
3725                                         do_escape_coding,
3726                                         &private_->partitioned_rice_contents_extra[!best_parameters_index],
3727                                         &residual_bits
3728                                 )
3729                         )
3730                         {
3731                                 FLAC__ASSERT(best_residual_bits != 0);
3732                                 break;
3733                         }
3734                         sum += 1u << partition_order;
3735                         if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3736                                 best_residual_bits = residual_bits;
3737                                 best_parameters_index = !best_parameters_index;
3738                                 best_partition_order = partition_order;
3739                         }
3740                 }
3741         }
3742
3743         best_ecm->data.partitioned_rice.order = best_partition_order;
3744
3745         {
3746                 /*
3747                  * We are allowed to de-const the pointer based on our special
3748                  * knowledge; it is const to the outside world.
3749                  */
3750                 FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
3751                 unsigned partition;
3752
3753                 /* save best parameters and raw_bits */
3754                 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
3755                 memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
3756                 if(do_escape_coding)
3757                         memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
3758                 /*
3759                  * Now need to check if the type should be changed to
3760                  * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
3761                  * size of the rice parameters.
3762                  */
3763                 for(partition = 0; partition < (1u<<best_partition_order); partition++) {
3764                         if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3765                                 best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
3766                                 break;
3767                         }
3768                 }
3769         }
3770
3771         return best_residual_bits;
3772 }
3773
3774 #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
3775 extern void precompute_partition_info_sums_32bit_asm_ia32_(
3776         const FLAC__int32 residual[],
3777         FLAC__uint64 abs_residual_partition_sums[],
3778         unsigned blocksize,
3779         unsigned predictor_order,
3780         unsigned min_partition_order,
3781         unsigned max_partition_order
3782 );
3783 #endif
3784
3785 void precompute_partition_info_sums_(
3786         const FLAC__int32 residual[],
3787         FLAC__uint64 abs_residual_partition_sums[],
3788         unsigned residual_samples,
3789         unsigned predictor_order,
3790         unsigned min_partition_order,
3791         unsigned max_partition_order,
3792         unsigned bps
3793 )
3794 {
3795         const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
3796         unsigned partitions = 1u << max_partition_order;
3797
3798         FLAC__ASSERT(default_partition_samples > predictor_order);
3799
3800 #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
3801         /* slightly pessimistic but still catches all common cases */
3802         /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
3803         if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
3804                 precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
3805                 return;
3806         }
3807 #endif
3808
3809         /* first do max_partition_order */
3810         {
3811                 unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
3812                 /* slightly pessimistic but still catches all common cases */
3813                 /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
3814                 if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
3815                         FLAC__uint32 abs_residual_partition_sum;
3816
3817                         for(partition = residual_sample = 0; partition < partitions; partition++) {
3818                                 end += default_partition_samples;
3819                                 abs_residual_partition_sum = 0;
3820                                 for( ; residual_sample < end; residual_sample++)
3821                                         abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3822                                 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3823                         }
3824                 }
3825                 else { /* have to pessimistically use 64 bits for accumulator */
3826                         FLAC__uint64 abs_residual_partition_sum;
3827
3828                         for(partition = residual_sample = 0; partition < partitions; partition++) {
3829                                 end += default_partition_samples;
3830                                 abs_residual_partition_sum = 0;
3831                                 for( ; residual_sample < end; residual_sample++)
3832                                         abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3833                                 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3834                         }
3835                 }
3836         }
3837
3838         /* now merge partitions for lower orders */
3839         {
3840                 unsigned from_partition = 0, to_partition = partitions;
3841                 int partition_order;
3842                 for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
3843                         unsigned i;
3844                         partitions >>= 1;
3845                         for(i = 0; i < partitions; i++) {
3846                                 abs_residual_partition_sums[to_partition++] =
3847                                         abs_residual_partition_sums[from_partition  ] +
3848                                         abs_residual_partition_sums[from_partition+1];
3849                                 from_partition += 2;
3850                         }
3851                 }
3852         }
3853 }
3854
3855 void precompute_partition_info_escapes_(
3856         const FLAC__int32 residual[],
3857         unsigned raw_bits_per_partition[],
3858         unsigned residual_samples,
3859         unsigned predictor_order,
3860         unsigned min_partition_order,
3861         unsigned max_partition_order
3862 )
3863 {
3864         int partition_order;
3865         unsigned from_partition, to_partition = 0;
3866         const unsigned blocksize = residual_samples + predictor_order;
3867
3868         /* first do max_partition_order */
3869         for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3870                 FLAC__int32 r;
3871                 FLAC__uint32 rmax;
3872                 unsigned partition, partition_sample, partition_samples, residual_sample;
3873                 const unsigned partitions = 1u << partition_order;
3874                 const unsigned default_partition_samples = blocksize >> partition_order;
3875
3876                 FLAC__ASSERT(default_partition_samples > predictor_order);
3877
3878                 for(partition = residual_sample = 0; partition < partitions; partition++) {
3879                         partition_samples = default_partition_samples;
3880                         if(partition == 0)
3881                                 partition_samples -= predictor_order;
3882                         rmax = 0;
3883                         for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
3884                                 r = residual[residual_sample++];
3885                                 /* OPT: maybe faster: rmax |= r ^ (r>>31) */
3886                                 if(r < 0)
3887                                         rmax |= ~r;
3888                                 else
3889                                         rmax |= r;
3890                         }
3891                         /* now we know all residual values are in the range [-rmax-1,rmax] */
3892                         raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
3893                 }
3894                 to_partition = partitions;
3895                 break; /*@@@ yuck, should remove the 'for' loop instead */
3896         }
3897
3898         /* now merge partitions for lower orders */
3899         for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
3900                 unsigned m;
3901                 unsigned i;
3902                 const unsigned partitions = 1u << partition_order;
3903                 for(i = 0; i < partitions; i++) {
3904                         m = raw_bits_per_partition[from_partition];
3905                         from_partition++;
3906                         raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
3907                         from_partition++;
3908                         to_partition++;
3909                 }
3910         }
3911 }
3912
3913 #ifdef EXACT_RICE_BITS_CALCULATION
3914 static FLaC__INLINE unsigned count_rice_bits_in_partition_(
3915         const unsigned rice_parameter,
3916         const unsigned partition_samples,
3917         const FLAC__int32 *residual
3918 )
3919 {
3920         unsigned i, partition_bits =
3921                 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
3922                 (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
3923         ;
3924         for(i = 0; i < partition_samples; i++)
3925                 partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
3926         return partition_bits;
3927 }
3928 #else
3929 static FLaC__INLINE unsigned count_rice_bits_in_partition_(
3930         const unsigned rice_parameter,
3931         const unsigned partition_samples,
3932         const FLAC__uint64 abs_residual_partition_sum
3933 )
3934 {
3935         return
3936                 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
3937                 (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
3938                 (
3939                         rice_parameter?
3940                                 (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
3941                                 : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
3942                 )
3943                 - (partition_samples >> 1)
3944                 /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
3945                  * The actual number of bits used is closer to the sum(for all i in the partition) of  abs(residual[i])>>(rice_parameter-1)
3946                  * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
3947                  * So the subtraction term tries to guess how many extra bits were contributed.
3948                  * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
3949                  */
3950         ;
3951 }
3952 #endif
3953
3954 FLAC__bool set_partitioned_rice_(
3955 #ifdef EXACT_RICE_BITS_CALCULATION
3956         const FLAC__int32 residual[],
3957 #endif
3958         const FLAC__uint64 abs_residual_partition_sums[],
3959         const unsigned raw_bits_per_partition[],
3960         const unsigned residual_samples,
3961         const unsigned predictor_order,
3962         const unsigned suggested_rice_parameter,
3963         const unsigned rice_parameter_limit,
3964         const unsigned rice_parameter_search_dist,
3965         const unsigned partition_order,
3966         const FLAC__bool search_for_escapes,
3967         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3968         unsigned *bits
3969 )
3970 {
3971         unsigned rice_parameter, partition_bits;
3972         unsigned best_partition_bits, best_rice_parameter = 0;
3973         unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
3974         unsigned *parameters, *raw_bits;
3975 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3976         unsigned min_rice_parameter, max_rice_parameter;
3977 #else
3978         (void)rice_parameter_search_dist;
3979 #endif
3980
3981         FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
3982         FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
3983
3984         FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
3985         parameters = partitioned_rice_contents->parameters;
3986         raw_bits = partitioned_rice_contents->raw_bits;
3987
3988         if(partition_order == 0) {
3989                 best_partition_bits = (unsigned)(-1);
3990 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3991                 if(rice_parameter_search_dist) {
3992                         if(suggested_rice_parameter < rice_parameter_search_dist)
3993                                 min_rice_parameter = 0;
3994                         else
3995                                 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
3996                         max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
3997                         if(max_rice_parameter >= rice_parameter_limit) {
3998 #ifdef DEBUG_VERBOSE
3999                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
4000 #endif
4001                                 max_rice_parameter = rice_parameter_limit - 1;
4002                         }
4003                 }
4004                 else
4005                         min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
4006
4007                 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4008 #else
4009                         rice_parameter = suggested_rice_parameter;
4010 #endif
4011 #ifdef EXACT_RICE_BITS_CALCULATION
4012                         partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
4013 #else
4014                         partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
4015 #endif
4016                         if(partition_bits < best_partition_bits) {
4017                                 best_rice_parameter = rice_parameter;
4018                                 best_partition_bits = partition_bits;
4019                         }
4020 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4021                 }
4022 #endif
4023                 if(search_for_escapes) {
4024                         partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[0] * residual_samples;
4025                         if(partition_bits <= best_partition_bits) {
4026                                 raw_bits[0] = raw_bits_per_partition[0];
4027                                 best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4028                                 best_partition_bits = partition_bits;
4029                         }
4030                         else
4031                                 raw_bits[0] = 0;
4032                 }
4033                 parameters[0] = best_rice_parameter;
4034                 bits_ += best_partition_bits;
4035         }
4036         else {
4037                 unsigned partition, residual_sample;
4038                 unsigned partition_samples;
4039                 FLAC__uint64 mean, k;
4040                 const unsigned partitions = 1u << partition_order;
4041                 for(partition = residual_sample = 0; partition < partitions; partition++) {
4042                         partition_samples = (residual_samples+predictor_order) >> partition_order;
4043                         if(partition == 0) {
4044                                 if(partition_samples <= predictor_order)
4045                                         return false;
4046                                 else
4047                                         partition_samples -= predictor_order;
4048                         }
4049                         mean = abs_residual_partition_sums[partition];
4050                         /* we are basically calculating the size in bits of the
4051                          * average residual magnitude in the partition:
4052                          *   rice_parameter = floor(log2(mean/partition_samples))
4053                          * 'mean' is not a good name for the variable, it is
4054                          * actually the sum of magnitudes of all residual values
4055                          * in the partition, so the actual mean is
4056                          * mean/partition_samples
4057                          */
4058                         for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
4059                                 ;
4060                         if(rice_parameter >= rice_parameter_limit) {
4061 #ifdef DEBUG_VERBOSE
4062                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
4063 #endif
4064                                 rice_parameter = rice_parameter_limit - 1;
4065                         }
4066
4067                         best_partition_bits = (unsigned)(-1);
4068 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4069                         if(rice_parameter_search_dist) {
4070                                 if(rice_parameter < rice_parameter_search_dist)
4071                                         min_rice_parameter = 0;
4072                                 else
4073                                         min_rice_parameter = rice_parameter - rice_parameter_search_dist;
4074                                 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
4075                                 if(max_rice_parameter >= rice_parameter_limit) {
4076 #ifdef DEBUG_VERBOSE
4077                                         fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
4078 #endif
4079                                         max_rice_parameter = rice_parameter_limit - 1;
4080                                 }
4081                         }
4082                         else
4083                                 min_rice_parameter = max_rice_parameter = rice_parameter;
4084
4085                         for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4086 #endif
4087 #ifdef EXACT_RICE_BITS_CALCULATION
4088                                 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
4089 #else
4090                                 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
4091 #endif
4092                                 if(partition_bits < best_partition_bits) {
4093                                         best_rice_parameter = rice_parameter;
4094                                         best_partition_bits = partition_bits;
4095                                 }
4096 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4097                         }
4098 #endif
4099                         if(search_for_escapes) {
4100                                 partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[partition] * partition_samples;
4101                                 if(partition_bits <= best_partition_bits) {
4102                                         raw_bits[partition] = raw_bits_per_partition[partition];
4103                                         best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4104                                         best_partition_bits = partition_bits;
4105                                 }
4106                                 else
4107                                         raw_bits[partition] = 0;
4108                         }
4109                         parameters[partition] = best_rice_parameter;
4110                         bits_ += best_partition_bits;
4111                         residual_sample += partition_samples;
4112                 }
4113         }
4114
4115         *bits = bits_;
4116         return true;
4117 }
4118
4119 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
4120 {
4121         unsigned i, shift;
4122         FLAC__int32 x = 0;
4123
4124         for(i = 0; i < samples && !(x&1); i++)
4125                 x |= signal[i];
4126
4127         if(x == 0) {
4128                 shift = 0;
4129         }
4130         else {
4131                 for(shift = 0; !(x&1); shift++)
4132                         x >>= 1;
4133         }
4134
4135         if(shift > 0) {
4136                 for(i = 0; i < samples; i++)
4137                          signal[i] >>= shift;
4138         }
4139
4140         return shift;
4141 }
4142
4143 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4144 {
4145         unsigned channel;
4146
4147         for(channel = 0; channel < channels; channel++)
4148                 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
4149
4150         fifo->tail += wide_samples;
4151
4152         FLAC__ASSERT(fifo->tail <= fifo->size);
4153 }
4154
4155 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4156 {
4157         unsigned channel;
4158         unsigned sample, wide_sample;
4159         unsigned tail = fifo->tail;
4160
4161         sample = input_offset * channels;
4162         for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
4163                 for(channel = 0; channel < channels; channel++)
4164                         fifo->data[channel][tail] = input[sample++];
4165                 tail++;
4166         }
4167         fifo->tail = tail;
4168
4169         FLAC__ASSERT(fifo->tail <= fifo->size);
4170 }
4171
4172 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4173 {
4174         FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4175         const size_t encoded_bytes = encoder->private_->verify.output.bytes;
4176         (void)decoder;
4177
4178         if(encoder->private_->verify.needs_magic_hack) {
4179                 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
4180                 *bytes = FLAC__STREAM_SYNC_LENGTH;
4181                 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
4182                 encoder->private_->verify.needs_magic_hack = false;
4183         }
4184         else {
4185                 if(encoded_bytes == 0) {
4186                         /*
4187                          * If we get here, a FIFO underflow has occurred,
4188                          * which means there is a bug somewhere.
4189                          */
4190                         FLAC__ASSERT(0);
4191                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
4192                 }
4193                 else if(encoded_bytes < *bytes)
4194                         *bytes = encoded_bytes;
4195                 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
4196                 encoder->private_->verify.output.data += *bytes;
4197                 encoder->private_->verify.output.bytes -= *bytes;
4198         }
4199
4200         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
4201 }
4202
4203 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
4204 {
4205         FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
4206         unsigned channel;
4207         const unsigned channels = frame->header.channels;
4208         const unsigned blocksize = frame->header.blocksize;
4209         const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
4210
4211         (void)decoder;
4212
4213         for(channel = 0; channel < channels; channel++) {
4214                 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
4215                         unsigned i, sample = 0;
4216                         FLAC__int32 expect = 0, got = 0;
4217
4218                         for(i = 0; i < blocksize; i++) {
4219                                 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
4220                                         sample = i;
4221                                         expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
4222                                         got = (FLAC__int32)buffer[channel][i];
4223                                         break;
4224                                 }
4225                         }
4226                         FLAC__ASSERT(i < blocksize);
4227                         FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
4228                         encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
4229                         encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
4230                         encoder->private_->verify.error_stats.channel = channel;
4231                         encoder->private_->verify.error_stats.sample = sample;
4232                         encoder->private_->verify.error_stats.expected = expect;
4233                         encoder->private_->verify.error_stats.got = got;
4234                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
4235                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
4236                 }
4237         }
4238         /* dequeue the frame from the fifo */
4239         encoder->private_->verify.input_fifo.tail -= blocksize;
4240         FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
4241         for(channel = 0; channel < channels; channel++)
4242                 memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail * sizeof(encoder->private_->verify.input_fifo.data[0][0]));
4243         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4244 }
4245
4246 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4247 {
4248         (void)decoder, (void)metadata, (void)client_data;
4249 }
4250
4251 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4252 {
4253         FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4254         (void)decoder, (void)status;
4255         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4256 }
4257
4258 FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4259 {
4260         (void)client_data;
4261
4262         *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
4263         if (*bytes == 0) {
4264                 if (feof(encoder->private_->file))
4265                         return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
4266                 else if (ferror(encoder->private_->file))
4267                         return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
4268         }
4269         return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
4270 }
4271
4272 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4273 {
4274         (void)client_data;
4275
4276         if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
4277                 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4278         else
4279                 return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4280 }
4281
4282 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4283 {
4284         off_t offset;
4285
4286         (void)client_data;
4287
4288         offset = ftello(encoder->private_->file);
4289
4290         if(offset < 0) {
4291                 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4292         }
4293         else {
4294                 *absolute_byte_offset = (FLAC__uint64)offset;
4295                 return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4296         }
4297 }
4298
4299 #ifdef FLAC__VALGRIND_TESTING
4300 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4301 {
4302         size_t ret = fwrite(ptr, size, nmemb, stream);
4303         if(!ferror(stream))
4304                 fflush(stream);
4305         return ret;
4306 }
4307 #else
4308 #define local__fwrite fwrite
4309 #endif
4310
4311 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
4312 {
4313         (void)client_data, (void)current_frame;
4314
4315         if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4316                 FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
4317 #if FLAC__HAS_OGG
4318                         /* We would like to be able to use 'samples > 0' in the
4319                          * clause here but currently because of the nature of our
4320                          * Ogg writing implementation, 'samples' is always 0 (see
4321                          * ogg_encoder_aspect.c).  The downside is extra progress
4322                          * callbacks.
4323                          */
4324                         encoder->private_->is_ogg? true :
4325 #endif
4326                         samples > 0
4327                 );
4328                 if(call_it) {
4329                         /* NOTE: We have to add +bytes, +samples, and +1 to the stats
4330                          * because at this point in the callback chain, the stats
4331                          * have not been updated.  Only after we return and control
4332                          * gets back to write_frame_() are the stats updated
4333                          */
4334                         encoder->private_->progress_callback(encoder, encoder->private_->bytes_written+bytes, encoder->private_->samples_written+samples, encoder->private_->frames_written+(samples?1:0), encoder->private_->total_frames_estimate, encoder->private_->client_data);
4335                 }
4336                 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4337         }
4338         else
4339                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4340 }
4341
4342 /*
4343  * This will forcibly set stdout to binary mode (for OSes that require it)
4344  */
4345 FILE *get_binary_stdout_(void)
4346 {
4347         /* if something breaks here it is probably due to the presence or
4348          * absence of an underscore before the identifiers 'setmode',
4349          * 'fileno', and/or 'O_BINARY'; check your system header files.
4350          */
4351 #if defined _MSC_VER || defined __MINGW32__
4352         _setmode(_fileno(stdout), _O_BINARY);
4353 #elif defined __CYGWIN__
4354         /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4355         setmode(_fileno(stdout), _O_BINARY);
4356 #elif defined __EMX__
4357         setmode(fileno(stdout), O_BINARY);
4358 #endif
4359
4360         return stdout;
4361 }