Win32: Only use large buffers when writing to disk
[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         if(GetFileType((HANDLE)_get_osfhandle(_fileno(file))) == FILE_TYPE_DISK)
1334                 setvbuf(file, NULL, _IOFBF, 10*1024*1024);
1335 #endif
1336         encoder->private_->file = file;
1337
1338         encoder->private_->progress_callback = progress_callback;
1339         encoder->private_->bytes_written = 0;
1340         encoder->private_->samples_written = 0;
1341         encoder->private_->frames_written = 0;
1342
1343         init_status = init_stream_internal_(
1344                 encoder,
1345                 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1346                 file_write_callback_,
1347                 encoder->private_->file == stdout? 0 : file_seek_callback_,
1348                 encoder->private_->file == stdout? 0 : file_tell_callback_,
1349                 /*metadata_callback=*/0,
1350                 client_data,
1351                 is_ogg
1352         );
1353         if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1354                 /* the above function sets the state for us in case of an error */
1355                 return init_status;
1356         }
1357
1358         {
1359                 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1360
1361                 FLAC__ASSERT(blocksize != 0);
1362                 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1363         }
1364
1365         return init_status;
1366 }
1367
1368 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1369         FLAC__StreamEncoder *encoder,
1370         FILE *file,
1371         FLAC__StreamEncoderProgressCallback progress_callback,
1372         void *client_data
1373 )
1374 {
1375         return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1376 }
1377
1378 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1379         FLAC__StreamEncoder *encoder,
1380         FILE *file,
1381         FLAC__StreamEncoderProgressCallback progress_callback,
1382         void *client_data
1383 )
1384 {
1385         return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1386 }
1387
1388 static FLAC__StreamEncoderInitStatus init_file_internal_(
1389         FLAC__StreamEncoder *encoder,
1390         const char *filename,
1391         FLAC__StreamEncoderProgressCallback progress_callback,
1392         void *client_data,
1393         FLAC__bool is_ogg
1394 )
1395 {
1396         FILE *file;
1397
1398         FLAC__ASSERT(0 != encoder);
1399
1400         /*
1401          * To make sure that our file does not go unclosed after an error, we
1402          * have to do the same entrance checks here that are later performed
1403          * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1404          */
1405         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1406                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1407
1408         file = filename? flac_fopen(filename, "w+b") : stdout;
1409
1410         if(file == 0) {
1411                 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1412                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1413         }
1414
1415         return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1416 }
1417
1418 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1419         FLAC__StreamEncoder *encoder,
1420         const char *filename,
1421         FLAC__StreamEncoderProgressCallback progress_callback,
1422         void *client_data
1423 )
1424 {
1425         return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1426 }
1427
1428 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1429         FLAC__StreamEncoder *encoder,
1430         const char *filename,
1431         FLAC__StreamEncoderProgressCallback progress_callback,
1432         void *client_data
1433 )
1434 {
1435         return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1436 }
1437
1438 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1439 {
1440         FLAC__bool error = false;
1441
1442         FLAC__ASSERT(0 != encoder);
1443         FLAC__ASSERT(0 != encoder->private_);
1444         FLAC__ASSERT(0 != encoder->protected_);
1445
1446         if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1447                 return true;
1448
1449         if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1450                 if(encoder->private_->current_sample_number != 0) {
1451                         const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1452                         encoder->protected_->blocksize = encoder->private_->current_sample_number;
1453                         if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1454                                 error = true;
1455                 }
1456         }
1457
1458         if(encoder->protected_->do_md5)
1459                 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1460
1461         if(!encoder->private_->is_being_deleted) {
1462                 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1463                         if(encoder->private_->seek_callback) {
1464 #if FLAC__HAS_OGG
1465                                 if(encoder->private_->is_ogg)
1466                                         update_ogg_metadata_(encoder);
1467                                 else
1468 #endif
1469                                 update_metadata_(encoder);
1470
1471                                 /* check if an error occurred while updating metadata */
1472                                 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1473                                         error = true;
1474                         }
1475                         if(encoder->private_->metadata_callback)
1476                                 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1477                 }
1478
1479                 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1480                         if(!error)
1481                                 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1482                         error = true;
1483                 }
1484         }
1485
1486         if(0 != encoder->private_->file) {
1487                 if(encoder->private_->file != stdout)
1488                         fclose(encoder->private_->file);
1489                 encoder->private_->file = 0;
1490         }
1491
1492 #if FLAC__HAS_OGG
1493         if(encoder->private_->is_ogg)
1494                 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1495 #endif
1496
1497         free_(encoder);
1498         set_defaults_(encoder);
1499
1500         if(!error)
1501                 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1502
1503         return !error;
1504 }
1505
1506 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1507 {
1508         FLAC__ASSERT(0 != encoder);
1509         FLAC__ASSERT(0 != encoder->private_);
1510         FLAC__ASSERT(0 != encoder->protected_);
1511         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1512                 return false;
1513 #if FLAC__HAS_OGG
1514         /* can't check encoder->private_->is_ogg since that's not set until init time */
1515         FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1516         return true;
1517 #else
1518         (void)value;
1519         return false;
1520 #endif
1521 }
1522
1523 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1524 {
1525         FLAC__ASSERT(0 != encoder);
1526         FLAC__ASSERT(0 != encoder->private_);
1527         FLAC__ASSERT(0 != encoder->protected_);
1528         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1529                 return false;
1530 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1531         encoder->protected_->verify = value;
1532 #endif
1533         return true;
1534 }
1535
1536 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1537 {
1538         FLAC__ASSERT(0 != encoder);
1539         FLAC__ASSERT(0 != encoder->private_);
1540         FLAC__ASSERT(0 != encoder->protected_);
1541         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1542                 return false;
1543         encoder->protected_->streamable_subset = value;
1544         return true;
1545 }
1546
1547 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
1548 {
1549         FLAC__ASSERT(0 != encoder);
1550         FLAC__ASSERT(0 != encoder->private_);
1551         FLAC__ASSERT(0 != encoder->protected_);
1552         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1553                 return false;
1554         encoder->protected_->do_md5 = value;
1555         return true;
1556 }
1557
1558 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1559 {
1560         FLAC__ASSERT(0 != encoder);
1561         FLAC__ASSERT(0 != encoder->private_);
1562         FLAC__ASSERT(0 != encoder->protected_);
1563         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1564                 return false;
1565         encoder->protected_->channels = value;
1566         return true;
1567 }
1568
1569 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1570 {
1571         FLAC__ASSERT(0 != encoder);
1572         FLAC__ASSERT(0 != encoder->private_);
1573         FLAC__ASSERT(0 != encoder->protected_);
1574         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1575                 return false;
1576         encoder->protected_->bits_per_sample = value;
1577         return true;
1578 }
1579
1580 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1581 {
1582         FLAC__ASSERT(0 != encoder);
1583         FLAC__ASSERT(0 != encoder->private_);
1584         FLAC__ASSERT(0 != encoder->protected_);
1585         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1586                 return false;
1587         encoder->protected_->sample_rate = value;
1588         return true;
1589 }
1590
1591 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1592 {
1593         FLAC__bool ok = true;
1594         FLAC__ASSERT(0 != encoder);
1595         FLAC__ASSERT(0 != encoder->private_);
1596         FLAC__ASSERT(0 != encoder->protected_);
1597         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1598                 return false;
1599         if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1600                 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1601         ok &= FLAC__stream_encoder_set_do_mid_side_stereo          (encoder, compression_levels_[value].do_mid_side_stereo);
1602         ok &= FLAC__stream_encoder_set_loose_mid_side_stereo       (encoder, compression_levels_[value].loose_mid_side_stereo);
1603 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1604 #if 1
1605         ok &= FLAC__stream_encoder_set_apodization                 (encoder, compression_levels_[value].apodization);
1606 #else
1607         /* equivalent to -A tukey(0.5) */
1608         encoder->protected_->num_apodizations = 1;
1609         encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1610         encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1611 #endif
1612 #endif
1613         ok &= FLAC__stream_encoder_set_max_lpc_order               (encoder, compression_levels_[value].max_lpc_order);
1614         ok &= FLAC__stream_encoder_set_qlp_coeff_precision         (encoder, compression_levels_[value].qlp_coeff_precision);
1615         ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search    (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1616         ok &= FLAC__stream_encoder_set_do_escape_coding            (encoder, compression_levels_[value].do_escape_coding);
1617         ok &= FLAC__stream_encoder_set_do_exhaustive_model_search  (encoder, compression_levels_[value].do_exhaustive_model_search);
1618         ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1619         ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1620         ok &= FLAC__stream_encoder_set_rice_parameter_search_dist  (encoder, compression_levels_[value].rice_parameter_search_dist);
1621         return ok;
1622 }
1623
1624 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1625 {
1626         FLAC__ASSERT(0 != encoder);
1627         FLAC__ASSERT(0 != encoder->private_);
1628         FLAC__ASSERT(0 != encoder->protected_);
1629         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1630                 return false;
1631         encoder->protected_->blocksize = value;
1632         return true;
1633 }
1634
1635 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1636 {
1637         FLAC__ASSERT(0 != encoder);
1638         FLAC__ASSERT(0 != encoder->private_);
1639         FLAC__ASSERT(0 != encoder->protected_);
1640         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1641                 return false;
1642         encoder->protected_->do_mid_side_stereo = value;
1643         return true;
1644 }
1645
1646 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1647 {
1648         FLAC__ASSERT(0 != encoder);
1649         FLAC__ASSERT(0 != encoder->private_);
1650         FLAC__ASSERT(0 != encoder->protected_);
1651         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1652                 return false;
1653         encoder->protected_->loose_mid_side_stereo = value;
1654         return true;
1655 }
1656
1657 /*@@@@add to tests*/
1658 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1659 {
1660         FLAC__ASSERT(0 != encoder);
1661         FLAC__ASSERT(0 != encoder->private_);
1662         FLAC__ASSERT(0 != encoder->protected_);
1663         FLAC__ASSERT(0 != specification);
1664         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1665                 return false;
1666 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1667         (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1668 #else
1669         encoder->protected_->num_apodizations = 0;
1670         while(1) {
1671                 const char *s = strchr(specification, ';');
1672                 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1673                 if     (n==8  && 0 == strncmp("bartlett"     , specification, n))
1674                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1675                 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1676                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1677                 else if(n==8  && 0 == strncmp("blackman"     , specification, n))
1678                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1679                 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1680                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1681                 else if(n==6  && 0 == strncmp("connes"       , specification, n))
1682                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1683                 else if(n==7  && 0 == strncmp("flattop"      , specification, n))
1684                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1685                 else if(n>7   && 0 == strncmp("gauss("       , specification, 6)) {
1686                         FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1687                         if (stddev > 0.0 && stddev <= 0.5) {
1688                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1689                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1690                         }
1691                 }
1692                 else if(n==7  && 0 == strncmp("hamming"      , specification, n))
1693                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1694                 else if(n==4  && 0 == strncmp("hann"         , specification, n))
1695                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1696                 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1697                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1698                 else if(n==7  && 0 == strncmp("nuttall"      , specification, n))
1699                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1700                 else if(n==9  && 0 == strncmp("rectangle"    , specification, n))
1701                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1702                 else if(n==8  && 0 == strncmp("triangle"     , specification, n))
1703                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1704                 else if(n>7   && 0 == strncmp("tukey("       , specification, 6)) {
1705                         FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1706                         if (p >= 0.0 && p <= 1.0) {
1707                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1708                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1709                         }
1710                 }
1711                 else if(n>15   && 0 == strncmp("partial_tukey("       , specification, 14)) {
1712                         FLAC__int32 tukey_parts = (FLAC__int32)strtod(specification+14, 0);
1713                         const char *si_1 = strchr(specification, '/');
1714                         FLAC__real overlap = si_1?flac_min((FLAC__real)strtod(si_1+1, 0),0.99f):0.1f;
1715                         FLAC__real overlap_units = 1.0f/(1.0f - overlap) - 1.0f;
1716                         const char *si_2 = strchr((si_1?(si_1+1):specification), '/');
1717                         FLAC__real tukey_p = si_2?(FLAC__real)strtod(si_2+1, 0):0.2f;
1718
1719                         if (tukey_parts <= 1) {
1720                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = tukey_p;
1721                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1722                         }else if (encoder->protected_->num_apodizations + tukey_parts < 32){
1723                                 FLAC__int32 m;
1724                                 for(m = 0; m < tukey_parts; m++){
1725                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.p = tukey_p;
1726                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.start = m/(tukey_parts+overlap_units);
1727                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.end = (m+1+overlap_units)/(tukey_parts+overlap_units);
1728                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_PARTIAL_TUKEY;
1729                                 }
1730                         }
1731                 }
1732                 else if(n>16   && 0 == strncmp("punchout_tukey("       , specification, 15)) {
1733                         FLAC__int32 tukey_parts = (FLAC__int32)strtod(specification+15, 0);
1734                         const char *si_1 = strchr(specification, '/');
1735                         FLAC__real overlap = si_1?flac_min((FLAC__real)strtod(si_1+1, 0),0.99f):0.2f;
1736                         FLAC__real overlap_units = 1.0f/(1.0f - overlap) - 1.0f;
1737                         const char *si_2 = strchr((si_1?(si_1+1):specification), '/');
1738                         FLAC__real tukey_p = si_2?(FLAC__real)strtod(si_2+1, 0):0.2f;
1739
1740                         if (tukey_parts <= 1) {
1741                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = tukey_p;
1742                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1743                         }else if (encoder->protected_->num_apodizations + tukey_parts < 32){
1744                                 FLAC__int32 m;
1745                                 for(m = 0; m < tukey_parts; m++){
1746                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.p = tukey_p;
1747                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.start = m/(tukey_parts+overlap_units);
1748                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.end = (m+1+overlap_units)/(tukey_parts+overlap_units);
1749                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_PUNCHOUT_TUKEY;
1750                                 }
1751                         }
1752                 }
1753                 else if(n==5  && 0 == strncmp("welch"        , specification, n))
1754                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1755                 if (encoder->protected_->num_apodizations == 32)
1756                         break;
1757                 if (s)
1758                         specification = s+1;
1759                 else
1760                         break;
1761         }
1762         if(encoder->protected_->num_apodizations == 0) {
1763                 encoder->protected_->num_apodizations = 1;
1764                 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1765                 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1766         }
1767 #endif
1768         return true;
1769 }
1770
1771 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1772 {
1773         FLAC__ASSERT(0 != encoder);
1774         FLAC__ASSERT(0 != encoder->private_);
1775         FLAC__ASSERT(0 != encoder->protected_);
1776         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1777                 return false;
1778         encoder->protected_->max_lpc_order = value;
1779         return true;
1780 }
1781
1782 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1783 {
1784         FLAC__ASSERT(0 != encoder);
1785         FLAC__ASSERT(0 != encoder->private_);
1786         FLAC__ASSERT(0 != encoder->protected_);
1787         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1788                 return false;
1789         encoder->protected_->qlp_coeff_precision = value;
1790         return true;
1791 }
1792
1793 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1794 {
1795         FLAC__ASSERT(0 != encoder);
1796         FLAC__ASSERT(0 != encoder->private_);
1797         FLAC__ASSERT(0 != encoder->protected_);
1798         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1799                 return false;
1800         encoder->protected_->do_qlp_coeff_prec_search = value;
1801         return true;
1802 }
1803
1804 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1805 {
1806         FLAC__ASSERT(0 != encoder);
1807         FLAC__ASSERT(0 != encoder->private_);
1808         FLAC__ASSERT(0 != encoder->protected_);
1809         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1810                 return false;
1811 #if 0
1812         /*@@@ deprecated: */
1813         encoder->protected_->do_escape_coding = value;
1814 #else
1815         (void)value;
1816 #endif
1817         return true;
1818 }
1819
1820 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1821 {
1822         FLAC__ASSERT(0 != encoder);
1823         FLAC__ASSERT(0 != encoder->private_);
1824         FLAC__ASSERT(0 != encoder->protected_);
1825         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1826                 return false;
1827         encoder->protected_->do_exhaustive_model_search = value;
1828         return true;
1829 }
1830
1831 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1832 {
1833         FLAC__ASSERT(0 != encoder);
1834         FLAC__ASSERT(0 != encoder->private_);
1835         FLAC__ASSERT(0 != encoder->protected_);
1836         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1837                 return false;
1838         encoder->protected_->min_residual_partition_order = value;
1839         return true;
1840 }
1841
1842 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1843 {
1844         FLAC__ASSERT(0 != encoder);
1845         FLAC__ASSERT(0 != encoder->private_);
1846         FLAC__ASSERT(0 != encoder->protected_);
1847         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1848                 return false;
1849         encoder->protected_->max_residual_partition_order = value;
1850         return true;
1851 }
1852
1853 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1854 {
1855         FLAC__ASSERT(0 != encoder);
1856         FLAC__ASSERT(0 != encoder->private_);
1857         FLAC__ASSERT(0 != encoder->protected_);
1858         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1859                 return false;
1860 #if 0
1861         /*@@@ deprecated: */
1862         encoder->protected_->rice_parameter_search_dist = value;
1863 #else
1864         (void)value;
1865 #endif
1866         return true;
1867 }
1868
1869 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1870 {
1871         FLAC__ASSERT(0 != encoder);
1872         FLAC__ASSERT(0 != encoder->private_);
1873         FLAC__ASSERT(0 != encoder->protected_);
1874         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1875                 return false;
1876         encoder->protected_->total_samples_estimate = value;
1877         return true;
1878 }
1879
1880 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1881 {
1882         FLAC__ASSERT(0 != encoder);
1883         FLAC__ASSERT(0 != encoder->private_);
1884         FLAC__ASSERT(0 != encoder->protected_);
1885         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1886                 return false;
1887         if(0 == metadata)
1888                 num_blocks = 0;
1889         if(0 == num_blocks)
1890                 metadata = 0;
1891         /* realloc() does not do exactly what we want so... */
1892         if(encoder->protected_->metadata) {
1893                 free(encoder->protected_->metadata);
1894                 encoder->protected_->metadata = 0;
1895                 encoder->protected_->num_metadata_blocks = 0;
1896         }
1897         if(num_blocks) {
1898                 FLAC__StreamMetadata **m;
1899                 if(0 == (m = safe_malloc_mul_2op_p(sizeof(m[0]), /*times*/num_blocks)))
1900                         return false;
1901                 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1902                 encoder->protected_->metadata = m;
1903                 encoder->protected_->num_metadata_blocks = num_blocks;
1904         }
1905 #if FLAC__HAS_OGG
1906         if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1907                 return false;
1908 #endif
1909         return true;
1910 }
1911
1912 /*
1913  * These three functions are not static, but not publically exposed in
1914  * include/FLAC/ either.  They are used by the test suite.
1915  */
1916 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1917 {
1918         FLAC__ASSERT(0 != encoder);
1919         FLAC__ASSERT(0 != encoder->private_);
1920         FLAC__ASSERT(0 != encoder->protected_);
1921         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1922                 return false;
1923         encoder->private_->disable_constant_subframes = value;
1924         return true;
1925 }
1926
1927 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1928 {
1929         FLAC__ASSERT(0 != encoder);
1930         FLAC__ASSERT(0 != encoder->private_);
1931         FLAC__ASSERT(0 != encoder->protected_);
1932         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1933                 return false;
1934         encoder->private_->disable_fixed_subframes = value;
1935         return true;
1936 }
1937
1938 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1939 {
1940         FLAC__ASSERT(0 != encoder);
1941         FLAC__ASSERT(0 != encoder->private_);
1942         FLAC__ASSERT(0 != encoder->protected_);
1943         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1944                 return false;
1945         encoder->private_->disable_verbatim_subframes = value;
1946         return true;
1947 }
1948
1949 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1950 {
1951         FLAC__ASSERT(0 != encoder);
1952         FLAC__ASSERT(0 != encoder->private_);
1953         FLAC__ASSERT(0 != encoder->protected_);
1954         return encoder->protected_->state;
1955 }
1956
1957 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1958 {
1959         FLAC__ASSERT(0 != encoder);
1960         FLAC__ASSERT(0 != encoder->private_);
1961         FLAC__ASSERT(0 != encoder->protected_);
1962         if(encoder->protected_->verify)
1963                 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1964         else
1965                 return FLAC__STREAM_DECODER_UNINITIALIZED;
1966 }
1967
1968 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1969 {
1970         FLAC__ASSERT(0 != encoder);
1971         FLAC__ASSERT(0 != encoder->private_);
1972         FLAC__ASSERT(0 != encoder->protected_);
1973         if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1974                 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1975         else
1976                 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1977 }
1978
1979 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)
1980 {
1981         FLAC__ASSERT(0 != encoder);
1982         FLAC__ASSERT(0 != encoder->private_);
1983         FLAC__ASSERT(0 != encoder->protected_);
1984         if(0 != absolute_sample)
1985                 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1986         if(0 != frame_number)
1987                 *frame_number = encoder->private_->verify.error_stats.frame_number;
1988         if(0 != channel)
1989                 *channel = encoder->private_->verify.error_stats.channel;
1990         if(0 != sample)
1991                 *sample = encoder->private_->verify.error_stats.sample;
1992         if(0 != expected)
1993                 *expected = encoder->private_->verify.error_stats.expected;
1994         if(0 != got)
1995                 *got = encoder->private_->verify.error_stats.got;
1996 }
1997
1998 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1999 {
2000         FLAC__ASSERT(0 != encoder);
2001         FLAC__ASSERT(0 != encoder->private_);
2002         FLAC__ASSERT(0 != encoder->protected_);
2003         return encoder->protected_->verify;
2004 }
2005
2006 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
2007 {
2008         FLAC__ASSERT(0 != encoder);
2009         FLAC__ASSERT(0 != encoder->private_);
2010         FLAC__ASSERT(0 != encoder->protected_);
2011         return encoder->protected_->streamable_subset;
2012 }
2013
2014 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
2015 {
2016         FLAC__ASSERT(0 != encoder);
2017         FLAC__ASSERT(0 != encoder->private_);
2018         FLAC__ASSERT(0 != encoder->protected_);
2019         return encoder->protected_->do_md5;
2020 }
2021
2022 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
2023 {
2024         FLAC__ASSERT(0 != encoder);
2025         FLAC__ASSERT(0 != encoder->private_);
2026         FLAC__ASSERT(0 != encoder->protected_);
2027         return encoder->protected_->channels;
2028 }
2029
2030 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
2031 {
2032         FLAC__ASSERT(0 != encoder);
2033         FLAC__ASSERT(0 != encoder->private_);
2034         FLAC__ASSERT(0 != encoder->protected_);
2035         return encoder->protected_->bits_per_sample;
2036 }
2037
2038 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
2039 {
2040         FLAC__ASSERT(0 != encoder);
2041         FLAC__ASSERT(0 != encoder->private_);
2042         FLAC__ASSERT(0 != encoder->protected_);
2043         return encoder->protected_->sample_rate;
2044 }
2045
2046 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
2047 {
2048         FLAC__ASSERT(0 != encoder);
2049         FLAC__ASSERT(0 != encoder->private_);
2050         FLAC__ASSERT(0 != encoder->protected_);
2051         return encoder->protected_->blocksize;
2052 }
2053
2054 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
2055 {
2056         FLAC__ASSERT(0 != encoder);
2057         FLAC__ASSERT(0 != encoder->private_);
2058         FLAC__ASSERT(0 != encoder->protected_);
2059         return encoder->protected_->do_mid_side_stereo;
2060 }
2061
2062 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
2063 {
2064         FLAC__ASSERT(0 != encoder);
2065         FLAC__ASSERT(0 != encoder->private_);
2066         FLAC__ASSERT(0 != encoder->protected_);
2067         return encoder->protected_->loose_mid_side_stereo;
2068 }
2069
2070 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
2071 {
2072         FLAC__ASSERT(0 != encoder);
2073         FLAC__ASSERT(0 != encoder->private_);
2074         FLAC__ASSERT(0 != encoder->protected_);
2075         return encoder->protected_->max_lpc_order;
2076 }
2077
2078 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
2079 {
2080         FLAC__ASSERT(0 != encoder);
2081         FLAC__ASSERT(0 != encoder->private_);
2082         FLAC__ASSERT(0 != encoder->protected_);
2083         return encoder->protected_->qlp_coeff_precision;
2084 }
2085
2086 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
2087 {
2088         FLAC__ASSERT(0 != encoder);
2089         FLAC__ASSERT(0 != encoder->private_);
2090         FLAC__ASSERT(0 != encoder->protected_);
2091         return encoder->protected_->do_qlp_coeff_prec_search;
2092 }
2093
2094 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
2095 {
2096         FLAC__ASSERT(0 != encoder);
2097         FLAC__ASSERT(0 != encoder->private_);
2098         FLAC__ASSERT(0 != encoder->protected_);
2099         return encoder->protected_->do_escape_coding;
2100 }
2101
2102 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
2103 {
2104         FLAC__ASSERT(0 != encoder);
2105         FLAC__ASSERT(0 != encoder->private_);
2106         FLAC__ASSERT(0 != encoder->protected_);
2107         return encoder->protected_->do_exhaustive_model_search;
2108 }
2109
2110 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
2111 {
2112         FLAC__ASSERT(0 != encoder);
2113         FLAC__ASSERT(0 != encoder->private_);
2114         FLAC__ASSERT(0 != encoder->protected_);
2115         return encoder->protected_->min_residual_partition_order;
2116 }
2117
2118 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
2119 {
2120         FLAC__ASSERT(0 != encoder);
2121         FLAC__ASSERT(0 != encoder->private_);
2122         FLAC__ASSERT(0 != encoder->protected_);
2123         return encoder->protected_->max_residual_partition_order;
2124 }
2125
2126 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
2127 {
2128         FLAC__ASSERT(0 != encoder);
2129         FLAC__ASSERT(0 != encoder->private_);
2130         FLAC__ASSERT(0 != encoder->protected_);
2131         return encoder->protected_->rice_parameter_search_dist;
2132 }
2133
2134 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
2135 {
2136         FLAC__ASSERT(0 != encoder);
2137         FLAC__ASSERT(0 != encoder->private_);
2138         FLAC__ASSERT(0 != encoder->protected_);
2139         return encoder->protected_->total_samples_estimate;
2140 }
2141
2142 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
2143 {
2144         unsigned i, j = 0, channel;
2145         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2146
2147         FLAC__ASSERT(0 != encoder);
2148         FLAC__ASSERT(0 != encoder->private_);
2149         FLAC__ASSERT(0 != encoder->protected_);
2150         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2151
2152 //      FLAC__ASSERT(samples <= blocksize);
2153
2154         do {
2155                 const unsigned n = flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
2156
2157                 if(encoder->protected_->verify)
2158                         append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
2159
2160                 for(channel = 0; channel < channels; channel++) {
2161                         if (buffer[channel] == NULL) {
2162                                 encoder->protected_->state = FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2163                                 return false;
2164                         }
2165                         memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
2166                 }
2167
2168                 if(encoder->protected_->do_mid_side_stereo) {
2169                         FLAC__ASSERT(channels == 2);
2170                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2171                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2172                                 encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
2173                                 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' ! */
2174                         }
2175                 }
2176                 else
2177                         j += n;
2178
2179                 encoder->private_->current_sample_number += n;
2180
2181                 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2182                 if(encoder->private_->current_sample_number > blocksize) {
2183                         FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
2184                         FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2185                         if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2186                                 return false;
2187                         /* move unprocessed overread samples to beginnings of arrays */
2188                         for(channel = 0; channel < channels; channel++)
2189                                 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2190                         if(encoder->protected_->do_mid_side_stereo) {
2191                                 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2192                                 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2193                         }
2194                         encoder->private_->current_sample_number = 1;
2195                 }
2196         } while(j < samples);
2197
2198         return true;
2199 }
2200
2201 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2202 {
2203         unsigned i, j, k, channel;
2204         FLAC__int32 x, mid, side;
2205         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2206
2207         FLAC__ASSERT(0 != encoder);
2208         FLAC__ASSERT(0 != encoder->private_);
2209         FLAC__ASSERT(0 != encoder->protected_);
2210         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2211
2212         j = k = 0;
2213         /*
2214          * we have several flavors of the same basic loop, optimized for
2215          * different conditions:
2216          */
2217         if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2218                 /*
2219                  * stereo coding: unroll channel loop
2220                  */
2221                 do {
2222                         if(encoder->protected_->verify)
2223                                 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2224
2225                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2226                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2227                                 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2228                                 x = buffer[k++];
2229                                 encoder->private_->integer_signal[1][i] = x;
2230                                 mid += x;
2231                                 side -= x;
2232                                 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2233                                 encoder->private_->integer_signal_mid_side[1][i] = side;
2234                                 encoder->private_->integer_signal_mid_side[0][i] = mid;
2235                         }
2236                         encoder->private_->current_sample_number = i;
2237                         /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2238                         if(i > blocksize) {
2239                                 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2240                                         return false;
2241                                 /* move unprocessed overread samples to beginnings of arrays */
2242                                 FLAC__ASSERT(i == blocksize+OVERREAD_);
2243                                 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2244                                 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
2245                                 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
2246                                 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2247                                 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2248                                 encoder->private_->current_sample_number = 1;
2249                         }
2250                 } while(j < samples);
2251         }
2252         else {
2253                 /*
2254                  * independent channel coding: buffer each channel in inner loop
2255                  */
2256                 do {
2257                         if(encoder->protected_->verify)
2258                                 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2259
2260                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2261                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2262                                 for(channel = 0; channel < channels; channel++)
2263                                         encoder->private_->integer_signal[channel][i] = buffer[k++];
2264                         }
2265                         encoder->private_->current_sample_number = i;
2266                         /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2267                         if(i > blocksize) {
2268                                 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2269                                         return false;
2270                                 /* move unprocessed overread samples to beginnings of arrays */
2271                                 FLAC__ASSERT(i == blocksize+OVERREAD_);
2272                                 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2273                                 for(channel = 0; channel < channels; channel++)
2274                                         encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2275                                 encoder->private_->current_sample_number = 1;
2276                         }
2277                 } while(j < samples);
2278         }
2279
2280         return true;
2281 }
2282
2283 /***********************************************************************
2284  *
2285  * Private class methods
2286  *
2287  ***********************************************************************/
2288
2289 void set_defaults_(FLAC__StreamEncoder *encoder)
2290 {
2291         FLAC__ASSERT(0 != encoder);
2292
2293 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2294         encoder->protected_->verify = true;
2295 #else
2296         encoder->protected_->verify = false;
2297 #endif
2298         encoder->protected_->streamable_subset = true;
2299         encoder->protected_->do_md5 = true;
2300         encoder->protected_->do_mid_side_stereo = false;
2301         encoder->protected_->loose_mid_side_stereo = false;
2302         encoder->protected_->channels = 2;
2303         encoder->protected_->bits_per_sample = 16;
2304         encoder->protected_->sample_rate = 44100;
2305         encoder->protected_->blocksize = 0;
2306 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2307         encoder->protected_->num_apodizations = 1;
2308         encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2309         encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2310 #endif
2311         encoder->protected_->max_lpc_order = 0;
2312         encoder->protected_->qlp_coeff_precision = 0;
2313         encoder->protected_->do_qlp_coeff_prec_search = false;
2314         encoder->protected_->do_exhaustive_model_search = false;
2315         encoder->protected_->do_escape_coding = false;
2316         encoder->protected_->min_residual_partition_order = 0;
2317         encoder->protected_->max_residual_partition_order = 0;
2318         encoder->protected_->rice_parameter_search_dist = 0;
2319         encoder->protected_->total_samples_estimate = 0;
2320         encoder->protected_->metadata = 0;
2321         encoder->protected_->num_metadata_blocks = 0;
2322
2323         encoder->private_->seek_table = 0;
2324         encoder->private_->disable_constant_subframes = false;
2325         encoder->private_->disable_fixed_subframes = false;
2326         encoder->private_->disable_verbatim_subframes = false;
2327 #if FLAC__HAS_OGG
2328         encoder->private_->is_ogg = false;
2329 #endif
2330         encoder->private_->read_callback = 0;
2331         encoder->private_->write_callback = 0;
2332         encoder->private_->seek_callback = 0;
2333         encoder->private_->tell_callback = 0;
2334         encoder->private_->metadata_callback = 0;
2335         encoder->private_->progress_callback = 0;
2336         encoder->private_->client_data = 0;
2337
2338 #if FLAC__HAS_OGG
2339         FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2340 #endif
2341
2342         FLAC__stream_encoder_set_compression_level(encoder, 5);
2343 }
2344
2345 void free_(FLAC__StreamEncoder *encoder)
2346 {
2347         unsigned i, channel;
2348
2349         FLAC__ASSERT(0 != encoder);
2350         if(encoder->protected_->metadata) {
2351                 free(encoder->protected_->metadata);
2352                 encoder->protected_->metadata = 0;
2353                 encoder->protected_->num_metadata_blocks = 0;
2354         }
2355         for(i = 0; i < encoder->protected_->channels; i++) {
2356                 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2357                         free(encoder->private_->integer_signal_unaligned[i]);
2358                         encoder->private_->integer_signal_unaligned[i] = 0;
2359                 }
2360 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2361                 if(0 != encoder->private_->real_signal_unaligned[i]) {
2362                         free(encoder->private_->real_signal_unaligned[i]);
2363                         encoder->private_->real_signal_unaligned[i] = 0;
2364                 }
2365 #endif
2366         }
2367         for(i = 0; i < 2; i++) {
2368                 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2369                         free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2370                         encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2371                 }
2372 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2373                 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2374                         free(encoder->private_->real_signal_mid_side_unaligned[i]);
2375                         encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2376                 }
2377 #endif
2378         }
2379 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2380         for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2381                 if(0 != encoder->private_->window_unaligned[i]) {
2382                         free(encoder->private_->window_unaligned[i]);
2383                         encoder->private_->window_unaligned[i] = 0;
2384                 }
2385         }
2386         if(0 != encoder->private_->windowed_signal_unaligned) {
2387                 free(encoder->private_->windowed_signal_unaligned);
2388                 encoder->private_->windowed_signal_unaligned = 0;
2389         }
2390 #endif
2391         for(channel = 0; channel < encoder->protected_->channels; channel++) {
2392                 for(i = 0; i < 2; i++) {
2393                         if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2394                                 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2395                                 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2396                         }
2397                 }
2398         }
2399         for(channel = 0; channel < 2; channel++) {
2400                 for(i = 0; i < 2; i++) {
2401                         if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2402                                 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2403                                 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2404                         }
2405                 }
2406         }
2407         if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2408                 free(encoder->private_->abs_residual_partition_sums_unaligned);
2409                 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2410         }
2411         if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2412                 free(encoder->private_->raw_bits_per_partition_unaligned);
2413                 encoder->private_->raw_bits_per_partition_unaligned = 0;
2414         }
2415         if(encoder->protected_->verify) {
2416                 for(i = 0; i < encoder->protected_->channels; i++) {
2417                         if(0 != encoder->private_->verify.input_fifo.data[i]) {
2418                                 free(encoder->private_->verify.input_fifo.data[i]);
2419                                 encoder->private_->verify.input_fifo.data[i] = 0;
2420                         }
2421                 }
2422         }
2423         FLAC__bitwriter_free(encoder->private_->frame);
2424 }
2425
2426 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2427 {
2428         FLAC__bool ok;
2429         unsigned i, channel;
2430
2431         FLAC__ASSERT(new_blocksize > 0);
2432         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2433         FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2434
2435         /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2436         if(new_blocksize <= encoder->private_->input_capacity)
2437                 return true;
2438
2439         ok = true;
2440
2441         /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx() and ..._intrin_sse2()
2442          * require that the input arrays (in our case the integer signals)
2443          * have a buffer of up to 3 zeroes in front (at negative indices) for
2444          * alignment purposes; we use 4 in front to keep the data well-aligned.
2445          */
2446
2447         for(i = 0; ok && i < encoder->protected_->channels; i++) {
2448                 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2449                 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2450                 encoder->private_->integer_signal[i] += 4;
2451 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2452 #if 0 /* @@@ currently unused */
2453                 if(encoder->protected_->max_lpc_order > 0)
2454                         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2455 #endif
2456 #endif
2457         }
2458         for(i = 0; ok && i < 2; i++) {
2459                 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]);
2460                 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2461                 encoder->private_->integer_signal_mid_side[i] += 4;
2462 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2463 #if 0 /* @@@ currently unused */
2464                 if(encoder->protected_->max_lpc_order > 0)
2465                         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]);
2466 #endif
2467 #endif
2468         }
2469 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2470         if(ok && encoder->protected_->max_lpc_order > 0) {
2471                 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2472                         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2473                 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2474         }
2475 #endif
2476         for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2477                 for(i = 0; ok && i < 2; i++) {
2478                         ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2479                 }
2480         }
2481         for(channel = 0; ok && channel < 2; channel++) {
2482                 for(i = 0; ok && i < 2; i++) {
2483                         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]);
2484                 }
2485         }
2486         /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2487         /*@@@ 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) */
2488         ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2489         if(encoder->protected_->do_escape_coding)
2490                 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2491
2492         /* now adjust the windows if the blocksize has changed */
2493 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2494         if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2495                 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2496                         switch(encoder->protected_->apodizations[i].type) {
2497                                 case FLAC__APODIZATION_BARTLETT:
2498                                         FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2499                                         break;
2500                                 case FLAC__APODIZATION_BARTLETT_HANN:
2501                                         FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2502                                         break;
2503                                 case FLAC__APODIZATION_BLACKMAN:
2504                                         FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2505                                         break;
2506                                 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2507                                         FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2508                                         break;
2509                                 case FLAC__APODIZATION_CONNES:
2510                                         FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2511                                         break;
2512                                 case FLAC__APODIZATION_FLATTOP:
2513                                         FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2514                                         break;
2515                                 case FLAC__APODIZATION_GAUSS:
2516                                         FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2517                                         break;
2518                                 case FLAC__APODIZATION_HAMMING:
2519                                         FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2520                                         break;
2521                                 case FLAC__APODIZATION_HANN:
2522                                         FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2523                                         break;
2524                                 case FLAC__APODIZATION_KAISER_BESSEL:
2525                                         FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2526                                         break;
2527                                 case FLAC__APODIZATION_NUTTALL:
2528                                         FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2529                                         break;
2530                                 case FLAC__APODIZATION_RECTANGLE:
2531                                         FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2532                                         break;
2533                                 case FLAC__APODIZATION_TRIANGLE:
2534                                         FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2535                                         break;
2536                                 case FLAC__APODIZATION_TUKEY:
2537                                         FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2538                                         break;
2539                                 case FLAC__APODIZATION_PARTIAL_TUKEY:
2540                                         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);
2541                                         break;
2542                                 case FLAC__APODIZATION_PUNCHOUT_TUKEY:
2543                                         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);
2544                                         break;
2545                                 case FLAC__APODIZATION_WELCH:
2546                                         FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2547                                         break;
2548                                 default:
2549                                         FLAC__ASSERT(0);
2550                                         /* double protection */
2551                                         FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2552                                         break;
2553                         }
2554                 }
2555         }
2556 #endif
2557
2558         if(ok)
2559                 encoder->private_->input_capacity = new_blocksize;
2560         else
2561                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2562
2563         return ok;
2564 }
2565
2566 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2567 {
2568         const FLAC__byte *buffer;
2569         size_t bytes;
2570
2571         FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2572
2573         if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2574                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2575                 return false;
2576         }
2577
2578         if(encoder->protected_->verify) {
2579                 encoder->private_->verify.output.data = buffer;
2580                 encoder->private_->verify.output.bytes = bytes;
2581                 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2582                         encoder->private_->verify.needs_magic_hack = true;
2583                 }
2584                 else {
2585                         if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2586                                 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2587                                 FLAC__bitwriter_clear(encoder->private_->frame);
2588                                 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2589                                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2590                                 return false;
2591                         }
2592                 }
2593         }
2594
2595         if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2596                 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2597                 FLAC__bitwriter_clear(encoder->private_->frame);
2598                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2599                 return false;
2600         }
2601
2602         FLAC__bitwriter_release_buffer(encoder->private_->frame);
2603         FLAC__bitwriter_clear(encoder->private_->frame);
2604
2605         if(samples > 0) {
2606                 encoder->private_->streaminfo.data.stream_info.min_framesize = flac_min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2607                 encoder->private_->streaminfo.data.stream_info.max_framesize = flac_max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2608         }
2609
2610         return true;
2611 }
2612
2613 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2614 {
2615         FLAC__StreamEncoderWriteStatus status;
2616         FLAC__uint64 output_position = 0;
2617
2618 #if FLAC__HAS_OGG == 0
2619         (void)is_last_block;
2620 #endif
2621
2622         /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2623         if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2624                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2625                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2626         }
2627
2628         /*
2629          * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2630          */
2631         if(samples == 0) {
2632                 FLAC__MetadataType type = (buffer[0] & 0x7f);
2633                 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2634                         encoder->protected_->streaminfo_offset = output_position;
2635                 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2636                         encoder->protected_->seektable_offset = output_position;
2637         }
2638
2639         /*
2640          * Mark the current seek point if hit (if audio_offset == 0 that
2641          * means we're still writing metadata and haven't hit the first
2642          * frame yet)
2643          */
2644         if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2645                 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2646                 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2647                 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2648                 FLAC__uint64 test_sample;
2649                 unsigned i;
2650                 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2651                         test_sample = encoder->private_->seek_table->points[i].sample_number;
2652                         if(test_sample > frame_last_sample) {
2653                                 break;
2654                         }
2655                         else if(test_sample >= frame_first_sample) {
2656                                 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2657                                 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2658                                 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2659                                 encoder->private_->first_seekpoint_to_check++;
2660                                 /* DO NOT: "break;" and here's why:
2661                                  * The seektable template may contain more than one target
2662                                  * sample for any given frame; we will keep looping, generating
2663                                  * duplicate seekpoints for them, and we'll clean it up later,
2664                                  * just before writing the seektable back to the metadata.
2665                                  */
2666                         }
2667                         else {
2668                                 encoder->private_->first_seekpoint_to_check++;
2669                         }
2670                 }
2671         }
2672
2673 #if FLAC__HAS_OGG
2674         if(encoder->private_->is_ogg) {
2675                 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2676                         &encoder->protected_->ogg_encoder_aspect,
2677                         buffer,
2678                         bytes,
2679                         samples,
2680                         encoder->private_->current_frame_number,
2681                         is_last_block,
2682                         (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2683                         encoder,
2684                         encoder->private_->client_data
2685                 );
2686         }
2687         else
2688 #endif
2689         status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2690
2691         if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2692                 encoder->private_->bytes_written += bytes;
2693                 encoder->private_->samples_written += samples;
2694                 /* we keep a high watermark on the number of frames written because
2695                  * when the encoder goes back to write metadata, 'current_frame'
2696                  * will drop back to 0.
2697                  */
2698                 encoder->private_->frames_written = flac_max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2699         }
2700         else
2701                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2702
2703         return status;
2704 }
2705
2706 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2707 void update_metadata_(const FLAC__StreamEncoder *encoder)
2708 {
2709         FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2710         const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2711         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2712         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2713         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2714         const unsigned bps = metadata->data.stream_info.bits_per_sample;
2715         FLAC__StreamEncoderSeekStatus seek_status;
2716
2717         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2718
2719         /* All this is based on intimate knowledge of the stream header
2720          * layout, but a change to the header format that would break this
2721          * would also break all streams encoded in the previous format.
2722          */
2723
2724         /*
2725          * Write MD5 signature
2726          */
2727         {
2728                 const unsigned md5_offset =
2729                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2730                         (
2731                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2732                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2733                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2734                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2735                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2736                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2737                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2738                                 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2739                         ) / 8;
2740
2741                 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2742                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2743                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2744                         return;
2745                 }
2746                 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2747                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2748                         return;
2749                 }
2750         }
2751
2752         /*
2753          * Write total samples
2754          */
2755         {
2756                 const unsigned total_samples_byte_offset =
2757                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2758                         (
2759                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2760                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2761                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2762                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2763                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2764                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2765                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2766                                 - 4
2767                         ) / 8;
2768
2769                 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2770                 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2771                 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2772                 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2773                 b[4] = (FLAC__byte)(samples & 0xFF);
2774                 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) {
2775                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2776                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2777                         return;
2778                 }
2779                 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2780                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2781                         return;
2782                 }
2783         }
2784
2785         /*
2786          * Write min/max framesize
2787          */
2788         {
2789                 const unsigned min_framesize_offset =
2790                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2791                         (
2792                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2793                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2794                         ) / 8;
2795
2796                 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2797                 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2798                 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2799                 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2800                 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2801                 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2802                 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) {
2803                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2804                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2805                         return;
2806                 }
2807                 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2808                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2809                         return;
2810                 }
2811         }
2812
2813         /*
2814          * Write seektable
2815          */
2816         if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2817                 unsigned i;
2818
2819                 FLAC__format_seektable_sort(encoder->private_->seek_table);
2820
2821                 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2822
2823                 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) {
2824                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2825                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2826                         return;
2827                 }
2828
2829                 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2830                         FLAC__uint64 xx;
2831                         unsigned x;
2832                         xx = encoder->private_->seek_table->points[i].sample_number;
2833                         b[7] = (FLAC__byte)xx; xx >>= 8;
2834                         b[6] = (FLAC__byte)xx; xx >>= 8;
2835                         b[5] = (FLAC__byte)xx; xx >>= 8;
2836                         b[4] = (FLAC__byte)xx; xx >>= 8;
2837                         b[3] = (FLAC__byte)xx; xx >>= 8;
2838                         b[2] = (FLAC__byte)xx; xx >>= 8;
2839                         b[1] = (FLAC__byte)xx; xx >>= 8;
2840                         b[0] = (FLAC__byte)xx; xx >>= 8;
2841                         xx = encoder->private_->seek_table->points[i].stream_offset;
2842                         b[15] = (FLAC__byte)xx; xx >>= 8;
2843                         b[14] = (FLAC__byte)xx; xx >>= 8;
2844                         b[13] = (FLAC__byte)xx; xx >>= 8;
2845                         b[12] = (FLAC__byte)xx; xx >>= 8;
2846                         b[11] = (FLAC__byte)xx; xx >>= 8;
2847                         b[10] = (FLAC__byte)xx; xx >>= 8;
2848                         b[9] = (FLAC__byte)xx; xx >>= 8;
2849                         b[8] = (FLAC__byte)xx; xx >>= 8;
2850                         x = encoder->private_->seek_table->points[i].frame_samples;
2851                         b[17] = (FLAC__byte)x; x >>= 8;
2852                         b[16] = (FLAC__byte)x; x >>= 8;
2853                         if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2854                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2855                                 return;
2856                         }
2857                 }
2858         }
2859 }
2860
2861 #if FLAC__HAS_OGG
2862 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2863 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2864 {
2865         /* the # of bytes in the 1st packet that precede the STREAMINFO */
2866         static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2867                 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2868                 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2869                 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2870                 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2871                 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2872                 FLAC__STREAM_SYNC_LENGTH
2873         ;
2874         FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2875         const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2876         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2877         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2878         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2879         ogg_page page;
2880
2881         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2882         FLAC__ASSERT(0 != encoder->private_->seek_callback);
2883
2884         /* Pre-check that client supports seeking, since we don't want the
2885          * ogg_helper code to ever have to deal with this condition.
2886          */
2887         if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2888                 return;
2889
2890         /* All this is based on intimate knowledge of the stream header
2891          * layout, but a change to the header format that would break this
2892          * would also break all streams encoded in the previous format.
2893          */
2894
2895         /**
2896          ** Write STREAMINFO stats
2897          **/
2898         simple_ogg_page__init(&page);
2899         if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2900                 simple_ogg_page__clear(&page);
2901                 return; /* state already set */
2902         }
2903
2904         /*
2905          * Write MD5 signature
2906          */
2907         {
2908                 const unsigned md5_offset =
2909                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2910                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2911                         (
2912                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2913                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2914                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2915                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2916                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2917                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2918                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2919                                 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2920                         ) / 8;
2921
2922                 if(md5_offset + 16 > (unsigned)page.body_len) {
2923                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2924                         simple_ogg_page__clear(&page);
2925                         return;
2926                 }
2927                 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2928         }
2929
2930         /*
2931          * Write total samples
2932          */
2933         {
2934                 const unsigned total_samples_byte_offset =
2935                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2936                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2937                         (
2938                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2939                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2940                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2941                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2942                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2943                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2944                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2945                                 - 4
2946                         ) / 8;
2947
2948                 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2949                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2950                         simple_ogg_page__clear(&page);
2951                         return;
2952                 }
2953                 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2954                 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2955                 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2956                 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2957                 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2958                 b[4] = (FLAC__byte)(samples & 0xFF);
2959                 memcpy(page.body + total_samples_byte_offset, b, 5);
2960         }
2961
2962         /*
2963          * Write min/max framesize
2964          */
2965         {
2966                 const unsigned min_framesize_offset =
2967                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2968                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2969                         (
2970                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2971                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2972                         ) / 8;
2973
2974                 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2975                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2976                         simple_ogg_page__clear(&page);
2977                         return;
2978                 }
2979                 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2980                 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2981                 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2982                 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2983                 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2984                 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2985                 memcpy(page.body + min_framesize_offset, b, 6);
2986         }
2987         if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2988                 simple_ogg_page__clear(&page);
2989                 return; /* state already set */
2990         }
2991         simple_ogg_page__clear(&page);
2992
2993         /*
2994          * Write seektable
2995          */
2996         if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2997                 unsigned i;
2998                 FLAC__byte *p;
2999
3000                 FLAC__format_seektable_sort(encoder->private_->seek_table);
3001
3002                 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
3003
3004                 simple_ogg_page__init(&page);
3005                 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
3006                         simple_ogg_page__clear(&page);
3007                         return; /* state already set */
3008                 }
3009
3010                 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
3011                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
3012                         simple_ogg_page__clear(&page);
3013                         return;
3014                 }
3015
3016                 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
3017                         FLAC__uint64 xx;
3018                         unsigned x;
3019                         xx = encoder->private_->seek_table->points[i].sample_number;
3020                         b[7] = (FLAC__byte)xx; xx >>= 8;
3021                         b[6] = (FLAC__byte)xx; xx >>= 8;
3022                         b[5] = (FLAC__byte)xx; xx >>= 8;
3023                         b[4] = (FLAC__byte)xx; xx >>= 8;
3024                         b[3] = (FLAC__byte)xx; xx >>= 8;
3025                         b[2] = (FLAC__byte)xx; xx >>= 8;
3026                         b[1] = (FLAC__byte)xx; xx >>= 8;
3027                         b[0] = (FLAC__byte)xx; xx >>= 8;
3028                         xx = encoder->private_->seek_table->points[i].stream_offset;
3029                         b[15] = (FLAC__byte)xx; xx >>= 8;
3030                         b[14] = (FLAC__byte)xx; xx >>= 8;
3031                         b[13] = (FLAC__byte)xx; xx >>= 8;
3032                         b[12] = (FLAC__byte)xx; xx >>= 8;
3033                         b[11] = (FLAC__byte)xx; xx >>= 8;
3034                         b[10] = (FLAC__byte)xx; xx >>= 8;
3035                         b[9] = (FLAC__byte)xx; xx >>= 8;
3036                         b[8] = (FLAC__byte)xx; xx >>= 8;
3037                         x = encoder->private_->seek_table->points[i].frame_samples;
3038                         b[17] = (FLAC__byte)x; x >>= 8;
3039                         b[16] = (FLAC__byte)x; x >>= 8;
3040                         memcpy(p, b, 18);
3041                 }
3042
3043                 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
3044                         simple_ogg_page__clear(&page);
3045                         return; /* state already set */
3046                 }
3047                 simple_ogg_page__clear(&page);
3048         }
3049 }
3050 #endif
3051
3052 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
3053 {
3054         FLAC__uint16 crc;
3055         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
3056
3057         /*
3058          * Accumulate raw signal to the MD5 signature
3059          */
3060         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)) {
3061                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3062                 return false;
3063         }
3064
3065         /*
3066          * Process the frame header and subframes into the frame bitbuffer
3067          */
3068         if(!process_subframes_(encoder, is_fractional_block)) {
3069                 /* the above function sets the state for us in case of an error */
3070                 return false;
3071         }
3072
3073         /*
3074          * Zero-pad the frame to a byte_boundary
3075          */
3076         if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
3077                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3078                 return false;
3079         }
3080
3081         /*
3082          * CRC-16 the whole thing
3083          */
3084         FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
3085         if(
3086                 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
3087                 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
3088         ) {
3089                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3090                 return false;
3091         }
3092
3093         /*
3094          * Write it
3095          */
3096         if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
3097                 /* the above function sets the state for us in case of an error */
3098                 return false;
3099         }
3100
3101         /*
3102          * Get ready for the next frame
3103          */
3104         encoder->private_->current_sample_number = 0;
3105         encoder->private_->current_frame_number++;
3106         encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
3107
3108         return true;
3109 }
3110
3111 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
3112 {
3113         FLAC__FrameHeader frame_header;
3114         unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
3115         FLAC__bool do_independent, do_mid_side;
3116
3117         /*
3118          * Calculate the min,max Rice partition orders
3119          */