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