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