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