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