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