203a271fef33fc0db02749c4b538b1207417ce36
[flac.git] / src / libFLAC / stream_encoder.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000-2009  Josh Coalson
3  * Copyright (C) 2011-2014  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 #include "share/compat.h"
43 #include "FLAC/assert.h"
44 #include "FLAC/stream_decoder.h"
45 #include "protected/stream_encoder.h"
46 #include "private/bitwriter.h"
47 #include "private/bitmath.h"
48 #include "private/crc.h"
49 #include "private/cpu.h"
50 #include "private/fixed.h"
51 #include "private/format.h"
52 #include "private/lpc.h"
53 #include "private/md5.h"
54 #include "private/memory.h"
55 #include "private/macros.h"
56 #if FLAC__HAS_OGG
57 #include "private/ogg_helper.h"
58 #include "private/ogg_mapping.h"
59 #endif
60 #include "private/stream_encoder.h"
61 #include "private/stream_encoder_framing.h"
62 #include "private/window.h"
63 #include "share/alloc.h"
64 #include "share/private.h"
65
66
67 /* Exact Rice codeword length calculation is off by default.  The simple
68  * (and fast) estimation (of how many bits a residual value will be
69  * encoded with) in this encoder is very good, almost always yielding
70  * compression within 0.1% of exact calculation.
71  */
72 #undef EXACT_RICE_BITS_CALCULATION
73 /* Rice parameter searching is off by default.  The simple (and fast)
74  * parameter estimation in this encoder is very good, almost always
75  * yielding compression within 0.1% of the optimal parameters.
76  */
77 #undef ENABLE_RICE_PARAMETER_SEARCH
78
79
80 typedef struct {
81         FLAC__int32 *data[FLAC__MAX_CHANNELS];
82         unsigned size; /* of each data[] in samples */
83         unsigned tail;
84 } verify_input_fifo;
85
86 typedef struct {
87         const FLAC__byte *data;
88         unsigned capacity;
89         unsigned bytes;
90 } verify_output;
91
92 typedef enum {
93         ENCODER_IN_MAGIC = 0,
94         ENCODER_IN_METADATA = 1,
95         ENCODER_IN_AUDIO = 2
96 } EncoderStateHint;
97
98 static struct CompressionLevels {
99         FLAC__bool do_mid_side_stereo;
100         FLAC__bool loose_mid_side_stereo;
101         unsigned max_lpc_order;
102         unsigned qlp_coeff_precision;
103         FLAC__bool do_qlp_coeff_prec_search;
104         FLAC__bool do_escape_coding;
105         FLAC__bool do_exhaustive_model_search;
106         unsigned min_residual_partition_order;
107         unsigned max_residual_partition_order;
108         unsigned rice_parameter_search_dist;
109         const char *apodization;
110 } compression_levels_[] = {
111         { false, false,  0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
112         { true , true ,  0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
113         { true , false,  0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
114         { false, false,  6, 0, false, false, false, 0, 4, 0, "tukey(5e-1)" },
115         { true , true ,  8, 0, false, false, false, 0, 4, 0, "tukey(5e-1)" },
116         { true , false,  8, 0, false, false, false, 0, 5, 0, "tukey(5e-1)" },
117         { true , false,  8, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2)" },
118         { true , false, 12, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2)" },
119         { true , false, 12, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2);punchout_tukey(3)" }
120         /* here we use locale-independent 5e-1 instead of 0.5 or 0,5 */
121 };
122
123
124 /***********************************************************************
125  *
126  * Private class method prototypes
127  *
128  ***********************************************************************/
129
130 static void set_defaults_(FLAC__StreamEncoder *encoder);
131 static void free_(FLAC__StreamEncoder *encoder);
132 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
133 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
134 static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
135 static void update_metadata_(const FLAC__StreamEncoder *encoder);
136 #if FLAC__HAS_OGG
137 static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
138 #endif
139 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
140 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
141
142 static FLAC__bool process_subframe_(
143         FLAC__StreamEncoder *encoder,
144         unsigned min_partition_order,
145         unsigned max_partition_order,
146         const FLAC__FrameHeader *frame_header,
147         unsigned subframe_bps,
148         const FLAC__int32 integer_signal[],
149         FLAC__Subframe *subframe[2],
150         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
151         FLAC__int32 *residual[2],
152         unsigned *best_subframe,
153         unsigned *best_bits
154 );
155
156 static FLAC__bool add_subframe_(
157         FLAC__StreamEncoder *encoder,
158         unsigned blocksize,
159         unsigned subframe_bps,
160         const FLAC__Subframe *subframe,
161         FLAC__BitWriter *frame
162 );
163
164 static unsigned evaluate_constant_subframe_(
165         FLAC__StreamEncoder *encoder,
166         const FLAC__int32 signal,
167         unsigned blocksize,
168         unsigned subframe_bps,
169         FLAC__Subframe *subframe
170 );
171
172 static unsigned evaluate_fixed_subframe_(
173         FLAC__StreamEncoder *encoder,
174         const FLAC__int32 signal[],
175         FLAC__int32 residual[],
176         FLAC__uint64 abs_residual_partition_sums[],
177         unsigned raw_bits_per_partition[],
178         unsigned blocksize,
179         unsigned subframe_bps,
180         unsigned order,
181         unsigned rice_parameter,
182         unsigned rice_parameter_limit,
183         unsigned min_partition_order,
184         unsigned max_partition_order,
185         FLAC__bool do_escape_coding,
186         unsigned rice_parameter_search_dist,
187         FLAC__Subframe *subframe,
188         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
189 );
190
191 #ifndef FLAC__INTEGER_ONLY_LIBRARY
192 static unsigned evaluate_lpc_subframe_(
193         FLAC__StreamEncoder *encoder,
194         const FLAC__int32 signal[],
195         FLAC__int32 residual[],
196         FLAC__uint64 abs_residual_partition_sums[],
197         unsigned raw_bits_per_partition[],
198         const FLAC__real lp_coeff[],
199         unsigned blocksize,
200         unsigned subframe_bps,
201         unsigned order,
202         unsigned qlp_coeff_precision,
203         unsigned rice_parameter,
204         unsigned rice_parameter_limit,
205         unsigned min_partition_order,
206         unsigned max_partition_order,
207         FLAC__bool do_escape_coding,
208         unsigned rice_parameter_search_dist,
209         FLAC__Subframe *subframe,
210         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
211 );
212 #endif
213
214 static unsigned evaluate_verbatim_subframe_(
215         FLAC__StreamEncoder *encoder,
216         const FLAC__int32 signal[],
217         unsigned blocksize,
218         unsigned subframe_bps,
219         FLAC__Subframe *subframe
220 );
221
222 static unsigned find_best_partition_order_(
223         struct FLAC__StreamEncoderPrivate *private_,
224         const FLAC__int32 residual[],
225         FLAC__uint64 abs_residual_partition_sums[],
226         unsigned raw_bits_per_partition[],
227         unsigned residual_samples,
228         unsigned predictor_order,
229         unsigned rice_parameter,
230         unsigned rice_parameter_limit,
231         unsigned min_partition_order,
232         unsigned max_partition_order,
233         unsigned bps,
234         FLAC__bool do_escape_coding,
235         unsigned rice_parameter_search_dist,
236         FLAC__EntropyCodingMethod *best_ecm
237 );
238
239 static void precompute_partition_info_sums_(
240         const FLAC__int32 residual[],
241         FLAC__uint64 abs_residual_partition_sums[],
242         unsigned residual_samples,
243         unsigned predictor_order,
244         unsigned min_partition_order,
245         unsigned max_partition_order,
246         unsigned bps
247 );
248
249 static void precompute_partition_info_escapes_(
250         const FLAC__int32 residual[],
251         unsigned raw_bits_per_partition[],
252         unsigned residual_samples,
253         unsigned predictor_order,
254         unsigned min_partition_order,
255         unsigned max_partition_order
256 );
257
258 static FLAC__bool set_partitioned_rice_(
259 #ifdef EXACT_RICE_BITS_CALCULATION
260         const FLAC__int32 residual[],
261 #endif
262         const FLAC__uint64 abs_residual_partition_sums[],
263         const unsigned raw_bits_per_partition[],
264         const unsigned residual_samples,
265         const unsigned predictor_order,
266         const unsigned suggested_rice_parameter,
267         const unsigned rice_parameter_limit,
268         const unsigned rice_parameter_search_dist,
269         const unsigned partition_order,
270         const FLAC__bool search_for_escapes,
271         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
272         unsigned *bits
273 );
274
275 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
276
277 /* verify-related routines: */
278 static void append_to_verify_fifo_(
279         verify_input_fifo *fifo,
280         const FLAC__int32 * const input[],
281         unsigned input_offset,
282         unsigned channels,
283         unsigned wide_samples
284 );
285
286 static void append_to_verify_fifo_interleaved_(
287         verify_input_fifo *fifo,
288         const FLAC__int32 input[],
289         unsigned input_offset,
290         unsigned channels,
291         unsigned wide_samples
292 );
293
294 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
295 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
296 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
297 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
298
299 static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
300 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
301 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
302 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);
303 static FILE *get_binary_stdout_(void);
304
305
306 /***********************************************************************
307  *
308  * Private class data
309  *
310  ***********************************************************************/
311
312 typedef struct FLAC__StreamEncoderPrivate {
313         unsigned input_capacity;                          /* current size (in samples) of the signal and residual buffers */
314         FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS];  /* the integer version of the input signal */
315         FLAC__int32 *integer_signal_mid_side[2];          /* the integer version of the mid-side input signal (stereo only) */
316 #ifndef FLAC__INTEGER_ONLY_LIBRARY
317         FLAC__real *real_signal[FLAC__MAX_CHANNELS];      /* (@@@ currently unused) the floating-point version of the input signal */
318         FLAC__real *real_signal_mid_side[2];              /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
319         FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
320         FLAC__real *windowed_signal;                      /* the integer_signal[] * current window[] */
321 #endif
322         unsigned subframe_bps[FLAC__MAX_CHANNELS];        /* the effective bits per sample of the input signal (stream bps - wasted bits) */
323         unsigned subframe_bps_mid_side[2];                /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
324         FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
325         FLAC__int32 *residual_workspace_mid_side[2][2];
326         FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
327         FLAC__Subframe subframe_workspace_mid_side[2][2];
328         FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
329         FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
330         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
331         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
332         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
333         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
334         unsigned best_subframe[FLAC__MAX_CHANNELS];       /* index (0 or 1) into 2nd dimension of the above workspaces */
335         unsigned best_subframe_mid_side[2];
336         unsigned best_subframe_bits[FLAC__MAX_CHANNELS];  /* size in bits of the best subframe for each channel */
337         unsigned best_subframe_bits_mid_side[2];
338         FLAC__uint64 *abs_residual_partition_sums;        /* workspace where the sum of abs(candidate residual) for each partition is stored */
339         unsigned *raw_bits_per_partition;                 /* workspace where the sum of silog2(candidate residual) for each partition is stored */
340         FLAC__BitWriter *frame;                           /* the current frame being worked on */
341         unsigned loose_mid_side_stereo_frames;            /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
342         unsigned loose_mid_side_stereo_frame_count;       /* number of frames using the current channel assignment */
343         FLAC__ChannelAssignment last_channel_assignment;
344         FLAC__StreamMetadata streaminfo;                  /* scratchpad for STREAMINFO as it is built */
345         FLAC__StreamMetadata_SeekTable *seek_table;       /* pointer into encoder->protected_->metadata_ where the seek table is */
346         unsigned current_sample_number;
347         unsigned current_frame_number;
348         FLAC__MD5Context md5context;
349         FLAC__CPUInfo cpuinfo;
350         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);
351 #ifndef FLAC__INTEGER_ONLY_LIBRARY
352         unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
353         unsigned (*local_fixed_compute_best_predictor_wide)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
354 #else
355         unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
356         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]);
357 #endif
358 #ifndef FLAC__INTEGER_ONLY_LIBRARY
359         void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
360         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[]);
361         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[]);
362         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[]);
363 #endif
364         FLAC__bool disable_constant_subframes;
365         FLAC__bool disable_fixed_subframes;
366         FLAC__bool disable_verbatim_subframes;
367 #if FLAC__HAS_OGG
368         FLAC__bool is_ogg;
369 #endif
370         FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
371         FLAC__StreamEncoderSeekCallback seek_callback;
372         FLAC__StreamEncoderTellCallback tell_callback;
373         FLAC__StreamEncoderWriteCallback write_callback;
374         FLAC__StreamEncoderMetadataCallback metadata_callback;
375         FLAC__StreamEncoderProgressCallback progress_callback;
376         void *client_data;
377         unsigned first_seekpoint_to_check;
378         FILE *file;                            /* only used when encoding to a file */
379         FLAC__uint64 bytes_written;
380         FLAC__uint64 samples_written;
381         unsigned frames_written;
382         unsigned total_frames_estimate;
383         /* unaligned (original) pointers to allocated data */
384         FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
385         FLAC__int32 *integer_signal_mid_side_unaligned[2];
386 #ifndef FLAC__INTEGER_ONLY_LIBRARY
387         FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
388         FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
389         FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
390         FLAC__real *windowed_signal_unaligned;
391 #endif
392         FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
393         FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
394         FLAC__uint64 *abs_residual_partition_sums_unaligned;
395         unsigned *raw_bits_per_partition_unaligned;
396         /*
397          * These fields have been moved here from private function local
398          * declarations merely to save stack space during encoding.
399          */
400 #ifndef FLAC__INTEGER_ONLY_LIBRARY
401         FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
402 #endif
403         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
404         /*
405          * The data for the verify section
406          */
407         struct {
408                 FLAC__StreamDecoder *decoder;
409                 EncoderStateHint state_hint;
410                 FLAC__bool needs_magic_hack;
411                 verify_input_fifo input_fifo;
412                 verify_output output;
413                 struct {
414                         FLAC__uint64 absolute_sample;
415                         unsigned frame_number;
416                         unsigned channel;
417                         unsigned sample;
418                         FLAC__int32 expected;
419                         FLAC__int32 got;
420                 } error_stats;
421         } verify;
422         FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
423 } FLAC__StreamEncoderPrivate;
424
425 /***********************************************************************
426  *
427  * Public static class data
428  *
429  ***********************************************************************/
430
431 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
432         "FLAC__STREAM_ENCODER_OK",
433         "FLAC__STREAM_ENCODER_UNINITIALIZED",
434         "FLAC__STREAM_ENCODER_OGG_ERROR",
435         "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
436         "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
437         "FLAC__STREAM_ENCODER_CLIENT_ERROR",
438         "FLAC__STREAM_ENCODER_IO_ERROR",
439         "FLAC__STREAM_ENCODER_FRAMING_ERROR",
440         "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
441 };
442
443 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
444         "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
445         "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
446         "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
447         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
448         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
449         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
450         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
451         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
452         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
453         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
454         "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
455         "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
456         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
457         "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
458 };
459
460 FLAC_API const char * const FLAC__StreamEncoderReadStatusString[] = {
461         "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
462         "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
463         "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
464         "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
465 };
466
467 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
468         "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
469         "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
470 };
471
472 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
473         "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
474         "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
475         "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
476 };
477
478 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
479         "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
480         "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
481         "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
482 };
483
484 /* Number of samples that will be overread to watch for end of stream.  By
485  * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
486  * always try to read blocksize+1 samples before encoding a block, so that
487  * even if the stream has a total sample count that is an integral multiple
488  * of the blocksize, we will still notice when we are encoding the last
489  * block.  This is needed, for example, to correctly set the end-of-stream
490  * marker in Ogg FLAC.
491  *
492  * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
493  * not really any reason to change it.
494  */
495 static const unsigned OVERREAD_ = 1;
496
497 /***********************************************************************
498  *
499  * Class constructor/destructor
500  *
501  */
502 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
503 {
504         FLAC__StreamEncoder *encoder;
505         unsigned i;
506
507         FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
508
509         encoder = calloc(1, sizeof(FLAC__StreamEncoder));
510         if(encoder == 0) {
511                 return 0;
512         }
513
514         encoder->protected_ = calloc(1, sizeof(FLAC__StreamEncoderProtected));
515         if(encoder->protected_ == 0) {
516                 free(encoder);
517                 return 0;
518         }
519
520         encoder->private_ = calloc(1, sizeof(FLAC__StreamEncoderPrivate));
521         if(encoder->private_ == 0) {
522                 free(encoder->protected_);
523                 free(encoder);
524                 return 0;
525         }
526
527         encoder->private_->frame = FLAC__bitwriter_new();
528         if(encoder->private_->frame == 0) {
529                 free(encoder->private_);
530                 free(encoder->protected_);
531                 free(encoder);
532                 return 0;
533         }
534
535         encoder->private_->file = 0;
536
537         set_defaults_(encoder);
538
539         encoder->private_->is_being_deleted = false;
540
541         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
542                 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
543                 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
544         }
545         for(i = 0; i < 2; i++) {
546                 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
547                 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
548         }
549         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
550                 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
551                 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
552         }
553         for(i = 0; i < 2; i++) {
554                 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
555                 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
556         }
557
558         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
559                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
560                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
561         }
562         for(i = 0; i < 2; i++) {
563                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
564                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
565         }
566         for(i = 0; i < 2; i++)
567                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
568
569         encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
570
571         return encoder;
572 }
573
574 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
575 {
576         unsigned i;
577
578         if (encoder == NULL)
579                 return ;
580
581         FLAC__ASSERT(0 != encoder->protected_);
582         FLAC__ASSERT(0 != encoder->private_);
583         FLAC__ASSERT(0 != encoder->private_->frame);
584
585         encoder->private_->is_being_deleted = true;
586
587         (void)FLAC__stream_encoder_finish(encoder);
588
589         if(0 != encoder->private_->verify.decoder)
590                 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
591
592         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
593                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
594                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
595         }
596         for(i = 0; i < 2; i++) {
597                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
598                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
599         }
600         for(i = 0; i < 2; i++)
601                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
602
603         FLAC__bitwriter_delete(encoder->private_->frame);
604         free(encoder->private_);
605         free(encoder->protected_);
606         free(encoder);
607 }
608
609 /***********************************************************************
610  *
611  * Public class methods
612  *
613  ***********************************************************************/
614
615 static FLAC__StreamEncoderInitStatus init_stream_internal_(
616         FLAC__StreamEncoder *encoder,
617         FLAC__StreamEncoderReadCallback read_callback,
618         FLAC__StreamEncoderWriteCallback write_callback,
619         FLAC__StreamEncoderSeekCallback seek_callback,
620         FLAC__StreamEncoderTellCallback tell_callback,
621         FLAC__StreamEncoderMetadataCallback metadata_callback,
622         void *client_data,
623         FLAC__bool is_ogg
624 )
625 {
626         unsigned i;
627         FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
628
629         FLAC__ASSERT(0 != encoder);
630
631         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
632                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
633
634 #if !FLAC__HAS_OGG
635         if(is_ogg)
636                 return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
637 #endif
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)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__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 #   ifdef 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 #   ifdef 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 && defined 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         setvbuf(file, NULL, _IOFBF, 10*1024*1024);
1334 #endif
1335         encoder->private_->file = file;
1336
1337         encoder->private_->progress_callback = progress_callback;
1338         encoder->private_->bytes_written = 0;
1339         encoder->private_->samples_written = 0;
1340         encoder->private_->frames_written = 0;
1341
1342         init_status = init_stream_internal_(
1343                 encoder,
1344                 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1345                 file_write_callback_,
1346                 encoder->private_->file == stdout? 0 : file_seek_callback_,
1347                 encoder->private_->file == stdout? 0 : file_tell_callback_,
1348                 /*metadata_callback=*/0,
1349                 client_data,
1350                 is_ogg
1351         );
1352         if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1353                 /* the above function sets the state for us in case of an error */
1354                 return init_status;
1355         }
1356
1357         {
1358                 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1359
1360                 FLAC__ASSERT(blocksize != 0);
1361                 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1362         }
1363
1364         return init_status;
1365 }
1366
1367 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1368         FLAC__StreamEncoder *encoder,
1369         FILE *file,
1370         FLAC__StreamEncoderProgressCallback progress_callback,
1371         void *client_data
1372 )
1373 {
1374         return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1375 }
1376
1377 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1378         FLAC__StreamEncoder *encoder,
1379         FILE *file,
1380         FLAC__StreamEncoderProgressCallback progress_callback,
1381         void *client_data
1382 )
1383 {
1384         return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1385 }
1386
1387 static FLAC__StreamEncoderInitStatus init_file_internal_(
1388         FLAC__StreamEncoder *encoder,
1389         const char *filename,
1390         FLAC__StreamEncoderProgressCallback progress_callback,
1391         void *client_data,
1392         FLAC__bool is_ogg
1393 )
1394 {
1395         FILE *file;
1396
1397         FLAC__ASSERT(0 != encoder);
1398
1399         /*
1400          * To make sure that our file does not go unclosed after an error, we
1401          * have to do the same entrance checks here that are later performed
1402          * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1403          */
1404         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1405                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1406
1407         file = filename? flac_fopen(filename, "w+b") : stdout;
1408
1409         if(file == 0) {
1410                 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1411                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1412         }
1413
1414         return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1415 }
1416
1417 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1418         FLAC__StreamEncoder *encoder,
1419         const char *filename,
1420         FLAC__StreamEncoderProgressCallback progress_callback,
1421         void *client_data
1422 )
1423 {
1424         return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1425 }
1426
1427 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1428         FLAC__StreamEncoder *encoder,
1429         const char *filename,
1430         FLAC__StreamEncoderProgressCallback progress_callback,
1431         void *client_data
1432 )
1433 {
1434         return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1435 }
1436
1437 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1438 {
1439         FLAC__bool error = false;
1440
1441         FLAC__ASSERT(0 != encoder);
1442         FLAC__ASSERT(0 != encoder->private_);
1443         FLAC__ASSERT(0 != encoder->protected_);
1444
1445         if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1446                 return true;
1447
1448         if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1449                 if(encoder->private_->current_sample_number != 0) {
1450                         const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1451                         encoder->protected_->blocksize = encoder->private_->current_sample_number;
1452                         if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1453                                 error = true;
1454                 }
1455         }
1456
1457         if(encoder->protected_->do_md5)
1458                 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1459
1460         if(!encoder->private_->is_being_deleted) {
1461                 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1462                         if(encoder->private_->seek_callback) {
1463 #if FLAC__HAS_OGG
1464                                 if(encoder->private_->is_ogg)
1465                                         update_ogg_metadata_(encoder);
1466                                 else
1467 #endif
1468                                 update_metadata_(encoder);
1469
1470                                 /* check if an error occurred while updating metadata */
1471                                 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1472                                         error = true;
1473                         }
1474                         if(encoder->private_->metadata_callback)
1475                                 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1476                 }
1477
1478                 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1479                         if(!error)
1480                                 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1481                         error = true;
1482                 }
1483         }
1484
1485         if(0 != encoder->private_->file) {
1486                 if(encoder->private_->file != stdout)
1487                         fclose(encoder->private_->file);
1488                 encoder->private_->file = 0;
1489         }
1490
1491 #if FLAC__HAS_OGG
1492         if(encoder->private_->is_ogg)
1493                 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1494 #endif
1495
1496         free_(encoder);
1497         set_defaults_(encoder);
1498
1499         if(!error)
1500                 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1501
1502         return !error;
1503 }
1504
1505 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1506 {
1507         FLAC__ASSERT(0 != encoder);
1508         FLAC__ASSERT(0 != encoder->private_);
1509         FLAC__ASSERT(0 != encoder->protected_);
1510         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1511                 return false;
1512 #if FLAC__HAS_OGG
1513         /* can't check encoder->private_->is_ogg since that's not set until init time */
1514         FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1515         return true;
1516 #else
1517         (void)value;
1518         return false;
1519 #endif
1520 }
1521
1522 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1523 {
1524         FLAC__ASSERT(0 != encoder);
1525         FLAC__ASSERT(0 != encoder->private_);
1526         FLAC__ASSERT(0 != encoder->protected_);
1527         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1528                 return false;
1529 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1530         encoder->protected_->verify = value;
1531 #endif
1532         return true;
1533 }
1534
1535 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1536 {
1537         FLAC__ASSERT(0 != encoder);
1538         FLAC__ASSERT(0 != encoder->private_);
1539         FLAC__ASSERT(0 != encoder->protected_);
1540         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1541                 return false;
1542         encoder->protected_->streamable_subset = value;
1543         return true;
1544 }
1545
1546 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
1547 {
1548         FLAC__ASSERT(0 != encoder);
1549         FLAC__ASSERT(0 != encoder->private_);
1550         FLAC__ASSERT(0 != encoder->protected_);
1551         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1552                 return false;
1553         encoder->protected_->do_md5 = value;
1554         return true;
1555 }
1556
1557 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1558 {
1559         FLAC__ASSERT(0 != encoder);
1560         FLAC__ASSERT(0 != encoder->private_);
1561         FLAC__ASSERT(0 != encoder->protected_);
1562         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1563                 return false;
1564         encoder->protected_->channels = value;
1565         return true;
1566 }
1567
1568 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1569 {
1570         FLAC__ASSERT(0 != encoder);
1571         FLAC__ASSERT(0 != encoder->private_);
1572         FLAC__ASSERT(0 != encoder->protected_);
1573         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1574                 return false;
1575         encoder->protected_->bits_per_sample = value;
1576         return true;
1577 }
1578
1579 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1580 {
1581         FLAC__ASSERT(0 != encoder);
1582         FLAC__ASSERT(0 != encoder->private_);
1583         FLAC__ASSERT(0 != encoder->protected_);
1584         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1585                 return false;
1586         encoder->protected_->sample_rate = value;
1587         return true;
1588 }
1589
1590 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1591 {
1592         FLAC__bool ok = true;
1593         FLAC__ASSERT(0 != encoder);
1594         FLAC__ASSERT(0 != encoder->private_);
1595         FLAC__ASSERT(0 != encoder->protected_);
1596         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1597                 return false;
1598         if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1599                 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1600         ok &= FLAC__stream_encoder_set_do_mid_side_stereo          (encoder, compression_levels_[value].do_mid_side_stereo);
1601         ok &= FLAC__stream_encoder_set_loose_mid_side_stereo       (encoder, compression_levels_[value].loose_mid_side_stereo);
1602 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1603 #if 1
1604         ok &= FLAC__stream_encoder_set_apodization                 (encoder, compression_levels_[value].apodization);
1605 #else
1606         /* equivalent to -A tukey(0.5) */
1607         encoder->protected_->num_apodizations = 1;
1608         encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1609         encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1610 #endif
1611 #endif
1612         ok &= FLAC__stream_encoder_set_max_lpc_order               (encoder, compression_levels_[value].max_lpc_order);
1613         ok &= FLAC__stream_encoder_set_qlp_coeff_precision         (encoder, compression_levels_[value].qlp_coeff_precision);
1614         ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search    (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1615         ok &= FLAC__stream_encoder_set_do_escape_coding            (encoder, compression_levels_[value].do_escape_coding);
1616         ok &= FLAC__stream_encoder_set_do_exhaustive_model_search  (encoder, compression_levels_[value].do_exhaustive_model_search);
1617         ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1618         ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1619         ok &= FLAC__stream_encoder_set_rice_parameter_search_dist  (encoder, compression_levels_[value].rice_parameter_search_dist);
1620         return ok;
1621 }
1622
1623 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1624 {
1625         FLAC__ASSERT(0 != encoder);
1626         FLAC__ASSERT(0 != encoder->private_);
1627         FLAC__ASSERT(0 != encoder->protected_);
1628         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1629                 return false;
1630         encoder->protected_->blocksize = value;
1631         return true;
1632 }
1633
1634 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1635 {
1636         FLAC__ASSERT(0 != encoder);
1637         FLAC__ASSERT(0 != encoder->private_);
1638         FLAC__ASSERT(0 != encoder->protected_);
1639         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1640                 return false;
1641         encoder->protected_->do_mid_side_stereo = value;
1642         return true;
1643 }
1644
1645 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1646 {
1647         FLAC__ASSERT(0 != encoder);
1648         FLAC__ASSERT(0 != encoder->private_);
1649         FLAC__ASSERT(0 != encoder->protected_);
1650         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1651                 return false;
1652         encoder->protected_->loose_mid_side_stereo = value;
1653         return true;
1654 }
1655
1656 /*@@@@add to tests*/
1657 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1658 {
1659         FLAC__ASSERT(0 != encoder);
1660         FLAC__ASSERT(0 != encoder->private_);
1661         FLAC__ASSERT(0 != encoder->protected_);
1662         FLAC__ASSERT(0 != specification);
1663         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1664                 return false;
1665 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1666         (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1667 #else
1668         encoder->protected_->num_apodizations = 0;
1669         while(1) {
1670                 const char *s = strchr(specification, ';');
1671                 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1672                 if     (n==8  && 0 == strncmp("bartlett"     , specification, n))
1673                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1674                 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1675                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1676                 else if(n==8  && 0 == strncmp("blackman"     , specification, n))
1677                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1678                 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1679                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1680                 else if(n==6  && 0 == strncmp("connes"       , specification, n))
1681                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1682                 else if(n==7  && 0 == strncmp("flattop"      , specification, n))
1683                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1684                 else if(n>7   && 0 == strncmp("gauss("       , specification, 6)) {
1685                         FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1686                         if (stddev > 0.0 && stddev <= 0.5) {
1687                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1688                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1689                         }
1690                 }
1691                 else if(n==7  && 0 == strncmp("hamming"      , specification, n))
1692                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1693                 else if(n==4  && 0 == strncmp("hann"         , specification, n))
1694                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1695                 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1696                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1697                 else if(n==7  && 0 == strncmp("nuttall"      , specification, n))
1698                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1699                 else if(n==9  && 0 == strncmp("rectangle"    , specification, n))
1700                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1701                 else if(n==8  && 0 == strncmp("triangle"     , specification, n))
1702                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1703                 else if(n>7   && 0 == strncmp("tukey("       , specification, 6)) {
1704                         FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1705                         if (p >= 0.0 && p <= 1.0) {
1706                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1707                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1708                         }
1709                 }
1710                 else if(n>15   && 0 == strncmp("partial_tukey("       , specification, 14)) {
1711                         FLAC__int32 tukey_parts = (FLAC__int32)strtod(specification+14, 0);
1712                         const char *si_1 = strchr(specification, '/');
1713                         FLAC__real overlap = si_1?flac_min((FLAC__real)strtod(si_1+1, 0),0.99f):0.1f;
1714                         FLAC__real overlap_units = 1.0f/(1.0f - overlap) - 1.0f;
1715                         const char *si_2 = strchr((si_1?(si_1+1):specification), '/');
1716                         FLAC__real tukey_p = si_2?(FLAC__real)strtod(si_2+1, 0):0.2f;
1717
1718                         if (tukey_parts <= 1) {
1719                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = tukey_p;
1720                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1721                         }else if (encoder->protected_->num_apodizations + tukey_parts < 32){
1722                                 FLAC__int32 m;
1723                                 for(m = 0; m < tukey_parts; m++){
1724                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.p = tukey_p;
1725                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.start = m/(tukey_parts+overlap_units);
1726                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.end = (m+1+overlap_units)/(tukey_parts+overlap_units);
1727                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_PARTIAL_TUKEY;
1728                                 }
1729                         }
1730                 }
1731                 else if(n>16   && 0 == strncmp("punchout_tukey("       , specification, 15)) {
1732                         FLAC__int32 tukey_parts = (FLAC__int32)strtod(specification+15, 0);
1733                         const char *si_1 = strchr(specification, '/');
1734                         FLAC__real overlap = si_1?flac_min((FLAC__real)strtod(si_1+1, 0),0.99f):0.2f;
1735                         FLAC__real overlap_units = 1.0f/(1.0f - overlap) - 1.0f;
1736                         const char *si_2 = strchr((si_1?(si_1+1):specification), '/');
1737                         FLAC__real tukey_p = si_2?(FLAC__real)strtod(si_2+1, 0):0.2f;
1738
1739                         if (tukey_parts <= 1) {
1740                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = tukey_p;
1741                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1742                         }else if (encoder->protected_->num_apodizations + tukey_parts < 32){
1743                                 FLAC__int32 m;
1744                                 for(m = 0; m < tukey_parts; m++){
1745                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.p = tukey_p;
1746                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.start = m/(tukey_parts+overlap_units);
1747                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.end = (m+1+overlap_units)/(tukey_parts+overlap_units);
1748                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_PUNCHOUT_TUKEY;
1749                                 }
1750                         }
1751                 }
1752                 else if(n==5  && 0 == strncmp("welch"        , specification, n))
1753                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1754                 if (encoder->protected_->num_apodizations == 32)
1755                         break;
1756                 if (s)
1757                         specification = s+1;
1758                 else
1759                         break;
1760         }
1761         if(encoder->protected_->num_apodizations == 0) {
1762                 encoder->protected_->num_apodizations = 1;
1763                 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1764                 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1765         }
1766 #endif
1767         return true;
1768 }
1769
1770 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1771 {
1772         FLAC__ASSERT(0 != encoder);
1773         FLAC__ASSERT(0 != encoder->private_);
1774         FLAC__ASSERT(0 != encoder->protected_);
1775         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1776                 return false;
1777         encoder->protected_->max_lpc_order = value;
1778         return true;
1779 }
1780
1781 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1782 {
1783         FLAC__ASSERT(0 != encoder);
1784         FLAC__ASSERT(0 != encoder->private_);
1785         FLAC__ASSERT(0 != encoder->protected_);
1786         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1787                 return false;
1788         encoder->protected_->qlp_coeff_precision = value;
1789         return true;
1790 }
1791
1792 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1793 {
1794         FLAC__ASSERT(0 != encoder);
1795         FLAC__ASSERT(0 != encoder->private_);
1796         FLAC__ASSERT(0 != encoder->protected_);
1797         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1798                 return false;
1799         encoder->protected_->do_qlp_coeff_prec_search = value;
1800         return true;
1801 }
1802
1803 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1804 {
1805         FLAC__ASSERT(0 != encoder);
1806         FLAC__ASSERT(0 != encoder->private_);
1807         FLAC__ASSERT(0 != encoder->protected_);
1808         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1809                 return false;
1810 #if 0
1811         /*@@@ deprecated: */
1812         encoder->protected_->do_escape_coding = value;
1813 #else
1814         (void)value;
1815 #endif
1816         return true;
1817 }
1818
1819 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1820 {
1821         FLAC__ASSERT(0 != encoder);
1822         FLAC__ASSERT(0 != encoder->private_);
1823         FLAC__ASSERT(0 != encoder->protected_);
1824         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1825                 return false;
1826         encoder->protected_->do_exhaustive_model_search = value;
1827         return true;
1828 }
1829
1830 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1831 {
1832         FLAC__ASSERT(0 != encoder);
1833         FLAC__ASSERT(0 != encoder->private_);
1834         FLAC__ASSERT(0 != encoder->protected_);
1835         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1836                 return false;
1837         encoder->protected_->min_residual_partition_order = value;
1838         return true;
1839 }
1840
1841 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1842 {
1843         FLAC__ASSERT(0 != encoder);
1844         FLAC__ASSERT(0 != encoder->private_);
1845         FLAC__ASSERT(0 != encoder->protected_);
1846         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1847                 return false;
1848         encoder->protected_->max_residual_partition_order = value;
1849         return true;
1850 }
1851
1852 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1853 {
1854         FLAC__ASSERT(0 != encoder);
1855         FLAC__ASSERT(0 != encoder->private_);
1856         FLAC__ASSERT(0 != encoder->protected_);
1857         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1858                 return false;
1859 #if 0
1860         /*@@@ deprecated: */
1861         encoder->protected_->rice_parameter_search_dist = value;
1862 #else
1863         (void)value;
1864 #endif
1865         return true;
1866 }
1867
1868 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1869 {
1870         FLAC__ASSERT(0 != encoder);
1871         FLAC__ASSERT(0 != encoder->private_);
1872         FLAC__ASSERT(0 != encoder->protected_);
1873         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1874                 return false;
1875         encoder->protected_->total_samples_estimate = value;
1876         return true;
1877 }
1878
1879 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1880 {
1881         FLAC__ASSERT(0 != encoder);
1882         FLAC__ASSERT(0 != encoder->private_);
1883         FLAC__ASSERT(0 != encoder->protected_);
1884         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1885                 return false;
1886         if(0 == metadata)
1887                 num_blocks = 0;
1888         if(0 == num_blocks)
1889                 metadata = 0;
1890         /* realloc() does not do exactly what we want so... */
1891         if(encoder->protected_->metadata) {
1892                 free(encoder->protected_->metadata);
1893                 encoder->protected_->metadata = 0;
1894                 encoder->protected_->num_metadata_blocks = 0;
1895         }
1896         if(num_blocks) {
1897                 FLAC__StreamMetadata **m;
1898                 if(0 == (m = safe_malloc_mul_2op_p(sizeof(m[0]), /*times*/num_blocks)))
1899                         return false;
1900                 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1901                 encoder->protected_->metadata = m;
1902                 encoder->protected_->num_metadata_blocks = num_blocks;
1903         }
1904 #if FLAC__HAS_OGG
1905         if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1906                 return false;
1907 #endif
1908         return true;
1909 }
1910
1911 /*
1912  * These three functions are not static, but not publically exposed in
1913  * include/FLAC/ either.  They are used by the test suite.
1914  */
1915 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1916 {
1917         FLAC__ASSERT(0 != encoder);
1918         FLAC__ASSERT(0 != encoder->private_);
1919         FLAC__ASSERT(0 != encoder->protected_);
1920         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1921                 return false;
1922         encoder->private_->disable_constant_subframes = value;
1923         return true;
1924 }
1925
1926 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1927 {
1928         FLAC__ASSERT(0 != encoder);
1929         FLAC__ASSERT(0 != encoder->private_);
1930         FLAC__ASSERT(0 != encoder->protected_);
1931         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1932                 return false;
1933         encoder->private_->disable_fixed_subframes = value;
1934         return true;
1935 }
1936
1937 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1938 {
1939         FLAC__ASSERT(0 != encoder);
1940         FLAC__ASSERT(0 != encoder->private_);
1941         FLAC__ASSERT(0 != encoder->protected_);
1942         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1943                 return false;
1944         encoder->private_->disable_verbatim_subframes = value;
1945         return true;
1946 }
1947
1948 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1949 {
1950         FLAC__ASSERT(0 != encoder);
1951         FLAC__ASSERT(0 != encoder->private_);
1952         FLAC__ASSERT(0 != encoder->protected_);
1953         return encoder->protected_->state;
1954 }
1955
1956 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1957 {
1958         FLAC__ASSERT(0 != encoder);
1959         FLAC__ASSERT(0 != encoder->private_);
1960         FLAC__ASSERT(0 != encoder->protected_);
1961         if(encoder->protected_->verify)
1962                 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1963         else
1964                 return FLAC__STREAM_DECODER_UNINITIALIZED;
1965 }
1966
1967 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1968 {
1969         FLAC__ASSERT(0 != encoder);
1970         FLAC__ASSERT(0 != encoder->private_);
1971         FLAC__ASSERT(0 != encoder->protected_);
1972         if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1973                 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1974         else
1975                 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1976 }
1977
1978 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)
1979 {
1980         FLAC__ASSERT(0 != encoder);
1981         FLAC__ASSERT(0 != encoder->private_);
1982         FLAC__ASSERT(0 != encoder->protected_);
1983         if(0 != absolute_sample)
1984                 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1985         if(0 != frame_number)
1986                 *frame_number = encoder->private_->verify.error_stats.frame_number;
1987         if(0 != channel)
1988                 *channel = encoder->private_->verify.error_stats.channel;
1989         if(0 != sample)
1990                 *sample = encoder->private_->verify.error_stats.sample;
1991         if(0 != expected)
1992                 *expected = encoder->private_->verify.error_stats.expected;
1993         if(0 != got)
1994                 *got = encoder->private_->verify.error_stats.got;
1995 }
1996
1997 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1998 {
1999         FLAC__ASSERT(0 != encoder);
2000         FLAC__ASSERT(0 != encoder->private_);
2001         FLAC__ASSERT(0 != encoder->protected_);
2002         return encoder->protected_->verify;
2003 }
2004
2005 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
2006 {
2007         FLAC__ASSERT(0 != encoder);
2008         FLAC__ASSERT(0 != encoder->private_);
2009         FLAC__ASSERT(0 != encoder->protected_);
2010         return encoder->protected_->streamable_subset;
2011 }
2012
2013 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
2014 {
2015         FLAC__ASSERT(0 != encoder);
2016         FLAC__ASSERT(0 != encoder->private_);
2017         FLAC__ASSERT(0 != encoder->protected_);
2018         return encoder->protected_->do_md5;
2019 }
2020
2021 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
2022 {
2023         FLAC__ASSERT(0 != encoder);
2024         FLAC__ASSERT(0 != encoder->private_);
2025         FLAC__ASSERT(0 != encoder->protected_);
2026         return encoder->protected_->channels;
2027 }
2028
2029 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
2030 {
2031         FLAC__ASSERT(0 != encoder);
2032         FLAC__ASSERT(0 != encoder->private_);
2033         FLAC__ASSERT(0 != encoder->protected_);
2034         return encoder->protected_->bits_per_sample;
2035 }
2036
2037 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
2038 {
2039         FLAC__ASSERT(0 != encoder);
2040         FLAC__ASSERT(0 != encoder->private_);
2041         FLAC__ASSERT(0 != encoder->protected_);
2042         return encoder->protected_->sample_rate;
2043 }
2044
2045 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
2046 {
2047         FLAC__ASSERT(0 != encoder);
2048         FLAC__ASSERT(0 != encoder->private_);
2049         FLAC__ASSERT(0 != encoder->protected_);
2050         return encoder->protected_->blocksize;
2051 }
2052
2053 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
2054 {
2055         FLAC__ASSERT(0 != encoder);
2056         FLAC__ASSERT(0 != encoder->private_);
2057         FLAC__ASSERT(0 != encoder->protected_);
2058         return encoder->protected_->do_mid_side_stereo;
2059 }
2060
2061 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
2062 {
2063         FLAC__ASSERT(0 != encoder);
2064         FLAC__ASSERT(0 != encoder->private_);
2065         FLAC__ASSERT(0 != encoder->protected_);
2066         return encoder->protected_->loose_mid_side_stereo;
2067 }
2068
2069 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
2070 {
2071         FLAC__ASSERT(0 != encoder);
2072         FLAC__ASSERT(0 != encoder->private_);
2073         FLAC__ASSERT(0 != encoder->protected_);
2074         return encoder->protected_->max_lpc_order;
2075 }
2076
2077 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
2078 {
2079         FLAC__ASSERT(0 != encoder);
2080         FLAC__ASSERT(0 != encoder->private_);
2081         FLAC__ASSERT(0 != encoder->protected_);
2082         return encoder->protected_->qlp_coeff_precision;
2083 }
2084
2085 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
2086 {
2087         FLAC__ASSERT(0 != encoder);
2088         FLAC__ASSERT(0 != encoder->private_);
2089         FLAC__ASSERT(0 != encoder->protected_);
2090         return encoder->protected_->do_qlp_coeff_prec_search;
2091 }
2092
2093 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
2094 {
2095         FLAC__ASSERT(0 != encoder);
2096         FLAC__ASSERT(0 != encoder->private_);
2097         FLAC__ASSERT(0 != encoder->protected_);
2098         return encoder->protected_->do_escape_coding;
2099 }
2100
2101 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
2102 {
2103         FLAC__ASSERT(0 != encoder);
2104         FLAC__ASSERT(0 != encoder->private_);
2105         FLAC__ASSERT(0 != encoder->protected_);
2106         return encoder->protected_->do_exhaustive_model_search;
2107 }
2108
2109 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
2110 {
2111         FLAC__ASSERT(0 != encoder);
2112         FLAC__ASSERT(0 != encoder->private_);
2113         FLAC__ASSERT(0 != encoder->protected_);
2114         return encoder->protected_->min_residual_partition_order;
2115 }
2116
2117 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
2118 {
2119         FLAC__ASSERT(0 != encoder);
2120         FLAC__ASSERT(0 != encoder->private_);
2121         FLAC__ASSERT(0 != encoder->protected_);
2122         return encoder->protected_->max_residual_partition_order;
2123 }
2124
2125 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
2126 {
2127         FLAC__ASSERT(0 != encoder);
2128         FLAC__ASSERT(0 != encoder->private_);
2129         FLAC__ASSERT(0 != encoder->protected_);
2130         return encoder->protected_->rice_parameter_search_dist;
2131 }
2132
2133 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
2134 {
2135         FLAC__ASSERT(0 != encoder);
2136         FLAC__ASSERT(0 != encoder->private_);
2137         FLAC__ASSERT(0 != encoder->protected_);
2138         return encoder->protected_->total_samples_estimate;
2139 }
2140
2141 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
2142 {
2143         unsigned i, j = 0, channel;
2144         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2145
2146         FLAC__ASSERT(0 != encoder);
2147         FLAC__ASSERT(0 != encoder->private_);
2148         FLAC__ASSERT(0 != encoder->protected_);
2149         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2150
2151 //      FLAC__ASSERT(samples <= blocksize);
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                                 encoder->protected_->state = FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2162                                 return false;
2163                         }
2164                         memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
2165                 }
2166
2167                 if(encoder->protected_->do_mid_side_stereo) {
2168                         FLAC__ASSERT(channels == 2);
2169                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2170                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2171                                 encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
2172                                 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' ! */
2173                         }
2174                 }
2175                 else
2176                         j += n;
2177
2178                 encoder->private_->current_sample_number += n;
2179
2180                 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2181                 if(encoder->private_->current_sample_number > blocksize) {
2182                         FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
2183                         FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2184                         if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2185                                 return false;
2186                         /* move unprocessed overread samples to beginnings of arrays */
2187                         for(channel = 0; channel < channels; channel++)
2188                                 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2189                         if(encoder->protected_->do_mid_side_stereo) {
2190                                 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2191                                 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2192                         }
2193                         encoder->private_->current_sample_number = 1;
2194                 }
2195         } while(j < samples);
2196
2197         return true;
2198 }
2199
2200 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2201 {
2202         unsigned i, j, k, channel;
2203         FLAC__int32 x, mid, side;
2204         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2205
2206         FLAC__ASSERT(0 != encoder);
2207         FLAC__ASSERT(0 != encoder->private_);
2208         FLAC__ASSERT(0 != encoder->protected_);
2209         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2210
2211         j = k = 0;
2212         /*
2213          * we have several flavors of the same basic loop, optimized for
2214          * different conditions:
2215          */
2216         if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2217                 /*
2218                  * stereo coding: unroll channel loop
2219                  */
2220                 do {
2221                         if(encoder->protected_->verify)
2222                                 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2223
2224                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2225                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2226                                 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2227                                 x = buffer[k++];
2228                                 encoder->private_->integer_signal[1][i] = x;
2229                                 mid += x;
2230                                 side -= x;
2231                                 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2232                                 encoder->private_->integer_signal_mid_side[1][i] = side;
2233                                 encoder->private_->integer_signal_mid_side[0][i] = mid;
2234                         }
2235                         encoder->private_->current_sample_number = i;
2236                         /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2237                         if(i > blocksize) {
2238                                 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2239                                         return false;
2240                                 /* move unprocessed overread samples to beginnings of arrays */
2241                                 FLAC__ASSERT(i == blocksize+OVERREAD_);
2242                                 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2243                                 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
2244                                 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
2245                                 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2246                                 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2247                                 encoder->private_->current_sample_number = 1;
2248                         }
2249                 } while(j < samples);
2250         }
2251         else {
2252                 /*
2253                  * independent channel coding: buffer each channel in inner loop
2254                  */
2255                 do {
2256                         if(encoder->protected_->verify)
2257                                 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2258
2259                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2260                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2261                                 for(channel = 0; channel < channels; channel++)
2262                                         encoder->private_->integer_signal[channel][i] = buffer[k++];
2263                         }
2264                         encoder->private_->current_sample_number = i;
2265                         /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2266                         if(i > blocksize) {
2267                                 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2268                                         return false;
2269                                 /* move unprocessed overread samples to beginnings of arrays */
2270                                 FLAC__ASSERT(i == blocksize+OVERREAD_);
2271                                 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2272                                 for(channel = 0; channel < channels; channel++)
2273                                         encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2274                                 encoder->private_->current_sample_number = 1;
2275                         }
2276                 } while(j < samples);
2277         }
2278
2279         return true;
2280 }
2281
2282 /***********************************************************************
2283  *
2284  * Private class methods
2285  *
2286  ***********************************************************************/
2287
2288 void set_defaults_(FLAC__StreamEncoder *encoder)
2289 {
2290         FLAC__ASSERT(0 != encoder);
2291
2292 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2293         encoder->protected_->verify = true;
2294 #else
2295         encoder->protected_->verify = false;
2296 #endif
2297         encoder->protected_->streamable_subset = true;
2298         encoder->protected_->do_md5 = true;
2299         encoder->protected_->do_mid_side_stereo = false;
2300         encoder->protected_->loose_mid_side_stereo = false;
2301         encoder->protected_->channels = 2;
2302         encoder->protected_->bits_per_sample = 16;
2303         encoder->protected_->sample_rate = 44100;
2304         encoder->protected_->blocksize = 0;
2305 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2306         encoder->protected_->num_apodizations = 1;
2307         encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2308         encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2309 #endif
2310         encoder->protected_->max_lpc_order = 0;
2311         encoder->protected_->qlp_coeff_precision = 0;
2312         encoder->protected_->do_qlp_coeff_prec_search = false;
2313         encoder->protected_->do_exhaustive_model_search = false;
2314         encoder->protected_->do_escape_coding = false;
2315         encoder->protected_->min_residual_partition_order = 0;
2316         encoder->protected_->max_residual_partition_order = 0;
2317         encoder->protected_->rice_parameter_search_dist = 0;
2318         encoder->protected_->total_samples_estimate = 0;
2319         encoder->protected_->metadata = 0;
2320         encoder->protected_->num_metadata_blocks = 0;
2321
2322         encoder->private_->seek_table = 0;
2323         encoder->private_->disable_constant_subframes = false;
2324         encoder->private_->disable_fixed_subframes = false;
2325         encoder->private_->disable_verbatim_subframes = false;
2326 #if FLAC__HAS_OGG
2327         encoder->private_->is_ogg = false;
2328 #endif
2329         encoder->private_->read_callback = 0;
2330         encoder->private_->write_callback = 0;
2331         encoder->private_->seek_callback = 0;
2332         encoder->private_->tell_callback = 0;
2333         encoder->private_->metadata_callback = 0;
2334         encoder->private_->progress_callback = 0;
2335         encoder->private_->client_data = 0;
2336
2337 #if FLAC__HAS_OGG
2338         FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2339 #endif
2340
2341         FLAC__stream_encoder_set_compression_level(encoder, 5);
2342 }
2343
2344 void free_(FLAC__StreamEncoder *encoder)
2345 {
2346         unsigned i, channel;
2347
2348         FLAC__ASSERT(0 != encoder);
2349         if(encoder->protected_->metadata) {
2350                 free(encoder->protected_->metadata);
2351                 encoder->protected_->metadata = 0;
2352                 encoder->protected_->num_metadata_blocks = 0;
2353         }
2354         for(i = 0; i < encoder->protected_->channels; i++) {
2355                 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2356                         free(encoder->private_->integer_signal_unaligned[i]);
2357                         encoder->private_->integer_signal_unaligned[i] = 0;
2358                 }
2359 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2360                 if(0 != encoder->private_->real_signal_unaligned[i]) {
2361                         free(encoder->private_->real_signal_unaligned[i]);
2362                         encoder->private_->real_signal_unaligned[i] = 0;
2363                 }
2364 #endif
2365         }
2366         for(i = 0; i < 2; i++) {
2367                 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2368                         free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2369                         encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2370                 }
2371 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2372                 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2373                         free(encoder->private_->real_signal_mid_side_unaligned[i]);
2374                         encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2375                 }
2376 #endif
2377         }
2378 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2379         for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2380                 if(0 != encoder->private_->window_unaligned[i]) {
2381                         free(encoder->private_->window_unaligned[i]);
2382                         encoder->private_->window_unaligned[i] = 0;
2383                 }
2384         }
2385         if(0 != encoder->private_->windowed_signal_unaligned) {
2386                 free(encoder->private_->windowed_signal_unaligned);
2387                 encoder->private_->windowed_signal_unaligned = 0;
2388         }
2389 #endif
2390         for(channel = 0; channel < encoder->protected_->channels; channel++) {
2391                 for(i = 0; i < 2; i++) {
2392                         if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2393                                 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2394                                 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2395                         }
2396                 }
2397         }
2398         for(channel = 0; channel < 2; channel++) {
2399                 for(i = 0; i < 2; i++) {
2400                         if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2401                                 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2402                                 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2403                         }
2404                 }
2405         }
2406         if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2407                 free(encoder->private_->abs_residual_partition_sums_unaligned);
2408                 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2409         }
2410         if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2411                 free(encoder->private_->raw_bits_per_partition_unaligned);
2412                 encoder->private_->raw_bits_per_partition_unaligned = 0;
2413         }
2414         if(encoder->protected_->verify) {
2415                 for(i = 0; i < encoder->protected_->channels; i++) {
2416                         if(0 != encoder->private_->verify.input_fifo.data[i]) {
2417                                 free(encoder->private_->verify.input_fifo.data[i]);
2418                                 encoder->private_->verify.input_fifo.data[i] = 0;
2419                         }
2420                 }
2421         }
2422         FLAC__bitwriter_free(encoder->private_->frame);
2423 }
2424
2425 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2426 {
2427         FLAC__bool ok;
2428         unsigned i, channel;
2429
2430         FLAC__ASSERT(new_blocksize > 0);
2431         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2432         FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2433
2434         /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2435         if(new_blocksize <= encoder->private_->input_capacity)
2436                 return true;
2437
2438         ok = true;
2439
2440         /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx() and ..._intrin_sse2()
2441          * require that the input arrays (in our case the integer signals)
2442          * have a buffer of up to 3 zeroes in front (at negative indices) for
2443          * alignment purposes; we use 4 in front to keep the data well-aligned.
2444          */
2445
2446         for(i = 0; ok && i < encoder->protected_->channels; i++) {
2447                 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2448                 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2449                 encoder->private_->integer_signal[i] += 4;
2450 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2451 #if 0 /* @@@ currently unused */
2452                 if(encoder->protected_->max_lpc_order > 0)
2453                         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2454 #endif
2455 #endif
2456         }
2457         for(i = 0; ok && i < 2; i++) {
2458                 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]);
2459                 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2460                 encoder->private_->integer_signal_mid_side[i] += 4;
2461 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2462 #if 0 /* @@@ currently unused */
2463                 if(encoder->protected_->max_lpc_order > 0)
2464                         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]);
2465 #endif
2466 #endif
2467         }
2468 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2469         if(ok && encoder->protected_->max_lpc_order > 0) {
2470                 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2471                         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2472                 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2473         }
2474 #endif
2475         for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2476                 for(i = 0; ok && i < 2; i++) {
2477                         ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2478                 }
2479         }
2480         for(channel = 0; ok && channel < 2; channel++) {
2481                 for(i = 0; ok && i < 2; i++) {
2482                         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]);
2483                 }
2484         }
2485         /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2486         /*@@@ 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) */
2487         ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2488         if(encoder->protected_->do_escape_coding)
2489                 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2490
2491         /* now adjust the windows if the blocksize has changed */
2492 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2493         if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2494                 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2495                         switch(encoder->protected_->apodizations[i].type) {
2496                                 case FLAC__APODIZATION_BARTLETT:
2497                                         FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2498                                         break;
2499                                 case FLAC__APODIZATION_BARTLETT_HANN:
2500                                         FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2501                                         break;
2502                                 case FLAC__APODIZATION_BLACKMAN:
2503                                         FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2504                                         break;
2505                                 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2506                                         FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2507                                         break;
2508                                 case FLAC__APODIZATION_CONNES:
2509                                         FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2510                                         break;
2511                                 case FLAC__APODIZATION_FLATTOP:
2512                                         FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2513                                         break;
2514                                 case FLAC__APODIZATION_GAUSS:
2515                                         FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2516                                         break;
2517                                 case FLAC__APODIZATION_HAMMING:
2518                                         FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2519                                         break;
2520                                 case FLAC__APODIZATION_HANN:
2521                                         FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2522                                         break;
2523                                 case FLAC__APODIZATION_KAISER_BESSEL:
2524                                         FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2525                                         break;
2526                                 case FLAC__APODIZATION_NUTTALL:
2527                                         FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2528                                         break;
2529                                 case FLAC__APODIZATION_RECTANGLE:
2530                                         FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2531                                         break;
2532                                 case FLAC__APODIZATION_TRIANGLE:
2533                                         FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2534                                         break;
2535                                 case FLAC__APODIZATION_TUKEY:
2536                                         FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2537                                         break;
2538                                 case FLAC__APODIZATION_PARTIAL_TUKEY:
2539                                         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);
2540                                         break;
2541                                 case FLAC__APODIZATION_PUNCHOUT_TUKEY:
2542                                         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);
2543                                         break;
2544                                 case FLAC__APODIZATION_WELCH:
2545                                         FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2546                                         break;
2547                                 default:
2548                                         FLAC__ASSERT(0);
2549                                         /* double protection */
2550                                         FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2551                                         break;
2552                         }
2553                 }
2554         }
2555 #endif
2556
2557         if(ok)
2558                 encoder->private_->input_capacity = new_blocksize;
2559         else
2560                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2561
2562         return ok;
2563 }
2564
2565 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2566 {
2567         const FLAC__byte *buffer;
2568         size_t bytes;
2569
2570         FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2571
2572         if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2573                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2574                 return false;
2575         }
2576
2577         if(encoder->protected_->verify) {
2578                 encoder->private_->verify.output.data = buffer;
2579                 encoder->private_->verify.output.bytes = bytes;
2580                 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2581                         encoder->private_->verify.needs_magic_hack = true;
2582                 }
2583                 else {
2584                         if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2585                                 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2586                                 FLAC__bitwriter_clear(encoder->private_->frame);
2587                                 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2588                                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2589                                 return false;
2590                         }
2591                 }
2592         }
2593
2594         if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2595                 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2596                 FLAC__bitwriter_clear(encoder->private_->frame);
2597                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2598                 return false;
2599         }
2600
2601         FLAC__bitwriter_release_buffer(encoder->private_->frame);
2602         FLAC__bitwriter_clear(encoder->private_->frame);
2603
2604         if(samples > 0) {
2605                 encoder->private_->streaminfo.data.stream_info.min_framesize = flac_min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2606                 encoder->private_->streaminfo.data.stream_info.max_framesize = flac_max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2607         }
2608
2609         return true;
2610 }
2611
2612 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2613 {
2614         FLAC__StreamEncoderWriteStatus status;
2615         FLAC__uint64 output_position = 0;
2616
2617 #if FLAC__HAS_OGG == 0
2618         (void)is_last_block;
2619 #endif
2620
2621         /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2622         if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2623                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2624                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2625         }
2626
2627         /*
2628          * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2629          */
2630         if(samples == 0) {
2631                 FLAC__MetadataType type = (buffer[0] & 0x7f);
2632                 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2633                         encoder->protected_->streaminfo_offset = output_position;
2634                 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2635                         encoder->protected_->seektable_offset = output_position;
2636         }
2637
2638         /*
2639          * Mark the current seek point if hit (if audio_offset == 0 that
2640          * means we're still writing metadata and haven't hit the first
2641          * frame yet)
2642          */
2643         if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2644                 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2645                 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2646                 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2647                 FLAC__uint64 test_sample;
2648                 unsigned i;
2649                 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2650                         test_sample = encoder->private_->seek_table->points[i].sample_number;
2651                         if(test_sample > frame_last_sample) {
2652                                 break;
2653                         }
2654                         else if(test_sample >= frame_first_sample) {
2655                                 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2656                                 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2657                                 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2658                                 encoder->private_->first_seekpoint_to_check++;
2659                                 /* DO NOT: "break;" and here's why:
2660                                  * The seektable template may contain more than one target
2661                                  * sample for any given frame; we will keep looping, generating
2662                                  * duplicate seekpoints for them, and we'll clean it up later,
2663                                  * just before writing the seektable back to the metadata.
2664                                  */
2665                         }
2666                         else {
2667                                 encoder->private_->first_seekpoint_to_check++;
2668                         }
2669                 }
2670         }
2671
2672 #if FLAC__HAS_OGG
2673         if(encoder->private_->is_ogg) {
2674                 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2675                         &encoder->protected_->ogg_encoder_aspect,
2676                         buffer,
2677                         bytes,
2678                         samples,
2679                         encoder->private_->current_frame_number,
2680                         is_last_block,
2681                         (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2682                         encoder,
2683                         encoder->private_->client_data
2684                 );
2685         }
2686         else
2687 #endif
2688         status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2689
2690         if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2691                 encoder->private_->bytes_written += bytes;
2692                 encoder->private_->samples_written += samples;
2693                 /* we keep a high watermark on the number of frames written because
2694                  * when the encoder goes back to write metadata, 'current_frame'
2695                  * will drop back to 0.
2696                  */
2697                 encoder->private_->frames_written = flac_max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2698         }
2699         else
2700                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2701
2702         return status;
2703 }
2704
2705 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2706 void update_metadata_(const FLAC__StreamEncoder *encoder)
2707 {
2708         FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2709         const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2710         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2711         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2712         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2713         const unsigned bps = metadata->data.stream_info.bits_per_sample;
2714         FLAC__StreamEncoderSeekStatus seek_status;
2715
2716         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2717
2718         /* All this is based on intimate knowledge of the stream header
2719          * layout, but a change to the header format that would break this
2720          * would also break all streams encoded in the previous format.
2721          */
2722
2723         /*
2724          * Write MD5 signature
2725          */
2726         {
2727                 const unsigned md5_offset =
2728                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2729                         (
2730                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2731                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2732                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2733                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2734                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2735                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2736                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2737                                 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2738                         ) / 8;
2739
2740                 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2741                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2742                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2743                         return;
2744                 }
2745                 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2746                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2747                         return;
2748                 }
2749         }
2750
2751         /*
2752          * Write total samples
2753          */
2754         {
2755                 const unsigned total_samples_byte_offset =
2756                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2757                         (
2758                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2759                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2760                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2761                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2762                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2763                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2764                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2765                                 - 4
2766                         ) / 8;
2767
2768                 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2769                 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2770                 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2771                 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2772                 b[4] = (FLAC__byte)(samples & 0xFF);
2773                 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) {
2774                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2775                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2776                         return;
2777                 }
2778                 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2779                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2780                         return;
2781                 }
2782         }
2783
2784         /*
2785          * Write min/max framesize
2786          */
2787         {
2788                 const unsigned min_framesize_offset =
2789                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2790                         (
2791                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2792                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2793                         ) / 8;
2794
2795                 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2796                 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2797                 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2798                 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2799                 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2800                 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2801                 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) {
2802                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2803                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2804                         return;
2805                 }
2806                 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2807                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2808                         return;
2809                 }
2810         }
2811
2812         /*
2813          * Write seektable
2814          */
2815         if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2816                 unsigned i;
2817
2818                 FLAC__format_seektable_sort(encoder->private_->seek_table);
2819
2820                 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2821
2822                 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) {
2823                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2824                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2825                         return;
2826                 }
2827
2828                 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2829                         FLAC__uint64 xx;
2830                         unsigned x;
2831                         xx = encoder->private_->seek_table->points[i].sample_number;
2832                         b[7] = (FLAC__byte)xx; xx >>= 8;
2833                         b[6] = (FLAC__byte)xx; xx >>= 8;
2834                         b[5] = (FLAC__byte)xx; xx >>= 8;
2835                         b[4] = (FLAC__byte)xx; xx >>= 8;
2836                         b[3] = (FLAC__byte)xx; xx >>= 8;
2837                         b[2] = (FLAC__byte)xx; xx >>= 8;
2838                         b[1] = (FLAC__byte)xx; xx >>= 8;
2839                         b[0] = (FLAC__byte)xx; xx >>= 8;
2840                         xx = encoder->private_->seek_table->points[i].stream_offset;
2841                         b[15] = (FLAC__byte)xx; xx >>= 8;
2842                         b[14] = (FLAC__byte)xx; xx >>= 8;
2843                         b[13] = (FLAC__byte)xx; xx >>= 8;
2844                         b[12] = (FLAC__byte)xx; xx >>= 8;
2845                         b[11] = (FLAC__byte)xx; xx >>= 8;
2846                         b[10] = (FLAC__byte)xx; xx >>= 8;
2847                         b[9] = (FLAC__byte)xx; xx >>= 8;
2848                         b[8] = (FLAC__byte)xx; xx >>= 8;
2849                         x = encoder->private_->seek_table->points[i].frame_samples;
2850                         b[17] = (FLAC__byte)x; x >>= 8;
2851                         b[16] = (FLAC__byte)x; x >>= 8;
2852                         if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2853                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2854                                 return;
2855                         }
2856                 }
2857         }
2858 }
2859
2860 #if FLAC__HAS_OGG
2861 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2862 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2863 {
2864         /* the # of bytes in the 1st packet that precede the STREAMINFO */
2865         static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2866                 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2867                 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2868                 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2869                 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2870                 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2871                 FLAC__STREAM_SYNC_LENGTH
2872         ;
2873         FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2874         const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2875         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2876         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2877         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2878         ogg_page page;
2879
2880         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2881         FLAC__ASSERT(0 != encoder->private_->seek_callback);
2882
2883         /* Pre-check that client supports seeking, since we don't want the
2884          * ogg_helper code to ever have to deal with this condition.
2885          */
2886         if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2887                 return;
2888
2889         /* All this is based on intimate knowledge of the stream header
2890          * layout, but a change to the header format that would break this
2891          * would also break all streams encoded in the previous format.
2892          */
2893
2894         /**
2895          ** Write STREAMINFO stats
2896          **/
2897         simple_ogg_page__init(&page);
2898         if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2899                 simple_ogg_page__clear(&page);
2900                 return; /* state already set */
2901         }
2902
2903         /*
2904          * Write MD5 signature
2905          */
2906         {
2907                 const unsigned md5_offset =
2908                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2909                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2910                         (
2911                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2912                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2913                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2914                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2915                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2916                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2917                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2918                                 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2919                         ) / 8;
2920
2921                 if(md5_offset + 16 > (unsigned)page.body_len) {
2922                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2923                         simple_ogg_page__clear(&page);
2924                         return;
2925                 }
2926                 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2927         }
2928
2929         /*
2930          * Write total samples
2931          */
2932         {
2933                 const unsigned total_samples_byte_offset =
2934                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2935                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2936                         (
2937                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2938                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2939                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2940                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2941                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2942                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2943                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2944                                 - 4
2945                         ) / 8;
2946
2947                 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2948                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2949                         simple_ogg_page__clear(&page);
2950                         return;
2951                 }
2952                 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2953                 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2954                 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2955                 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2956                 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2957                 b[4] = (FLAC__byte)(samples & 0xFF);
2958                 memcpy(page.body + total_samples_byte_offset, b, 5);
2959         }
2960
2961         /*
2962          * Write min/max framesize
2963          */
2964         {
2965                 const unsigned min_framesize_offset =
2966                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2967                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2968                         (
2969                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2970                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2971                         ) / 8;
2972
2973                 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2974                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2975                         simple_ogg_page__clear(&page);
2976                         return;
2977                 }
2978                 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2979                 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2980                 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2981                 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2982                 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2983                 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2984                 memcpy(page.body + min_framesize_offset, b, 6);
2985         }
2986         if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2987                 simple_ogg_page__clear(&page);
2988                 return; /* state already set */
2989         }
2990         simple_ogg_page__clear(&page);
2991
2992         /*
2993          * Write seektable
2994          */
2995         if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2996                 unsigned i;
2997                 FLAC__byte *p;
2998
2999                 FLAC__format_seektable_sort(encoder->private_->seek_table);
3000
3001                 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
3002
3003                 simple_ogg_page__init(&page);
3004                 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
3005                         simple_ogg_page__clear(&page);
3006                         return; /* state already set */
3007                 }
3008
3009                 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
3010                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
3011                         simple_ogg_page__clear(&page);
3012                         return;
3013                 }
3014
3015                 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
3016                         FLAC__uint64 xx;
3017                         unsigned x;
3018                         xx = encoder->private_->seek_table->points[i].sample_number;
3019                         b[7] = (FLAC__byte)xx; xx >>= 8;
3020                         b[6] = (FLAC__byte)xx; xx >>= 8;
3021                         b[5] = (FLAC__byte)xx; xx >>= 8;
3022                         b[4] = (FLAC__byte)xx; xx >>= 8;
3023                         b[3] = (FLAC__byte)xx; xx >>= 8;
3024                         b[2] = (FLAC__byte)xx; xx >>= 8;
3025                         b[1] = (FLAC__byte)xx; xx >>= 8;
3026                         b[0] = (FLAC__byte)xx; xx >>= 8;
3027                         xx = encoder->private_->seek_table->points[i].stream_offset;
3028                         b[15] = (FLAC__byte)xx; xx >>= 8;
3029                         b[14] = (FLAC__byte)xx; xx >>= 8;
3030                         b[13] = (FLAC__byte)xx; xx >>= 8;
3031                         b[12] = (FLAC__byte)xx; xx >>= 8;
3032                         b[11] = (FLAC__byte)xx; xx >>= 8;
3033                         b[10] = (FLAC__byte)xx; xx >>= 8;
3034                         b[9] = (FLAC__byte)xx; xx >>= 8;
3035                         b[8] = (FLAC__byte)xx; xx >>= 8;
3036                         x = encoder->private_->seek_table->points[i].frame_samples;
3037                         b[17] = (FLAC__byte)x; x >>= 8;
3038                         b[16] = (FLAC__byte)x; x >>= 8;
3039                         memcpy(p, b, 18);
3040                 }
3041
3042                 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
3043                         simple_ogg_page__clear(&page);
3044                         return; /* state already set */
3045                 }
3046                 simple_ogg_page__clear(&page);
3047         }
3048 }
3049 #endif
3050
3051 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
3052 {
3053         FLAC__uint16 crc;
3054         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
3055
3056         /*
3057          * Accumulate raw signal to the MD5 signature
3058          */
3059         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)) {
3060                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3061                 return false;
3062         }
3063
3064         /*
3065          * Process the frame header and subframes into the frame bitbuffer
3066          */
3067         if(!process_subframes_(encoder, is_fractional_block)) {
3068                 /* the above function sets the state for us in case of an error */
3069                 return false;
3070         }
3071
3072         /*
3073          * Zero-pad the frame to a byte_boundary
3074          */
3075         if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
3076                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3077                 return false;
3078         }
3079
3080         /*
3081          * CRC-16 the whole thing
3082          */
3083         FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
3084         if(
3085                 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
3086                 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
3087         ) {
3088                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3089                 return false;
3090         }
3091
3092         /*
3093          * Write it
3094          */
3095         if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
3096                 /* the above function sets the state for us in case of an error */
3097                 return false;
3098         }
3099
3100         /*
3101          * Get ready for the next frame
3102          */
3103         encoder->private_->current_sample_number = 0;
3104         encoder->private_->current_frame_number++;
3105         encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
3106
3107         return true;
3108 }
3109
3110 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
3111 {
3112         FLAC__FrameHeader frame_header;
3113         unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
3114         FLAC__bool do_independent, do_mid_side;
3115
3116         /*
3117          * Calculate the min,max Rice partition orders
3118          */
3119         if(is_fractional_block) {
3120                 max_partition_order = 0;
3121         }
3122         else {
3123                 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
3124                 max_partition_order = flac_min(max_partition_order, encoder->protected_->max_residual_partition_order);
3125         }
3126         min_partition_order = flac_min(min_partition_order, max_partition_order);
3127
3128         /*
3129          * Setup the frame
3130          */
3131         frame_header.blocksize = encoder->protected_->blocksize;
3132         frame_header.sample_rate = encoder->protected_->sample_rate;
3133         frame_header.channels = encoder->protected_->channels;
3134         frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
3135         frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
3136         frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
3137         frame_header.number.frame_number = encoder->private_->current_frame_number;
3138
3139         /*
3140          * Figure out what channel assignments to try
3141          */
3142         if(encoder->protected_->do_mid_side_stereo) {
3143                 if(encoder->protected_->loose_mid_side_stereo) {
3144                         if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
3145                                 do_independent = true;
3146                                 do_mid_side = true;
3147                         }
3148                         else {
3149                                 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
3150                                 do_mid_side = !do_independent;
3151                         }
3152                 }
3153                 else {
3154                         do_independent = true;
3155                         do_mid_side = true;
3156                 }
3157         }
3158         else {
3159                 do_independent = true;
3160                 do_mid_side = false;
3161         }
3162
3163         FLAC__ASSERT(do_independent || do_mid_side);
3164
3165         /*
3166          * Check for wasted bits; set effective bps for each subframe
3167          */
3168         if(do_independent) {
3169                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3170                         unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
3171                         if (w > encoder->protected_->bits_per_sample) {
3172                                 w = encoder->protected_->bits_per_sample;
3173                         }
3174                         encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
3175                         encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
3176                 }
3177         }
3178         if(do_mid_side) {
3179                 FLAC__ASSERT(encoder->protected_->channels == 2);
3180                 for(channel = 0; channel < 2; channel++) {
3181                         unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
3182                         if (w > encoder->protected_->bits_per_sample) {
3183                                 w = encoder->protected_->bits_per_sample;
3184                         }
3185                         encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
3186                         encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
3187                 }
3188         }
3189
3190         /*
3191          * First do a normal encoding pass of each independent channel
3192          */
3193         if(do_independent) {
3194                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3195                         if(!
3196                                 process_subframe_(
3197                                         encoder,
3198                                         min_partition_order,
3199                                         max_partition_order,
3200                                         &frame_header,
3201                                         encoder->private_->subframe_bps[channel],
3202                                         encoder->private_->integer_signal[channel],
3203                                         encoder->private_->subframe_workspace_ptr[channel],
3204                                         encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3205                                         encoder->private_->residual_workspace[channel],
3206                                         encoder->private_->best_subframe+channel,
3207                                         encoder->private_->best_subframe_bits+channel
3208                                 )
3209                         )
3210                                 return false;
3211                 }
3212         }
3213
3214         /*
3215          * Now do mid and side channels if requested
3216          */
3217         if(do_mid_side) {
3218                 FLAC__ASSERT(encoder->protected_->channels == 2);
3219
3220                 for(channel = 0; channel < 2; channel++) {
3221                         if(!
3222                                 process_subframe_(
3223                                         encoder,
3224                                         min_partition_order,
3225                                         max_partition_order,
3226                                         &frame_header,
3227                                         encoder->private_->subframe_bps_mid_side[channel],
3228                                         encoder->private_->integer_signal_mid_side[channel],
3229                                         encoder->private_->subframe_workspace_ptr_mid_side[channel],
3230                                         encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3231                                         encoder->private_->residual_workspace_mid_side[channel],
3232                                         encoder->private_->best_subframe_mid_side+channel,
3233                                         encoder->private_->best_subframe_bits_mid_side+channel
3234                                 )
3235                         )
3236                                 return false;
3237                 }
3238         }
3239
3240         /*
3241          * Compose the frame bitbuffer
3242          */
3243         if(do_mid_side) {
3244                 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3245                 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3246                 FLAC__ChannelAssignment channel_assignment;
3247
3248                 FLAC__ASSERT(encoder->protected_->channels == 2);
3249
3250                 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3251                         channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3252                 }
3253                 else {
3254                         unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3255                         unsigned min_bits;
3256                         int ca;
3257
3258                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3259                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE   == 1);
3260                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE  == 2);
3261                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE    == 3);
3262                         FLAC__ASSERT(do_independent && do_mid_side);
3263
3264                         /* We have to figure out which channel assignent results in the smallest frame */
3265                         bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits         [1];
3266                         bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE  ] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits_mid_side[1];
3267                         bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits         [1] + encoder->private_->best_subframe_bits_mid_side[1];
3268                         bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE   ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3269
3270                         channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3271                         min_bits = bits[channel_assignment];
3272                         for(ca = 1; ca <= 3; ca++) {
3273                                 if(bits[ca] < min_bits) {
3274                                         min_bits = bits[ca];
3275                                         channel_assignment = (FLAC__ChannelAssignment)ca;
3276                                 }
3277                         }
3278                 }
3279
3280                 frame_header.channel_assignment = channel_assignment;
3281
3282                 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3283                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3284                         return false;
3285                 }
3286
3287                 switch(channel_assignment) {
3288                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3289                                 left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3290                                 right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
3291                                 break;
3292                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3293                                 left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3294                                 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3295                                 break;
3296                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3297                                 left_subframe  = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3298                                 right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
3299                                 break;
3300                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3301                                 left_subframe  = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3302                                 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3303                                 break;
3304                         default:
3305                                 FLAC__ASSERT(0);
3306                 }
3307
3308                 switch(channel_assignment) {
3309                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3310                                 left_bps  = encoder->private_->subframe_bps         [0];
3311                                 right_bps = encoder->private_->subframe_bps         [1];
3312                                 break;
3313                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3314                                 left_bps  = encoder->private_->subframe_bps         [0];
3315                                 right_bps = encoder->private_->subframe_bps_mid_side[1];
3316                                 break;
3317                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3318                                 left_bps  = encoder->private_->subframe_bps_mid_side[1];
3319                                 right_bps = encoder->private_->subframe_bps         [1];
3320                                 break;
3321                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3322                                 left_bps  = encoder->private_->subframe_bps_mid_side[0];
3323                                 right_bps = encoder->private_->subframe_bps_mid_side[1];
3324                                 break;
3325                         default:
3326                                 FLAC__ASSERT(0);
3327                 }
3328
3329                 /* note that encoder_add_subframe_ sets the state for us in case of an error */
3330                 if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3331                         return false;
3332                 if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3333                         return false;
3334         }
3335         else {
3336                 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3337                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3338                         return false;
3339                 }
3340
3341                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3342                         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)) {
3343                                 /* the above function sets the state for us in case of an error */
3344                                 return false;
3345                         }
3346                 }
3347         }
3348
3349         if(encoder->protected_->loose_mid_side_stereo) {
3350                 encoder->private_->loose_mid_side_stereo_frame_count++;
3351                 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3352                         encoder->private_->loose_mid_side_stereo_frame_count = 0;
3353         }
3354
3355         encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3356
3357         return true;
3358 }
3359
3360 FLAC__bool process_subframe_(
3361         FLAC__StreamEncoder *encoder,
3362         unsigned min_partition_order,
3363         unsigned max_partition_order,
3364         const FLAC__FrameHeader *frame_header,
3365         unsigned subframe_bps,
3366         const FLAC__int32 integer_signal[],
3367         FLAC__Subframe *subframe[2],
3368         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3369         FLAC__int32 *residual[2],
3370         unsigned *best_subframe,
3371         unsigned *best_bits
3372 )
3373 {
3374 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3375         FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3376 #else
3377         FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3378 #endif
3379 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3380         FLAC__double lpc_residual_bits_per_sample;
3381         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 */
3382         FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3383         unsigned min_lpc_order, max_lpc_order, lpc_order;
3384         unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3385 #endif
3386         unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3387         unsigned rice_parameter;
3388         unsigned _candidate_bits, _best_bits;
3389         unsigned _best_subframe;
3390         /* only use RICE2 partitions if stream bps > 16 */
3391         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;
3392
3393         FLAC__ASSERT(frame_header->blocksize > 0);
3394
3395         /* verbatim subframe is the baseline against which we measure other compressed subframes */
3396         _best_subframe = 0;
3397         if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3398                 _best_bits = UINT_MAX;
3399         else
3400                 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3401
3402         if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3403                 unsigned signal_is_constant = false;
3404                 if(subframe_bps + 4 + FLAC__bitmath_ilog2((frame_header->blocksize-FLAC__MAX_FIXED_ORDER)|1) <= 32)
3405                         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);
3406                 else
3407                         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);
3408                 /* check for constant subframe */
3409                 if(
3410                         !encoder->private_->disable_constant_subframes &&
3411 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3412                         fixed_residual_bits_per_sample[1] == 0.0
3413 #else
3414                         fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3415 #endif
3416                 ) {
3417                         /* the above means it's possible all samples are the same value; now double-check it: */
3418                         unsigned i;
3419                         signal_is_constant = true;
3420                         for(i = 1; i < frame_header->blocksize; i++) {
3421                                 if(integer_signal[0] != integer_signal[i]) {
3422                                         signal_is_constant = false;
3423                                         break;
3424                                 }
3425                         }
3426                 }
3427                 if(signal_is_constant) {
3428                         _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3429                         if(_candidate_bits < _best_bits) {
3430                                 _best_subframe = !_best_subframe;
3431                                 _best_bits = _candidate_bits;
3432                         }
3433                 }
3434                 else {
3435                         if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3436                                 /* encode fixed */
3437                                 if(encoder->protected_->do_exhaustive_model_search) {
3438                                         min_fixed_order = 0;
3439                                         max_fixed_order = FLAC__MAX_FIXED_ORDER;
3440                                 }
3441                                 else {
3442                                         min_fixed_order = max_fixed_order = guess_fixed_order;
3443                                 }
3444                                 if(max_fixed_order >= frame_header->blocksize)
3445                                         max_fixed_order = frame_header->blocksize - 1;
3446                                 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3447 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3448                                         if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3449                                                 continue; /* don't even try */
3450                                         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 */
3451 #else
3452                                         if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3453                                                 continue; /* don't even try */
3454                                         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 */
3455 #endif
3456                                         rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3457                                         if(rice_parameter >= rice_parameter_limit) {
3458 #ifdef DEBUG_VERBOSE
3459                                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
3460 #endif
3461                                                 rice_parameter = rice_parameter_limit - 1;
3462                                         }
3463                                         _candidate_bits =
3464                                                 evaluate_fixed_subframe_(
3465                                                         encoder,
3466                                                         integer_signal,
3467                                                         residual[!_best_subframe],
3468                                                         encoder->private_->abs_residual_partition_sums,
3469                                                         encoder->private_->raw_bits_per_partition,
3470                                                         frame_header->blocksize,
3471                                                         subframe_bps,
3472                                                         fixed_order,
3473                                                         rice_parameter,
3474                                                         rice_parameter_limit,
3475                                                         min_partition_order,
3476                                                         max_partition_order,
3477                                                         encoder->protected_->do_escape_coding,
3478                                                         encoder->protected_->rice_parameter_search_dist,
3479                                                         subframe[!_best_subframe],
3480                                                         partitioned_rice_contents[!_best_subframe]
3481                                                 );
3482                                         if(_candidate_bits < _best_bits) {
3483                                                 _best_subframe = !_best_subframe;
3484                                                 _best_bits = _candidate_bits;
3485                                         }
3486                                 }
3487                         }
3488
3489 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3490                         /* encode lpc */
3491                         if(encoder->protected_->max_lpc_order > 0) {
3492                                 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3493                                         max_lpc_order = frame_header->blocksize-1;
3494                                 else
3495                                         max_lpc_order = encoder->protected_->max_lpc_order;
3496                                 if(max_lpc_order > 0) {
3497                                         unsigned a;
3498                                         for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3499                                                 FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3500                                                 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3501                                                 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3502                                                 if(autoc[0] != 0.0) {
3503                                                         FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3504                                                         if(encoder->protected_->do_exhaustive_model_search) {
3505                                                                 min_lpc_order = 1;
3506                                                         }
3507                                                         else {
3508                                                           &