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