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