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