libFLAC/cpu.c: Get rid of OS_IS_ANDROID function
[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-2016  Xiph.Org Foundation
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * - Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *
12  * - Redistributions in binary form must reproduce the above copyright
13  * notice, this list of conditions and the following disclaimer in the
14  * documentation and/or other materials provided with the distribution.
15  *
16  * - Neither the name of the Xiph.org Foundation nor the names of its
17  * contributors may be used to endorse or promote products derived from
18  * this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
24  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
28  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
30  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #ifdef HAVE_CONFIG_H
34 #  include <config.h>
35 #endif
36
37 #include <limits.h>
38 #include <stdio.h>
39 #include <stdlib.h> /* for malloc() */
40 #include <string.h> /* for memcpy() */
41 #include <sys/types.h> /* for off_t */
42 #ifdef _WIN32
43 #include <windows.h> /* for GetFileType() */
44 #include <io.h> /* for _get_osfhandle() */
45 #endif
46 #include "share/compat.h"
47 #include "FLAC/assert.h"
48 #include "FLAC/stream_decoder.h"
49 #include "protected/stream_encoder.h"
50 #include "private/bitwriter.h"
51 #include "private/bitmath.h"
52 #include "private/crc.h"
53 #include "private/cpu.h"
54 #include "private/fixed.h"
55 #include "private/format.h"
56 #include "private/lpc.h"
57 #include "private/md5.h"
58 #include "private/memory.h"
59 #include "private/macros.h"
60 #if FLAC__HAS_OGG
61 #include "private/ogg_helper.h"
62 #include "private/ogg_mapping.h"
63 #endif
64 #include "private/stream_encoder.h"
65 #include "private/stream_encoder_framing.h"
66 #include "private/window.h"
67 #include "share/alloc.h"
68 #include "share/private.h"
69
70
71 /* Exact Rice codeword length calculation is off by default.  The simple
72  * (and fast) estimation (of how many bits a residual value will be
73  * encoded with) in this encoder is very good, almost always yielding
74  * compression within 0.1% of exact calculation.
75  */
76 #undef EXACT_RICE_BITS_CALCULATION
77 /* Rice parameter searching is off by default.  The simple (and fast)
78  * parameter estimation in this encoder is very good, almost always
79  * yielding compression within 0.1% of the optimal parameters.
80  */
81 #undef ENABLE_RICE_PARAMETER_SEARCH
82
83
84 typedef struct {
85         FLAC__int32 *data[FLAC__MAX_CHANNELS];
86         unsigned size; /* of each data[] in samples */
87         unsigned tail;
88 } verify_input_fifo;
89
90 typedef struct {
91         const FLAC__byte *data;
92         unsigned capacity;
93         unsigned bytes;
94 } verify_output;
95
96 typedef enum {
97         ENCODER_IN_MAGIC = 0,
98         ENCODER_IN_METADATA = 1,
99         ENCODER_IN_AUDIO = 2
100 } EncoderStateHint;
101
102 static struct CompressionLevels {
103         FLAC__bool do_mid_side_stereo;
104         FLAC__bool loose_mid_side_stereo;
105         unsigned max_lpc_order;
106         unsigned qlp_coeff_precision;
107         FLAC__bool do_qlp_coeff_prec_search;
108         FLAC__bool do_escape_coding;
109         FLAC__bool do_exhaustive_model_search;
110         unsigned min_residual_partition_order;
111         unsigned max_residual_partition_order;
112         unsigned rice_parameter_search_dist;
113         const char *apodization;
114 } compression_levels_[] = {
115         { false, false,  0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
116         { true , true ,  0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
117         { true , false,  0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
118         { false, false,  6, 0, false, false, false, 0, 4, 0, "tukey(5e-1)" },
119         { true , true ,  8, 0, false, false, false, 0, 4, 0, "tukey(5e-1)" },
120         { true , false,  8, 0, false, false, false, 0, 5, 0, "tukey(5e-1)" },
121         { true , false,  8, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2)" },
122         { true , false, 12, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2)" },
123         { true , false, 12, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2);punchout_tukey(3)" }
124         /* here we use locale-independent 5e-1 instead of 0.5 or 0,5 */
125 };
126
127
128 /***********************************************************************
129  *
130  * Private class method prototypes
131  *
132  ***********************************************************************/
133
134 static void set_defaults_(FLAC__StreamEncoder *encoder);
135 static void free_(FLAC__StreamEncoder *encoder);
136 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
137 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
138 static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
139 static void update_metadata_(const FLAC__StreamEncoder *encoder);
140 #if FLAC__HAS_OGG
141 static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
142 #endif
143 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
144 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
145
146 static FLAC__bool process_subframe_(
147         FLAC__StreamEncoder *encoder,
148         unsigned min_partition_order,
149         unsigned max_partition_order,
150         const FLAC__FrameHeader *frame_header,
151         unsigned subframe_bps,
152         const FLAC__int32 integer_signal[],
153         FLAC__Subframe *subframe[2],
154         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
155         FLAC__int32 *residual[2],
156         unsigned *best_subframe,
157         unsigned *best_bits
158 );
159
160 static FLAC__bool add_subframe_(
161         FLAC__StreamEncoder *encoder,
162         unsigned blocksize,
163         unsigned subframe_bps,
164         const FLAC__Subframe *subframe,
165         FLAC__BitWriter *frame
166 );
167
168 static unsigned evaluate_constant_subframe_(
169         FLAC__StreamEncoder *encoder,
170         const FLAC__int32 signal,
171         unsigned blocksize,
172         unsigned subframe_bps,
173         FLAC__Subframe *subframe
174 );
175
176 static unsigned evaluate_fixed_subframe_(
177         FLAC__StreamEncoder *encoder,
178         const FLAC__int32 signal[],
179         FLAC__int32 residual[],
180         FLAC__uint64 abs_residual_partition_sums[],
181         unsigned raw_bits_per_partition[],
182         unsigned blocksize,
183         unsigned subframe_bps,
184         unsigned order,
185         unsigned rice_parameter,
186         unsigned rice_parameter_limit,
187         unsigned min_partition_order,
188         unsigned max_partition_order,
189         FLAC__bool do_escape_coding,
190         unsigned rice_parameter_search_dist,
191         FLAC__Subframe *subframe,
192         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
193 );
194
195 #ifndef FLAC__INTEGER_ONLY_LIBRARY
196 static unsigned evaluate_lpc_subframe_(
197         FLAC__StreamEncoder *encoder,
198         const FLAC__int32 signal[],
199         FLAC__int32 residual[],
200         FLAC__uint64 abs_residual_partition_sums[],
201         unsigned raw_bits_per_partition[],
202         const FLAC__real lp_coeff[],
203         unsigned blocksize,
204         unsigned subframe_bps,
205         unsigned order,
206         unsigned qlp_coeff_precision,
207         unsigned rice_parameter,
208         unsigned rice_parameter_limit,
209         unsigned min_partition_order,
210         unsigned max_partition_order,
211         FLAC__bool do_escape_coding,
212         unsigned rice_parameter_search_dist,
213         FLAC__Subframe *subframe,
214         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
215 );
216 #endif
217
218 static unsigned evaluate_verbatim_subframe_(
219         FLAC__StreamEncoder *encoder,
220         const FLAC__int32 signal[],
221         unsigned blocksize,
222         unsigned subframe_bps,
223         FLAC__Subframe *subframe
224 );
225
226 static unsigned find_best_partition_order_(
227         struct FLAC__StreamEncoderPrivate *private_,
228         const FLAC__int32 residual[],
229         FLAC__uint64 abs_residual_partition_sums[],
230         unsigned raw_bits_per_partition[],
231         unsigned residual_samples,
232         unsigned predictor_order,
233         unsigned rice_parameter,
234         unsigned rice_parameter_limit,
235         unsigned min_partition_order,
236         unsigned max_partition_order,
237         unsigned bps,
238         FLAC__bool do_escape_coding,
239         unsigned rice_parameter_search_dist,
240         FLAC__EntropyCodingMethod *best_ecm
241 );
242
243 static void precompute_partition_info_sums_(
244         const FLAC__int32 residual[],
245         FLAC__uint64 abs_residual_partition_sums[],
246         unsigned residual_samples,
247         unsigned predictor_order,
248         unsigned min_partition_order,
249         unsigned max_partition_order,
250         unsigned bps
251 );
252
253 static void precompute_partition_info_escapes_(
254         const FLAC__int32 residual[],
255         unsigned raw_bits_per_partition[],
256         unsigned residual_samples,
257         unsigned predictor_order,
258         unsigned min_partition_order,
259         unsigned max_partition_order
260 );
261
262 static FLAC__bool set_partitioned_rice_(
263 #ifdef EXACT_RICE_BITS_CALCULATION
264         const FLAC__int32 residual[],
265 #endif
266         const FLAC__uint64 abs_residual_partition_sums[],
267         const unsigned raw_bits_per_partition[],
268         const unsigned residual_samples,
269         const unsigned predictor_order,
270         const unsigned suggested_rice_parameter,
271         const unsigned rice_parameter_limit,
272         const unsigned rice_parameter_search_dist,
273         const unsigned partition_order,
274         const FLAC__bool search_for_escapes,
275         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
276         unsigned *bits
277 );
278
279 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
280
281 /* verify-related routines: */
282 static void append_to_verify_fifo_(
283         verify_input_fifo *fifo,
284         const FLAC__int32 * const input[],
285         unsigned input_offset,
286         unsigned channels,
287         unsigned wide_samples
288 );
289
290 static void append_to_verify_fifo_interleaved_(
291         verify_input_fifo *fifo,
292         const FLAC__int32 input[],
293         unsigned input_offset,
294         unsigned channels,
295         unsigned wide_samples
296 );
297
298 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
299 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
300 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
301 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
302
303 static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
304 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
305 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
306 static FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
307 static FILE *get_binary_stdout_(void);
308
309
310 /***********************************************************************
311  *
312  * Private class data
313  *
314  ***********************************************************************/
315
316 typedef struct FLAC__StreamEncoderPrivate {
317         unsigned input_capacity;                          /* current size (in samples) of the signal and residual buffers */
318         FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS];  /* the integer version of the input signal */
319         FLAC__int32 *integer_signal_mid_side[2];          /* the integer version of the mid-side input signal (stereo only) */
320 #ifndef FLAC__INTEGER_ONLY_LIBRARY
321         FLAC__real *real_signal[FLAC__MAX_CHANNELS];      /* (@@@ currently unused) the floating-point version of the input signal */
322         FLAC__real *real_signal_mid_side[2];              /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
323         FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
324         FLAC__real *windowed_signal;                      /* the integer_signal[] * current window[] */
325 #endif
326         unsigned subframe_bps[FLAC__MAX_CHANNELS];        /* the effective bits per sample of the input signal (stream bps - wasted bits) */
327         unsigned subframe_bps_mid_side[2];                /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
328         FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
329         FLAC__int32 *residual_workspace_mid_side[2][2];
330         FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
331         FLAC__Subframe subframe_workspace_mid_side[2][2];
332         FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
333         FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
334         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
335         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
336         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
337         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
338         unsigned best_subframe[FLAC__MAX_CHANNELS];       /* index (0 or 1) into 2nd dimension of the above workspaces */
339         unsigned best_subframe_mid_side[2];
340         unsigned best_subframe_bits[FLAC__MAX_CHANNELS];  /* size in bits of the best subframe for each channel */
341         unsigned best_subframe_bits_mid_side[2];
342         FLAC__uint64 *abs_residual_partition_sums;        /* workspace where the sum of abs(candidate residual) for each partition is stored */
343         unsigned *raw_bits_per_partition;                 /* workspace where the sum of silog2(candidate residual) for each partition is stored */
344         FLAC__BitWriter *frame;                           /* the current frame being worked on */
345         unsigned loose_mid_side_stereo_frames;            /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
346         unsigned loose_mid_side_stereo_frame_count;       /* number of frames using the current channel assignment */
347         FLAC__ChannelAssignment last_channel_assignment;
348         FLAC__StreamMetadata streaminfo;                  /* scratchpad for STREAMINFO as it is built */
349         FLAC__StreamMetadata_SeekTable *seek_table;       /* pointer into encoder->protected_->metadata_ where the seek table is */
350         unsigned current_sample_number;
351         unsigned current_frame_number;
352         FLAC__MD5Context md5context;
353         FLAC__CPUInfo cpuinfo;
354         void (*local_precompute_partition_info_sums)(const FLAC__int32 residual[], FLAC__uint64 abs_residual_partition_sums[], unsigned residual_samples, unsigned predictor_order, unsigned min_partition_order, unsigned max_partition_order, unsigned bps);
355 #ifndef FLAC__INTEGER_ONLY_LIBRARY
356         unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
357         unsigned (*local_fixed_compute_best_predictor_wide)(const FLAC__int32 data[], unsigned data_len, float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
358 #else
359         unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
360         unsigned (*local_fixed_compute_best_predictor_wide)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
361 #endif
362 #ifndef FLAC__INTEGER_ONLY_LIBRARY
363         void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
364         void (*local_lpc_compute_residual_from_qlp_coefficients)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
365         void (*local_lpc_compute_residual_from_qlp_coefficients_64bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
366         void (*local_lpc_compute_residual_from_qlp_coefficients_16bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
367 #endif
368         FLAC__bool disable_constant_subframes;
369         FLAC__bool disable_fixed_subframes;
370         FLAC__bool disable_verbatim_subframes;
371         FLAC__bool is_ogg;
372         FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
373         FLAC__StreamEncoderSeekCallback seek_callback;
374         FLAC__StreamEncoderTellCallback tell_callback;
375         FLAC__StreamEncoderWriteCallback write_callback;
376         FLAC__StreamEncoderMetadataCallback metadata_callback;
377         FLAC__StreamEncoderProgressCallback progress_callback;
378         void *client_data;
379         unsigned first_seekpoint_to_check;
380         FILE *file;                            /* only used when encoding to a file */
381         FLAC__uint64 bytes_written;
382         FLAC__uint64 samples_written;
383         unsigned frames_written;
384         unsigned total_frames_estimate;
385         /* unaligned (original) pointers to allocated data */
386         FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
387         FLAC__int32 *integer_signal_mid_side_unaligned[2];
388 #ifndef FLAC__INTEGER_ONLY_LIBRARY
389         FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
390         FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
391         FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
392         FLAC__real *windowed_signal_unaligned;
393 #endif
394         FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
395         FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
396         FLAC__uint64 *abs_residual_partition_sums_unaligned;
397         unsigned *raw_bits_per_partition_unaligned;
398         /*
399          * These fields have been moved here from private function local
400          * declarations merely to save stack space during encoding.
401          */
402 #ifndef FLAC__INTEGER_ONLY_LIBRARY
403         FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
404 #endif
405         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
406         /*
407          * The data for the verify section
408          */
409         struct {
410                 FLAC__StreamDecoder *decoder;
411                 EncoderStateHint state_hint;
412                 FLAC__bool needs_magic_hack;
413                 verify_input_fifo input_fifo;
414                 verify_output output;
415                 struct {
416                         FLAC__uint64 absolute_sample;
417                         unsigned frame_number;
418                         unsigned channel;
419                         unsigned sample;
420                         FLAC__int32 expected;
421                         FLAC__int32 got;
422                 } error_stats;
423         } verify;
424         FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
425 } FLAC__StreamEncoderPrivate;
426
427 /***********************************************************************
428  *
429  * Public static class data
430  *
431  ***********************************************************************/
432
433 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
434         "FLAC__STREAM_ENCODER_OK",
435         "FLAC__STREAM_ENCODER_UNINITIALIZED",
436         "FLAC__STREAM_ENCODER_OGG_ERROR",
437         "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
438         "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
439         "FLAC__STREAM_ENCODER_CLIENT_ERROR",
440         "FLAC__STREAM_ENCODER_IO_ERROR",
441         "FLAC__STREAM_ENCODER_FRAMING_ERROR",
442         "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
443 };
444
445 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
446         "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
447         "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
448         "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
449         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
450         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
451         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
452         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
453         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
454         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
455         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
456         "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
457         "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
458         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
459         "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
460 };
461
462 FLAC_API const char * const FLAC__StreamEncoderReadStatusString[] = {
463         "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
464         "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
465         "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
466         "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
467 };
468
469 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
470         "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
471         "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
472 };
473
474 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
475         "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
476         "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
477         "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
478 };
479
480 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
481         "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
482         "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
483         "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
484 };
485
486 /* Number of samples that will be overread to watch for end of stream.  By
487  * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
488  * always try to read blocksize+1 samples before encoding a block, so that
489  * even if the stream has a total sample count that is an integral multiple
490  * of the blocksize, we will still notice when we are encoding the last
491  * block.  This is needed, for example, to correctly set the end-of-stream
492  * marker in Ogg FLAC.
493  *
494  * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
495  * not really any reason to change it.
496  */
497 static const unsigned OVERREAD_ = 1;
498
499 /***********************************************************************
500  *
501  * Class constructor/destructor
502  *
503  */
504 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
505 {
506         FLAC__StreamEncoder *encoder;
507         unsigned i;
508
509         FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
510
511         encoder = calloc(1, sizeof(FLAC__StreamEncoder));
512         if(encoder == 0) {
513                 return 0;
514         }
515
516         encoder->protected_ = calloc(1, sizeof(FLAC__StreamEncoderProtected));
517         if(encoder->protected_ == 0) {
518                 free(encoder);
519                 return 0;
520         }
521
522         encoder->private_ = calloc(1, sizeof(FLAC__StreamEncoderPrivate));
523         if(encoder->private_ == 0) {
524                 free(encoder->protected_);
525                 free(encoder);
526                 return 0;
527         }
528
529         encoder->private_->frame = FLAC__bitwriter_new();
530         if(encoder->private_->frame == 0) {
531                 free(encoder->private_);
532                 free(encoder->protected_);
533                 free(encoder);
534                 return 0;
535         }
536
537         encoder->private_->file = 0;
538
539         set_defaults_(encoder);
540
541         encoder->private_->is_being_deleted = false;
542
543         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
544                 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
545                 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
546         }
547         for(i = 0; i < 2; i++) {
548                 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
549                 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
550         }
551         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
552                 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
553                 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
554         }
555         for(i = 0; i < 2; i++) {
556                 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
557                 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
558         }
559
560         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
561                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
562                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
563         }
564         for(i = 0; i < 2; i++) {
565                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
566                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
567         }
568         for(i = 0; i < 2; i++)
569                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
570
571         encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
572
573         return encoder;
574 }
575
576 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
577 {
578         unsigned i;
579
580         if (encoder == NULL)
581                 return ;
582
583         FLAC__ASSERT(0 != encoder->protected_);
584         FLAC__ASSERT(0 != encoder->private_);
585         FLAC__ASSERT(0 != encoder->private_->frame);
586
587         encoder->private_->is_being_deleted = true;
588
589         (void)FLAC__stream_encoder_finish(encoder);
590
591         if(0 != encoder->private_->verify.decoder)
592                 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
593
594         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
595                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
596                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
597         }
598         for(i = 0; i < 2; i++) {
599                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
600                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
601         }
602         for(i = 0; i < 2; i++)
603                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
604
605         FLAC__bitwriter_delete(encoder->private_->frame);
606         free(encoder->private_);
607         free(encoder->protected_);
608         free(encoder);
609 }
610
611 /***********************************************************************
612  *
613  * Public class methods
614  *
615  ***********************************************************************/
616
617 static FLAC__StreamEncoderInitStatus init_stream_internal_(
618         FLAC__StreamEncoder *encoder,
619         FLAC__StreamEncoderReadCallback read_callback,
620         FLAC__StreamEncoderWriteCallback write_callback,
621         FLAC__StreamEncoderSeekCallback seek_callback,
622         FLAC__StreamEncoderTellCallback tell_callback,
623         FLAC__StreamEncoderMetadataCallback metadata_callback,
624         void *client_data,
625         FLAC__bool is_ogg
626 )
627 {
628         unsigned i;
629         FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
630
631         FLAC__ASSERT(0 != encoder);
632
633         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
634                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
635
636         if(FLAC__HAS_OGG == 0 && is_ogg)
637                 return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
638
639         if(0 == write_callback || (seek_callback && 0 == tell_callback))
640                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
641
642         if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
643                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
644
645         if(encoder->protected_->channels != 2) {
646                 encoder->protected_->do_mid_side_stereo = false;
647                 encoder->protected_->loose_mid_side_stereo = false;
648         }
649         else if(!encoder->protected_->do_mid_side_stereo)
650                 encoder->protected_->loose_mid_side_stereo = false;
651
652         if(encoder->protected_->bits_per_sample >= 32)
653                 encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
654
655         if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
656                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
657
658         if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
659                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
660
661         if(encoder->protected_->blocksize == 0) {
662                 if(encoder->protected_->max_lpc_order == 0)
663                         encoder->protected_->blocksize = 1152;
664                 else
665                         encoder->protected_->blocksize = 4096;
666         }
667
668         if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
669                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
670
671         if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
672                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
673
674         if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
675                 return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
676
677         if(encoder->protected_->qlp_coeff_precision == 0) {
678                 if(encoder->protected_->bits_per_sample < 16) {
679                         /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
680                         /* @@@ until then we'll make a guess */
681                         encoder->protected_->qlp_coeff_precision = flac_max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
682                 }
683                 else if(encoder->protected_->bits_per_sample == 16) {
684                         if(encoder->protected_->blocksize <= 192)
685                                 encoder->protected_->qlp_coeff_precision = 7;
686                         else if(encoder->protected_->blocksize <= 384)
687                                 encoder->protected_->qlp_coeff_precision = 8;
688                         else if(encoder->protected_->blocksize <= 576)
689                                 encoder->protected_->qlp_coeff_precision = 9;
690                         else if(encoder->protected_->blocksize <= 1152)
691                                 encoder->protected_->qlp_coeff_precision = 10;
692                         else if(encoder->protected_->blocksize <= 2304)
693                                 encoder->protected_->qlp_coeff_precision = 11;
694                         else if(encoder->protected_->blocksize <= 4608)
695                                 encoder->protected_->qlp_coeff_precision = 12;
696                         else
697                                 encoder->protected_->qlp_coeff_precision = 13;
698                 }
699                 else {
700                         if(encoder->protected_->blocksize <= 384)
701                                 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
702                         else if(encoder->protected_->blocksize <= 1152)
703                                 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
704                         else
705                                 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
706                 }
707                 FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
708         }
709         else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
710                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
711
712         if(encoder->protected_->streamable_subset) {
713                 if(!FLAC__format_blocksize_is_subset(encoder->protected_->blocksize, encoder->protected_->sample_rate))
714                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
715                 if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
716                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
717                 if(
718                         encoder->protected_->bits_per_sample != 8 &&
719                         encoder->protected_->bits_per_sample != 12 &&
720                         encoder->protected_->bits_per_sample != 16 &&
721                         encoder->protected_->bits_per_sample != 20 &&
722                         encoder->protected_->bits_per_sample != 24
723                 )
724                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
725                 if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
726                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
727                 if(
728                         encoder->protected_->sample_rate <= 48000 &&
729                         (
730                                 encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
731                                 encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
732                         )
733                 ) {
734                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
735                 }
736         }
737
738         if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
739                 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
740         if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
741                 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
742
743 #if FLAC__HAS_OGG
744         /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
745         if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
746                 unsigned i1;
747                 for(i1 = 1; i1 < encoder->protected_->num_metadata_blocks; i1++) {
748                         if(0 != encoder->protected_->metadata[i1] && encoder->protected_->metadata[i1]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
749                                 FLAC__StreamMetadata *vc = encoder->protected_->metadata[i1];
750                                 for( ; i1 > 0; i1--)
751                                         encoder->protected_->metadata[i1] = encoder->protected_->metadata[i1-1];
752                                 encoder->protected_->metadata[0] = vc;
753                                 break;
754                         }
755                 }
756         }
757 #endif
758         /* keep track of any SEEKTABLE block */
759         if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
760                 unsigned i2;
761                 for(i2 = 0; i2 < encoder->protected_->num_metadata_blocks; i2++) {
762                         if(0 != encoder->protected_->metadata[i2] && encoder->protected_->metadata[i2]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
763                                 encoder->private_->seek_table = &encoder->protected_->metadata[i2]->data.seek_table;
764                                 break; /* take only the first one */
765                         }
766                 }
767         }
768
769         /* validate metadata */
770         if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
771                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
772         metadata_has_seektable = false;
773         metadata_has_vorbis_comment = false;
774         metadata_picture_has_type1 = false;
775         metadata_picture_has_type2 = false;
776         for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
777                 const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
778                 if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
779                         return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
780                 else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
781                         if(metadata_has_seektable) /* only one is allowed */
782                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
783                         metadata_has_seektable = true;
784                         if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
785                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
786                 }
787                 else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
788                         if(metadata_has_vorbis_comment) /* only one is allowed */
789                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
790                         metadata_has_vorbis_comment = true;
791                 }
792                 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
793                         if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
794                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
795                 }
796                 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
797                         if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
798                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
799                         if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
800                                 if(metadata_picture_has_type1) /* there should only be 1 per stream */
801                                         return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
802                                 metadata_picture_has_type1 = true;
803                                 /* standard icon must be 32x32 pixel PNG */
804                                 if(
805                                         m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
806                                         (
807                                                 (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
808                                                 m->data.picture.width != 32 ||
809                                                 m->data.picture.height != 32
810                                         )
811                                 )
812                                         return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
813                         }
814                         else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
815                                 if(metadata_picture_has_type2) /* there should only be 1 per stream */
816                                         return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
817                                 metadata_picture_has_type2 = true;
818                         }
819                 }
820         }
821
822         encoder->private_->input_capacity = 0;
823         for(i = 0; i < encoder->protected_->channels; i++) {
824                 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
825 #ifndef FLAC__INTEGER_ONLY_LIBRARY
826                 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
827 #endif
828         }
829         for(i = 0; i < 2; i++) {
830                 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
831 #ifndef FLAC__INTEGER_ONLY_LIBRARY
832                 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
833 #endif
834         }
835 #ifndef FLAC__INTEGER_ONLY_LIBRARY
836         for(i = 0; i < encoder->protected_->num_apodizations; i++)
837                 encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
838         encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
839 #endif
840         for(i = 0; i < encoder->protected_->channels; i++) {
841                 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
842                 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
843                 encoder->private_->best_subframe[i] = 0;
844         }
845         for(i = 0; i < 2; i++) {
846                 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
847                 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
848                 encoder->private_->best_subframe_mid_side[i] = 0;
849         }
850         encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
851         encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
852 #ifndef FLAC__INTEGER_ONLY_LIBRARY
853         encoder->private_->loose_mid_side_stereo_frames = (unsigned)((double)encoder->protected_->sample_rate * 0.4 / (double)encoder->protected_->blocksize + 0.5);
854 #else
855         /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
856         /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
857         FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
858         FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
859         FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
860         FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
861         encoder->private_->loose_mid_side_stereo_frames = (unsigned)FLAC__fixedpoint_trunc((((FLAC__uint64)(encoder->protected_->sample_rate) * (FLAC__uint64)(26214)) << 16) / (encoder->protected_->blocksize<<16) + FLAC__FP_ONE_HALF);
862 #endif
863         if(encoder->private_->loose_mid_side_stereo_frames == 0)
864                 encoder->private_->loose_mid_side_stereo_frames = 1;
865         encoder->private_->loose_mid_side_stereo_frame_count = 0;
866         encoder->private_->current_sample_number = 0;
867         encoder->private_->current_frame_number = 0;
868
869         /*
870          * get the CPU info and set the function pointers
871          */
872         FLAC__cpu_info(&encoder->private_->cpuinfo);
873         /* first default to the non-asm routines */
874 #ifndef FLAC__INTEGER_ONLY_LIBRARY
875         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
876 #endif
877         encoder->private_->local_precompute_partition_info_sums = precompute_partition_info_sums_;
878         encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
879         encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide;
880 #ifndef FLAC__INTEGER_ONLY_LIBRARY
881         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
882         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
883         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
884 #endif
885         /* now override with asm where appropriate */
886 #ifndef FLAC__INTEGER_ONLY_LIBRARY
887 # ifndef FLAC__NO_ASM
888         if(encoder->private_->cpuinfo.use_asm) {
889 #  ifdef FLAC__CPU_IA32
890                 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
891 #   ifdef FLAC__HAS_NASM
892                 if(encoder->private_->cpuinfo.ia32.sse) {
893                         if(encoder->protected_->max_lpc_order < 4)
894                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4_old;
895                         else if(encoder->protected_->max_lpc_order < 8)
896                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8_old;
897                         else if(encoder->protected_->max_lpc_order < 12)
898                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12_old;
899                         else if(encoder->protected_->max_lpc_order < 16)
900                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_16_old;
901                         else
902                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
903                 }
904                 else
905                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
906
907                 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_asm_ia32; /* OPT_IA32: was really necessary for GCC < 4.9 */
908                 if(encoder->private_->cpuinfo.ia32.mmx) {
909                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
910                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
911                 }
912                 else {
913                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
914                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
915                 }
916
917                 if(encoder->private_->cpuinfo.ia32.mmx && encoder->private_->cpuinfo.ia32.cmov)
918                         encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
919 #   endif /* FLAC__HAS_NASM */
920 #   if FLAC__HAS_X86INTRIN
921 #    if defined FLAC__SSE_SUPPORTED
922                 if(encoder->private_->cpuinfo.ia32.sse) {
923                         if(encoder->private_->cpuinfo.ia32.sse42 || !encoder->private_->cpuinfo.ia32.intel) { /* use new autocorrelation functions */
924                                 if(encoder->protected_->max_lpc_order < 4)
925                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_new;
926                                 else if(encoder->protected_->max_lpc_order < 8)
927                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_new;
928                                 else if(encoder->protected_->max_lpc_order < 12)
929                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_new;
930                                 else if(encoder->protected_->max_lpc_order < 16)
931                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_new;
932                                 else
933                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
934                         }
935                         else { /* use old autocorrelation functions */
936                                 if(encoder->protected_->max_lpc_order < 4)
937                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_old;
938                                 else if(encoder->protected_->max_lpc_order < 8)
939                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_old;
940                                 else if(encoder->protected_->max_lpc_order < 12)
941                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_old;
942                                 else if(encoder->protected_->max_lpc_order < 16)
943                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_old;
944                                 else
945                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
946                         }
947                 }
948 #    endif
949
950 #    ifdef FLAC__SSE2_SUPPORTED
951                 if(encoder->private_->cpuinfo.ia32.sse2) {
952                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients       = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse2;
953                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_sse2;
954                 }
955 #    endif
956 #    ifdef FLAC__SSE4_1_SUPPORTED
957                 if(encoder->private_->cpuinfo.ia32.sse41) {
958                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients       = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse41;
959                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_sse41;
960                 }
961 #    endif
962 #    ifdef FLAC__AVX2_SUPPORTED
963                 if(encoder->private_->cpuinfo.ia32.avx2) {
964                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_avx2;
965                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients       = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_avx2;
966                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_avx2;
967                 }
968 #    endif
969
970 #    ifdef FLAC__SSE2_SUPPORTED
971                 if (encoder->private_->cpuinfo.ia32.sse2) {
972                         encoder->private_->local_fixed_compute_best_predictor      = FLAC__fixed_compute_best_predictor_intrin_sse2;
973                         encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_sse2;
974                 }
975 #    endif
976 #    ifdef FLAC__SSSE3_SUPPORTED
977                 if (encoder->private_->cpuinfo.ia32.ssse3) {
978                         encoder->private_->local_fixed_compute_best_predictor      = FLAC__fixed_compute_best_predictor_intrin_ssse3;
979                         encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_ssse3;
980                 }
981 #    endif
982 #   endif /* FLAC__HAS_X86INTRIN */
983 #  elif defined FLAC__CPU_X86_64
984                 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_X86_64);
985 #   if FLAC__HAS_X86INTRIN
986 #    ifdef FLAC__SSE_SUPPORTED
987                 if(encoder->private_->cpuinfo.x86.sse42 || !encoder->private_->cpuinfo.x86.intel) { /* use new autocorrelation functions */
988                         if(encoder->protected_->max_lpc_order < 4)
989                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_new;
990                         else if(encoder->protected_->max_lpc_order < 8)
991                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_new;
992                         else if(encoder->protected_->max_lpc_order < 12)
993                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_new;
994                         else if(encoder->protected_->max_lpc_order < 16)
995                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_new;
996                 }
997                 else {
998                         if(encoder->protected_->max_lpc_order < 4)
999                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_old;
1000                         else if(encoder->protected_->max_lpc_order < 8)
1001                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_old;
1002                         else if(encoder->protected_->max_lpc_order < 12)
1003                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_old;
1004                         else if(encoder->protected_->max_lpc_order < 16)
1005                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_old;
1006                 }
1007 #    endif
1008
1009 #    ifdef FLAC__SSE2_SUPPORTED
1010                 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_sse2;
1011 #    endif
1012 #    ifdef FLAC__SSE4_1_SUPPORTED
1013                 if(encoder->private_->cpuinfo.x86.sse41) {
1014                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse41;
1015                 }
1016 #    endif
1017 #    ifdef FLAC__AVX2_SUPPORTED
1018                 if(encoder->private_->cpuinfo.x86.avx2) {
1019                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_avx2;
1020                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients       = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_avx2;
1021                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_avx2;
1022                 }
1023 #    endif
1024
1025 #    ifdef FLAC__SSE2_SUPPORTED
1026                 encoder->private_->local_fixed_compute_best_predictor      = FLAC__fixed_compute_best_predictor_intrin_sse2;
1027                 encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_sse2;
1028 #    endif
1029 #    ifdef FLAC__SSSE3_SUPPORTED
1030                 if (encoder->private_->cpuinfo.x86.ssse3) {
1031                         encoder->private_->local_fixed_compute_best_predictor      = FLAC__fixed_compute_best_predictor_intrin_ssse3;
1032                         encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_ssse3;
1033                 }
1034 #    endif
1035 #   endif /* FLAC__HAS_X86INTRIN */
1036 #  endif /* FLAC__CPU_... */
1037         }
1038 # endif /* !FLAC__NO_ASM */
1039 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
1040 #if !defined FLAC__NO_ASM && FLAC__HAS_X86INTRIN
1041         if(encoder->private_->cpuinfo.use_asm) {
1042 # if defined FLAC__CPU_IA32
1043 #  ifdef FLAC__SSE2_SUPPORTED
1044                 if(encoder->private_->cpuinfo.ia32.sse2)
1045                         encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_sse2;
1046 #  endif
1047 #  ifdef FLAC__SSSE3_SUPPORTED
1048                 if(encoder->private_->cpuinfo.ia32.ssse3)
1049                         encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_ssse3;
1050 #  endif
1051 #  ifdef FLAC__AVX2_SUPPORTED
1052                 if(encoder->private_->cpuinfo.ia32.avx2)
1053                         encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_avx2;
1054 #  endif
1055 # elif defined FLAC__CPU_X86_64
1056 #  ifdef FLAC__SSE2_SUPPORTED
1057                 encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_sse2;
1058 #  endif
1059 #  ifdef FLAC__SSSE3_SUPPORTED
1060                 if(encoder->private_->cpuinfo.x86.ssse3)
1061                         encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_ssse3;
1062 #  endif
1063 #  ifdef FLAC__AVX2_SUPPORTED
1064                 if(encoder->private_->cpuinfo.x86.avx2)
1065                         encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_avx2;
1066 #  endif
1067 # endif /* FLAC__CPU_... */
1068         }
1069 #endif /* !FLAC__NO_ASM && FLAC__HAS_X86INTRIN */
1070
1071         /* set state to OK; from here on, errors are fatal and we'll override the state then */
1072         encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
1073
1074 #if FLAC__HAS_OGG
1075         encoder->private_->is_ogg = is_ogg;
1076         if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
1077                 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
1078                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1079         }
1080 #endif
1081
1082         encoder->private_->read_callback = read_callback;
1083         encoder->private_->write_callback = write_callback;
1084         encoder->private_->seek_callback = seek_callback;
1085         encoder->private_->tell_callback = tell_callback;
1086         encoder->private_->metadata_callback = metadata_callback;
1087         encoder->private_->client_data = client_data;
1088
1089         if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
1090                 /* the above function sets the state for us in case of an error */
1091                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1092         }
1093
1094         if(!FLAC__bitwriter_init(encoder->private_->frame)) {
1095                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1096                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1097         }
1098
1099         /*
1100          * Set up the verify stuff if necessary
1101          */
1102         if(encoder->protected_->verify) {
1103                 /*
1104                  * First, set up the fifo which will hold the
1105                  * original signal to compare against
1106                  */
1107                 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
1108                 for(i = 0; i < encoder->protected_->channels; i++) {
1109                         if(0 == (encoder->private_->verify.input_fifo.data[i] = safe_malloc_mul_2op_p(sizeof(FLAC__int32), /*times*/encoder->private_->verify.input_fifo.size))) {
1110                                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1111                                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1112                         }
1113                 }
1114                 encoder->private_->verify.input_fifo.tail = 0;
1115
1116                 /*
1117                  * Now set up a stream decoder for verification
1118                  */
1119                 if(0 == encoder->private_->verify.decoder) {
1120                         encoder->private_->verify.decoder = FLAC__stream_decoder_new();
1121                         if(0 == encoder->private_->verify.decoder) {
1122                                 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1123                                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1124                         }
1125                 }
1126
1127                 if(FLAC__stream_decoder_init_stream(encoder->private_->verify.decoder, verify_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, verify_write_callback_, verify_metadata_callback_, verify_error_callback_, /*client_data=*/encoder) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
1128                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1129                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1130                 }
1131         }
1132         encoder->private_->verify.error_stats.absolute_sample = 0;
1133         encoder->private_->verify.error_stats.frame_number = 0;
1134         encoder->private_->verify.error_stats.channel = 0;
1135         encoder->private_->verify.error_stats.sample = 0;
1136         encoder->private_->verify.error_stats.expected = 0;
1137         encoder->private_->verify.error_stats.got = 0;
1138
1139         /*
1140          * These must be done before we write any metadata, because that
1141          * calls the write_callback, which uses these values.
1142          */
1143         encoder->private_->first_seekpoint_to_check = 0;
1144         encoder->private_->samples_written = 0;
1145         encoder->protected_->streaminfo_offset = 0;
1146         encoder->protected_->seektable_offset = 0;
1147         encoder->protected_->audio_offset = 0;
1148
1149         /*
1150          * write the stream header
1151          */
1152         if(encoder->protected_->verify)
1153                 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1154         if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1155                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1156                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1157         }
1158         if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1159                 /* the above function sets the state for us in case of an error */
1160                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1161         }
1162
1163         /*
1164          * write the STREAMINFO metadata block
1165          */
1166         if(encoder->protected_->verify)
1167                 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1168         encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1169         encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1170         encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1171         encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1172         encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1173         encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1174         encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1175         encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1176         encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1177         encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1178         encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1179         memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1180         if(encoder->protected_->do_md5)
1181                 FLAC__MD5Init(&encoder->private_->md5context);
1182         if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1183                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1184                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1185         }
1186         if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1187                 /* the above function sets the state for us in case of an error */
1188                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1189         }
1190
1191         /*
1192          * Now that the STREAMINFO block is written, we can init this to an
1193          * absurdly-high value...
1194          */
1195         encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1196         /* ... and clear this to 0 */
1197         encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1198
1199         /*
1200          * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1201          * if not, we will write an empty one (FLAC__add_metadata_block()
1202          * automatically supplies the vendor string).
1203          *
1204          * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1205          * the STREAMINFO.  (In the case that metadata_has_vorbis_comment is
1206          * true it will have already insured that the metadata list is properly
1207          * ordered.)
1208          */
1209         if(!metadata_has_vorbis_comment) {
1210                 FLAC__StreamMetadata vorbis_comment;
1211                 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1212                 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1213                 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1214                 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1215                 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1216                 vorbis_comment.data.vorbis_comment.num_comments = 0;
1217                 vorbis_comment.data.vorbis_comment.comments = 0;
1218                 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1219                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1220                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1221                 }
1222                 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1223                         /* the above function sets the state for us in case of an error */
1224                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1225                 }
1226         }
1227
1228         /*
1229          * write the user's metadata blocks
1230          */
1231         for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1232                 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1233                 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1234                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1235                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1236                 }
1237                 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1238                         /* the above function sets the state for us in case of an error */
1239                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1240                 }
1241         }
1242
1243         /* now that all the metadata is written, we save the stream offset */
1244         if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &encoder->protected_->audio_offset, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) { /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
1245                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1246                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1247         }
1248
1249         if(encoder->protected_->verify)
1250                 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1251
1252         return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1253 }
1254
1255 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1256         FLAC__StreamEncoder *encoder,
1257         FLAC__StreamEncoderWriteCallback write_callback,
1258         FLAC__StreamEncoderSeekCallback seek_callback,
1259         FLAC__StreamEncoderTellCallback tell_callback,
1260         FLAC__StreamEncoderMetadataCallback metadata_callback,
1261         void *client_data
1262 )
1263 {
1264         return init_stream_internal_(
1265                 encoder,
1266                 /*read_callback=*/0,
1267                 write_callback,
1268                 seek_callback,
1269                 tell_callback,
1270                 metadata_callback,
1271                 client_data,
1272                 /*is_ogg=*/false
1273         );
1274 }
1275
1276 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1277         FLAC__StreamEncoder *encoder,
1278         FLAC__StreamEncoderReadCallback read_callback,
1279         FLAC__StreamEncoderWriteCallback write_callback,
1280         FLAC__StreamEncoderSeekCallback seek_callback,
1281         FLAC__StreamEncoderTellCallback tell_callback,
1282         FLAC__StreamEncoderMetadataCallback metadata_callback,
1283         void *client_data
1284 )
1285 {
1286         return init_stream_internal_(
1287                 encoder,
1288                 read_callback,
1289                 write_callback,
1290                 seek_callback,
1291                 tell_callback,
1292                 metadata_callback,
1293                 client_data,
1294                 /*is_ogg=*/true
1295         );
1296 }
1297
1298 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1299         FLAC__StreamEncoder *encoder,
1300         FILE *file,
1301         FLAC__StreamEncoderProgressCallback progress_callback,
1302         void *client_data,
1303         FLAC__bool is_ogg
1304 )
1305 {
1306         FLAC__StreamEncoderInitStatus init_status;
1307
1308         FLAC__ASSERT(0 != encoder);
1309         FLAC__ASSERT(0 != file);
1310
1311         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1312                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1313
1314         /* double protection */
1315         if(file == 0) {
1316                 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1317                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1318         }
1319
1320         /*
1321          * To make sure that our file does not go unclosed after an error, we
1322          * must assign the FILE pointer before any further error can occur in
1323          * this routine.
1324          */
1325         if(file == stdout)
1326                 file = get_binary_stdout_(); /* just to be safe */
1327
1328 #ifdef _WIN32
1329         /*
1330          * Windows can suffer quite badly from disk fragmentation. This can be
1331          * reduced significantly by setting the output buffer size to be 10MB.
1332          */
1333         if(GetFileType((HANDLE)_get_osfhandle(_fileno(file))) == FILE_TYPE_DISK)
1334                 setvbuf(file, NULL, _IOFBF, 10*1024*1024);
1335 #endif
1336         encoder->private_->file = file;
1337
1338         encoder->private_->progress_callback = progress_callback;
1339         encoder->private_->bytes_written = 0;
1340         encoder->private_->samples_written = 0;
1341         encoder->private_->frames_written = 0;
1342
1343         init_status = init_stream_internal_(
1344                 encoder,
1345                 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1346                 file_write_callback_,
1347                 encoder->private_->file == stdout? 0 : file_seek_callback_,
1348                 encoder->private_->file == stdout? 0 : file_tell_callback_,
1349                 /*metadata_callback=*/0,
1350                 client_data,
1351                 is_ogg
1352         );
1353         if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1354                 /* the above function sets the state for us in case of an error */
1355                 return init_status;
1356         }
1357
1358         {
1359                 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1360
1361                 FLAC__ASSERT(blocksize != 0);
1362                 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1363         }
1364
1365         return init_status;
1366 }
1367
1368 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1369         FLAC__StreamEncoder *encoder,
1370         FILE *file,
1371         FLAC__StreamEncoderProgressCallback progress_callback,
1372         void *client_data
1373 )
1374 {
1375         return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1376 }
1377
1378 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1379         FLAC__StreamEncoder *encoder,
1380         FILE *file,
1381         FLAC__StreamEncoderProgressCallback progress_callback,
1382         void *client_data
1383 )
1384 {
1385         return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1386 }
1387
1388 static FLAC__StreamEncoderInitStatus init_file_internal_(
1389         FLAC__StreamEncoder *encoder,
1390         const char *filename,
1391         FLAC__StreamEncoderProgressCallback progress_callback,
1392         void *client_data,
1393         FLAC__bool is_ogg
1394 )
1395 {
1396         FILE *file;
1397
1398         FLAC__ASSERT(0 != encoder);
1399
1400         /*
1401          * To make sure that our file does not go unclosed after an error, we
1402          * have to do the same entrance checks here that are later performed
1403          * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1404          */
1405         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1406                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1407
1408         file = filename? flac_fopen(filename, "w+b") : stdout;
1409
1410         if(file == 0) {
1411                 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1412                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1413         }
1414
1415         return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1416 }
1417
1418 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1419         FLAC__StreamEncoder *encoder,
1420         const char *filename,
1421         FLAC__StreamEncoderProgressCallback progress_callback,
1422         void *client_data
1423 )
1424 {
1425         return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1426 }
1427
1428 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1429         FLAC__StreamEncoder *encoder,
1430         const char *filename,
1431         FLAC__StreamEncoderProgressCallback progress_callback,
1432         void *client_data
1433 )
1434 {
1435         return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1436 }
1437
1438 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1439 {
1440         FLAC__bool error = false;
1441
1442         FLAC__ASSERT(0 != encoder);
1443         FLAC__ASSERT(0 != encoder->private_);
1444         FLAC__ASSERT(0 != encoder->protected_);
1445
1446         if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1447                 return true;
1448
1449         if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1450                 if(encoder->private_->current_sample_number != 0) {
1451                         const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1452                         encoder->protected_->blocksize = encoder->private_->current_sample_number;
1453                         if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1454                                 error = true;
1455                 }
1456         }
1457
1458         if(encoder->protected_->do_md5)
1459                 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1460
1461         if(!encoder->private_->is_being_deleted) {
1462                 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1463                         if(encoder->private_->seek_callback) {
1464 #if FLAC__HAS_OGG
1465                                 if(encoder->private_->is_ogg)
1466                                         update_ogg_metadata_(encoder);
1467                                 else
1468 #endif
1469                                 update_metadata_(encoder);
1470
1471                                 /* check if an error occurred while updating metadata */
1472                                 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1473                                         error = true;
1474                         }
1475                         if(encoder->private_->metadata_callback)
1476                                 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1477                 }
1478
1479                 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1480                         if(!error)
1481                                 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1482                         error = true;
1483                 }
1484         }
1485
1486         if(0 != encoder->private_->file) {
1487                 if(encoder->private_->file != stdout)
1488                         fclose(encoder->private_->file);
1489                 encoder->private_->file = 0;
1490         }
1491
1492 #if FLAC__HAS_OGG
1493         if(encoder->private_->is_ogg)
1494                 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1495 #endif
1496
1497         free_(encoder);
1498         set_defaults_(encoder);
1499
1500         if(!error)
1501                 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1502
1503         return !error;
1504 }
1505
1506 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1507 {
1508         FLAC__ASSERT(0 != encoder);
1509         FLAC__ASSERT(0 != encoder->private_);
1510         FLAC__ASSERT(0 != encoder->protected_);
1511         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1512                 return false;
1513 #if FLAC__HAS_OGG
1514         /* can't check encoder->private_->is_ogg since that's not set until init time */
1515         FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1516         return true;
1517 #else
1518         (void)value;
1519         return false;
1520 #endif
1521 }
1522
1523 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1524 {
1525         FLAC__ASSERT(0 != encoder);
1526         FLAC__ASSERT(0 != encoder->private_);
1527         FLAC__ASSERT(0 != encoder->protected_);
1528         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1529                 return false;
1530 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1531         encoder->protected_->verify = value;
1532 #endif
1533         return true;
1534 }
1535
1536 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1537 {
1538         FLAC__ASSERT(0 != encoder);
1539         FLAC__ASSERT(0 != encoder->private_);
1540         FLAC__ASSERT(0 != encoder->protected_);
1541         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1542                 return false;
1543         encoder->protected_->streamable_subset = value;
1544         return true;
1545 }
1546
1547 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
1548 {
1549         FLAC__ASSERT(0 != encoder);
1550         FLAC__ASSERT(0 != encoder->private_);
1551         FLAC__ASSERT(0 != encoder->protected_);
1552         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1553                 return false;
1554         encoder->protected_->do_md5 = value;
1555         return true;
1556 }
1557
1558 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1559 {
1560         FLAC__ASSERT(0 != encoder);
1561         FLAC__ASSERT(0 != encoder->private_);
1562         FLAC__ASSERT(0 != encoder->protected_);
1563         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1564                 return false;
1565         encoder->protected_->channels = value;
1566         return true;
1567 }
1568
1569 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1570 {
1571         FLAC__ASSERT(0 != encoder);
1572         FLAC__ASSERT(0 != encoder->private_);
1573         FLAC__ASSERT(0 != encoder->protected_);
1574         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1575                 return false;
1576         encoder->protected_->bits_per_sample = value;
1577         return true;
1578 }
1579
1580 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1581 {
1582         FLAC__ASSERT(0 != encoder);
1583         FLAC__ASSERT(0 != encoder->private_);
1584         FLAC__ASSERT(0 != encoder->protected_);
1585         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1586                 return false;
1587         encoder->protected_->sample_rate = value;
1588         return true;
1589 }
1590
1591 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1592 {
1593         FLAC__bool ok = true;
1594         FLAC__ASSERT(0 != encoder);
1595         FLAC__ASSERT(0 != encoder->private_);
1596         FLAC__ASSERT(0 != encoder->protected_);
1597         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1598                 return false;
1599         if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1600                 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1601         ok &= FLAC__stream_encoder_set_do_mid_side_stereo          (encoder, compression_levels_[value].do_mid_side_stereo);
1602         ok &= FLAC__stream_encoder_set_loose_mid_side_stereo       (encoder, compression_levels_[value].loose_mid_side_stereo);
1603 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1604 #if 1
1605         ok &= FLAC__stream_encoder_set_apodization                 (encoder, compression_levels_[value].apodization);
1606 #else
1607         /* equivalent to -A tukey(0.5) */
1608         encoder->protected_->num_apodizations = 1;
1609         encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1610         encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1611 #endif
1612 #endif
1613         ok &= FLAC__stream_encoder_set_max_lpc_order               (encoder, compression_levels_[value].max_lpc_order);
1614         ok &= FLAC__stream_encoder_set_qlp_coeff_precision         (encoder, compression_levels_[value].qlp_coeff_precision);
1615         ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search    (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1616         ok &= FLAC__stream_encoder_set_do_escape_coding            (encoder, compression_levels_[value].do_escape_coding);
1617         ok &= FLAC__stream_encoder_set_do_exhaustive_model_search  (encoder, compression_levels_[value].do_exhaustive_model_search);
1618         ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1619         ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1620         ok &= FLAC__stream_encoder_set_rice_parameter_search_dist  (encoder, compression_levels_[value].rice_parameter_search_dist);
1621         return ok;
1622 }
1623
1624 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1625 {
1626         FLAC__ASSERT(0 != encoder);
1627         FLAC__ASSERT(0 != encoder->private_);
1628         FLAC__ASSERT(0 != encoder->protected_);
1629         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1630                 return false;
1631         encoder->protected_->blocksize = value;
1632         return true;
1633 }
1634
1635 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1636 {
1637         FLAC__ASSERT(0 != encoder);
1638         FLAC__ASSERT(0 != encoder->private_);
1639         FLAC__ASSERT(0 != encoder->protected_);
1640         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1641                 return false;
1642         encoder->protected_->do_mid_side_stereo = value;
1643         return true;
1644 }
1645
1646 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1647 {
1648         FLAC__ASSERT(0 != encoder);
1649         FLAC__ASSERT(0 != encoder->private_);
1650         FLAC__ASSERT(0 != encoder->protected_);
1651         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1652                 return false;
1653         encoder->protected_->loose_mid_side_stereo = value;
1654         return true;
1655 }
1656
1657 /*@@@@add to tests*/
1658 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1659 {
1660         FLAC__ASSERT(0 != encoder);
1661         FLAC__ASSERT(0 != encoder->private_);
1662         FLAC__ASSERT(0 != encoder->protected_);
1663         FLAC__ASSERT(0 != specification);
1664         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1665                 return false;
1666 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1667         (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1668 #else
1669         encoder->protected_->num_apodizations = 0;
1670         while(1) {
1671                 const char *s = strchr(specification, ';');
1672                 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1673                 if     (n==8  && 0 == strncmp("bartlett"     , specification, n))
1674                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1675                 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1676                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1677                 else if(n==8  && 0 == strncmp("blackman"     , specification, n))
1678                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1679                 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1680                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1681                 else if(n==6  && 0 == strncmp("connes"       , specification, n))
1682                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1683                 else if(n==7  && 0 == strncmp("flattop"      , specification, n))
1684                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1685                 else if(n>7   && 0 == strncmp("gauss("       , specification, 6)) {
1686                         FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1687                         if (stddev > 0.0 && stddev <= 0.5) {
1688                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1689                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1690                         }
1691                 }
1692                 else if(n==7  && 0 == strncmp("hamming"      , specification, n))
1693                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1694                 else if(n==4  && 0 == strncmp("hann"         , specification, n))
1695                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1696                 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1697                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1698                 else if(n==7  && 0 == strncmp("nuttall"      , specification, n))
1699                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1700                 else if(n==9  && 0 == strncmp("rectangle"    , specification, n))
1701                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1702                 else if(n==8  && 0 == strncmp("triangle"     , specification, n))
1703                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1704                 else if(n>7   && 0 == strncmp("tukey("       , specification, 6)) {
1705                         FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1706                         if (p >= 0.0 && p <= 1.0) {
1707                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1708                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1709                         }
1710                 }
1711                 else if(n>15   && 0 == strncmp("partial_tukey("       , specification, 14)) {
1712                         FLAC__int32 tukey_parts = (FLAC__int32)strtod(specification+14, 0);
1713                         const char *si_1 = strchr(specification, '/');
1714                         FLAC__real overlap = si_1?flac_min((FLAC__real)strtod(si_1+1, 0),0.99f):0.1f;
1715                         FLAC__real overlap_units = 1.0f/(1.0f - overlap) - 1.0f;
1716                         const char *si_2 = strchr((si_1?(si_1+1):specification), '/');
1717                         FLAC__real tukey_p = si_2?(FLAC__real)strtod(si_2+1, 0):0.2f;
1718
1719                         if (tukey_parts <= 1) {
1720                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = tukey_p;
1721                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1722                         }else if (encoder->protected_->num_apodizations + tukey_parts < 32){
1723                                 FLAC__int32 m;
1724                                 for(m = 0; m < tukey_parts; m++){
1725                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.p = tukey_p;
1726                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.start = m/(tukey_parts+overlap_units);
1727                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.end = (m+1+overlap_units)/(tukey_parts+overlap_units);
1728                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_PARTIAL_TUKEY;
1729                                 }
1730                         }
1731                 }
1732                 else if(n>16   && 0 == strncmp("punchout_tukey("       , specification, 15)) {
1733                         FLAC__int32 tukey_parts = (FLAC__int32)strtod(specification+15, 0);
1734                         const char *si_1 = strchr(specification, '/');
1735                         FLAC__real overlap = si_1?flac_min((FLAC__real)strtod(si_1+1, 0),0.99f):0.2f;
1736                         FLAC__real overlap_units = 1.0f/(1.0f - overlap) - 1.0f;
1737                         const char *si_2 = strchr((si_1?(si_1+1):specification), '/');
1738                         FLAC__real tukey_p = si_2?(FLAC__real)strtod(si_2+1, 0):0.2f;
1739
1740                         if (tukey_parts <= 1) {
1741                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = tukey_p;
1742                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1743                         }else if (encoder->protected_->num_apodizations + tukey_parts < 32){
1744                                 FLAC__int32 m;
1745                                 for(m = 0; m < tukey_parts; m++){
1746                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.p = tukey_p;
1747                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.start = m/(tukey_parts+overlap_units);
1748                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.end = (m+1+overlap_units)/(tukey_parts+overlap_units);
1749                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_PUNCHOUT_TUKEY;
1750                                 }
1751                         }
1752                 }
1753                 else if(n==5  && 0 == strncmp("welch"        , specification, n))
1754                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1755                 if (encoder->protected_->num_apodizations == 32)
1756                         break;
1757                 if (s)
1758                         specification = s+1;
1759                 else
1760                         break;
1761         }
1762         if(encoder->protected_->num_apodizations == 0) {
1763                 encoder->protected_->num_apodizations = 1;
1764                 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1765                 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1766         }
1767 #endif
1768         return true;
1769 }
1770
1771 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1772 {
1773         FLAC__ASSERT(0 != encoder);
1774         FLAC__ASSERT(0 != encoder->private_);
1775         FLAC__ASSERT(0 != encoder->protected_);
1776         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1777                 return false;
1778         encoder->protected_->max_lpc_order = value;
1779         return true;
1780 }
1781
1782 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1783 {
1784         FLAC__ASSERT(0 != encoder);
1785         FLAC__ASSERT(0 != encoder->private_);
1786         FLAC__ASSERT(0 != encoder->protected_);
1787         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1788                 return false;
1789         encoder->protected_->qlp_coeff_precision = value;
1790         return true;
1791 }
1792
1793 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1794 {
1795         FLAC__ASSERT(0 != encoder);
1796         FLAC__ASSERT(0 != encoder->private_);
1797         FLAC__ASSERT(0 != encoder->protected_);
1798         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1799                 return false;
1800         encoder->protected_->do_qlp_coeff_prec_search = value;
1801         return true;
1802 }
1803
1804 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1805 {
1806         FLAC__ASSERT(0 != encoder);
1807         FLAC__ASSERT(0 != encoder->private_);
1808         FLAC__ASSERT(0 != encoder->protected_);
1809         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1810                 return false;
1811 #if 0
1812         /*@@@ deprecated: */
1813         encoder->protected_->do_escape_coding = value;
1814 #else
1815         (void)value;
1816 #endif
1817         return true;
1818 }
1819
1820 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1821 {
1822         FLAC__ASSERT(0 != encoder);
1823         FLAC__ASSERT(0 != encoder->private_);
1824         FLAC__ASSERT(0 != encoder->protected_);
1825         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1826                 return false;
1827         encoder->protected_->do_exhaustive_model_search = value;
1828         return true;
1829 }
1830
1831 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1832 {
1833         FLAC__ASSERT(0 != encoder);
1834         FLAC__ASSERT(0 != encoder->private_);
1835         FLAC__ASSERT(0 != encoder->protected_);
1836         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1837                 return false;
1838         encoder->protected_->min_residual_partition_order = value;
1839         return true;
1840 }
1841
1842 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1843 {
1844         FLAC__ASSERT(0 != encoder);
1845         FLAC__ASSERT(0 != encoder->private_);
1846         FLAC__ASSERT(0 != encoder->protected_);
1847         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1848                 return false;
1849         encoder->protected_->max_residual_partition_order = value;
1850         return true;
1851 }
1852
1853 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1854 {
1855         FLAC__ASSERT(0 != encoder);
1856         FLAC__ASSERT(0 != encoder->private_);
1857         FLAC__ASSERT(0 != encoder->protected_);
1858         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1859                 return false;
1860 #if 0
1861         /*@@@ deprecated: */
1862         encoder->protected_->rice_parameter_search_dist = value;
1863 #else
1864         (void)value;
1865 #endif
1866         return true;
1867 }
1868
1869 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1870 {
1871         FLAC__ASSERT(0 != encoder);
1872         FLAC__ASSERT(0 != encoder->private_);
1873         FLAC__ASSERT(0 != encoder->protected_);
1874         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1875                 return false;
1876         value = flac_min(value, (FLAC__U64L(1) << FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN) - 1);
1877         encoder->protected_->total_samples_estimate = value;
1878         return true;
1879 }
1880
1881 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1882 {
1883         FLAC__ASSERT(0 != encoder);
1884         FLAC__ASSERT(0 != encoder->private_);
1885         FLAC__ASSERT(0 != encoder->protected_);
1886         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1887                 return false;
1888         if(0 == metadata)
1889                 num_blocks = 0;
1890         if(0 == num_blocks)
1891                 metadata = 0;
1892         /* realloc() does not do exactly what we want so... */
1893         if(encoder->protected_->metadata) {
1894                 free(encoder->protected_->metadata);
1895                 encoder->protected_->metadata = 0;
1896                 encoder->protected_->num_metadata_blocks = 0;
1897         }
1898         if(num_blocks) {
1899                 FLAC__StreamMetadata **m;
1900                 if(0 == (m = safe_malloc_mul_2op_p(sizeof(m[0]), /*times*/num_blocks)))
1901                         return false;
1902                 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1903                 encoder->protected_->metadata = m;
1904                 encoder->protected_->num_metadata_blocks = num_blocks;
1905         }
1906 #if FLAC__HAS_OGG
1907         if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1908                 return false;
1909 #endif
1910         return true;
1911 }
1912
1913 /*
1914  * These three functions are not static, but not publically exposed in
1915  * include/FLAC/ either.  They are used by the test suite.
1916  */
1917 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1918 {
1919         FLAC__ASSERT(0 != encoder);
1920         FLAC__ASSERT(0 != encoder->private_);
1921         FLAC__ASSERT(0 != encoder->protected_);
1922         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1923                 return false;
1924         encoder->private_->disable_constant_subframes = value;
1925         return true;
1926 }
1927
1928 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1929 {
1930         FLAC__ASSERT(0 != encoder);
1931         FLAC__ASSERT(0 != encoder->private_);
1932         FLAC__ASSERT(0 != encoder->protected_);
1933         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1934                 return false;
1935         encoder->private_->disable_fixed_subframes = value;
1936         return true;
1937 }
1938
1939 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1940 {
1941         FLAC__ASSERT(0 != encoder);
1942         FLAC__ASSERT(0 != encoder->private_);
1943         FLAC__ASSERT(0 != encoder->protected_);
1944         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1945                 return false;
1946         encoder->private_->disable_verbatim_subframes = value;
1947         return true;
1948 }
1949
1950 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1951 {
1952         FLAC__ASSERT(0 != encoder);
1953         FLAC__ASSERT(0 != encoder->private_);
1954         FLAC__ASSERT(0 != encoder->protected_);
1955         return encoder->protected_->state;
1956 }
1957
1958 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1959 {
1960         FLAC__ASSERT(0 != encoder);
1961         FLAC__ASSERT(0 != encoder->private_);
1962         FLAC__ASSERT(0 != encoder->protected_);
1963         if(encoder->protected_->verify)
1964                 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1965         else
1966                 return FLAC__STREAM_DECODER_UNINITIALIZED;
1967 }
1968
1969 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1970 {
1971         FLAC__ASSERT(0 != encoder);
1972         FLAC__ASSERT(0 != encoder->private_);
1973         FLAC__ASSERT(0 != encoder->protected_);
1974         if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1975                 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1976         else
1977                 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1978 }
1979
1980 FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got)
1981 {
1982         FLAC__ASSERT(0 != encoder);
1983         FLAC__ASSERT(0 != encoder->private_);
1984         FLAC__ASSERT(0 != encoder->protected_);
1985         if(0 != absolute_sample)
1986                 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1987         if(0 != frame_number)
1988                 *frame_number = encoder->private_->verify.error_stats.frame_number;
1989         if(0 != channel)
1990                 *channel = encoder->private_->verify.error_stats.channel;
1991         if(0 != sample)
1992                 *sample = encoder->private_->verify.error_stats.sample;
1993         if(0 != expected)
1994                 *expected = encoder->private_->verify.error_stats.expected;
1995         if(0 != got)
1996                 *got = encoder->private_->verify.error_stats.got;
1997 }
1998
1999 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
2000 {
2001         FLAC__ASSERT(0 != encoder);
2002         FLAC__ASSERT(0 != encoder->private_);
2003         FLAC__ASSERT(0 != encoder->protected_);
2004         return encoder->protected_->verify;
2005 }
2006
2007 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
2008 {
2009         FLAC__ASSERT(0 != encoder);
2010         FLAC__ASSERT(0 != encoder->private_);
2011         FLAC__ASSERT(0 != encoder->protected_);
2012         return encoder->protected_->streamable_subset;
2013 }
2014
2015 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
2016 {
2017         FLAC__ASSERT(0 != encoder);
2018         FLAC__ASSERT(0 != encoder->private_);
2019         FLAC__ASSERT(0 != encoder->protected_);
2020         return encoder->protected_->do_md5;
2021 }
2022
2023 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
2024 {
2025         FLAC__ASSERT(0 != encoder);
2026         FLAC__ASSERT(0 != encoder->private_);
2027         FLAC__ASSERT(0 != encoder->protected_);
2028         return encoder->protected_->channels;
2029 }
2030
2031 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
2032 {
2033         FLAC__ASSERT(0 != encoder);
2034         FLAC__ASSERT(0 != encoder->private_);
2035         FLAC__ASSERT(0 != encoder->protected_);
2036         return encoder->protected_->bits_per_sample;
2037 }
2038
2039 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
2040 {
2041         FLAC__ASSERT(0 != encoder);
2042         FLAC__ASSERT(0 != encoder->private_);
2043         FLAC__ASSERT(0 != encoder->protected_);
2044         return encoder->protected_->sample_rate;
2045 }
2046
2047 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
2048 {
2049         FLAC__ASSERT(0 != encoder);
2050         FLAC__ASSERT(0 != encoder->private_);
2051         FLAC__ASSERT(0 != encoder->protected_);
2052         return encoder->protected_->blocksize;
2053 }
2054
2055 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
2056 {
2057         FLAC__ASSERT(0 != encoder);
2058         FLAC__ASSERT(0 != encoder->private_);
2059         FLAC__ASSERT(0 != encoder->protected_);
2060         return encoder->protected_->do_mid_side_stereo;
2061 }
2062
2063 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
2064 {
2065         FLAC__ASSERT(0 != encoder);
2066         FLAC__ASSERT(0 != encoder->private_);
2067         FLAC__ASSERT(0 != encoder->protected_);
2068         return encoder->protected_->loose_mid_side_stereo;
2069 }
2070
2071 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
2072 {
2073         FLAC__ASSERT(0 != encoder);
2074         FLAC__ASSERT(0 != encoder->private_);
2075         FLAC__ASSERT(0 != encoder->protected_);
2076         return encoder->protected_->max_lpc_order;
2077 }
2078
2079 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
2080 {
2081         FLAC__ASSERT(0 != encoder);
2082         FLAC__ASSERT(0 != encoder->private_);
2083         FLAC__ASSERT(0 != encoder->protected_);
2084         return encoder->protected_->qlp_coeff_precision;
2085 }
2086
2087 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
2088 {
2089         FLAC__ASSERT(0 != encoder);
2090         FLAC__ASSERT(0 != encoder->private_);
2091         FLAC__ASSERT(0 != encoder->protected_);
2092         return encoder->protected_->do_qlp_coeff_prec_search;
2093 }
2094
2095 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
2096 {
2097         FLAC__ASSERT(0 != encoder);
2098         FLAC__ASSERT(0 != encoder->private_);
2099         FLAC__ASSERT(0 != encoder->protected_);
2100         return encoder->protected_->do_escape_coding;
2101 }
2102
2103 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
2104 {
2105         FLAC__ASSERT(0 != encoder);
2106         FLAC__ASSERT(0 != encoder->private_);
2107         FLAC__ASSERT(0 != encoder->protected_);
2108         return encoder->protected_->do_exhaustive_model_search;
2109 }
2110
2111 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
2112 {
2113         FLAC__ASSERT(0 != encoder);
2114         FLAC__ASSERT(0 != encoder->private_);
2115         FLAC__ASSERT(0 != encoder->protected_);
2116         return encoder->protected_->min_residual_partition_order;
2117 }
2118
2119 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
2120 {
2121         FLAC__ASSERT(0 != encoder);
2122         FLAC__ASSERT(0 != encoder->private_);
2123         FLAC__ASSERT(0 != encoder->protected_);
2124         return encoder->protected_->max_residual_partition_order;
2125 }
2126
2127 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
2128 {
2129         FLAC__ASSERT(0 != encoder);
2130         FLAC__ASSERT(0 != encoder->private_);
2131         FLAC__ASSERT(0 != encoder->protected_);
2132         return encoder->protected_->rice_parameter_search_dist;
2133 }
2134
2135 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
2136 {
2137         FLAC__ASSERT(0 != encoder);
2138         FLAC__ASSERT(0 != encoder->private_);
2139         FLAC__ASSERT(0 != encoder->protected_);
2140         return encoder->protected_->total_samples_estimate;
2141 }
2142
2143 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
2144 {
2145         unsigned i, j = 0, channel;
2146         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2147
2148         FLAC__ASSERT(0 != encoder);
2149         FLAC__ASSERT(0 != encoder->private_);
2150         FLAC__ASSERT(0 != encoder->protected_);
2151         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2152
2153 //      FLAC__ASSERT(samples <= blocksize);
2154
2155         do {
2156                 const unsigned n = flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
2157
2158                 if(encoder->protected_->verify)
2159                         append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
2160
2161                 for(channel = 0; channel < channels; channel++) {
2162                         if (buffer[channel] == NULL) {
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         encoder->private_->is_ogg = false;
2328         encoder->private_->read_callback = 0;
2329         encoder->private_->write_callback = 0;
2330         encoder->private_->seek_callback = 0;
2331         encoder->private_->tell_callback = 0;
2332         encoder->private_->metadata_callback = 0;
2333         encoder->private_->progress_callback = 0;
2334         encoder->private_->client_data = 0;
2335
2336 #if FLAC__HAS_OGG
2337         FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2338 #endif
2339
2340         FLAC__stream_encoder_set_compression_level(encoder, 5);
2341 }
2342
2343 void free_(FLAC__StreamEncoder *encoder)
2344 {
2345         unsigned i, channel;
2346
2347         FLAC__ASSERT(0 != encoder);
2348         if(encoder->protected_->metadata) {
2349                 free(encoder->protected_->metadata);
2350                 encoder->protected_->metadata = 0;
2351                 encoder->protected_->num_metadata_blocks = 0;
2352         }
2353         for(i = 0; i < encoder->protected_->channels; i++) {
2354                 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2355                         free(encoder->private_->integer_signal_unaligned[i]);
2356                         encoder->private_->integer_signal_unaligned[i] = 0;
2357                 }
2358 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2359                 if(0 != encoder->private_->real_signal_unaligned[i]) {
2360                         free(encoder->private_->real_signal_unaligned[i]);
2361                         encoder->private_->real_signal_unaligned[i] = 0;
2362                 }
2363 #endif
2364         }
2365         for(i = 0; i < 2; i++) {
2366                 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2367                         free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2368                         encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2369                 }
2370 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2371                 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2372                         free(encoder->private_->real_signal_mid_side_unaligned[i]);
2373                         encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2374                 }
2375 #endif
2376         }
2377 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2378         for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2379                 if(0 != encoder->private_->window_unaligned[i]) {
2380                         free(encoder->private_->window_unaligned[i]);
2381                         encoder->private_->window_unaligned[i] = 0;
2382                 }
2383         }
2384         if(0 != encoder->private_->windowed_signal_unaligned) {
2385                 free(encoder->private_->windowed_signal_unaligned);
2386                 encoder->private_->windowed_signal_unaligned = 0;
2387         }
2388 #endif
2389         for(channel = 0; channel < encoder->protected_->channels; channel++) {
2390                 for(i = 0; i < 2; i++) {
2391                         if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2392                                 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2393                                 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2394                         }
2395                 }
2396         }
2397         for(channel = 0; channel < 2; channel++) {
2398                 for(i = 0; i < 2; i++) {
2399                         if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2400                                 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2401                                 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2402                         }
2403                 }
2404         }
2405         if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2406                 free(encoder->private_->abs_residual_partition_sums_unaligned);
2407                 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2408         }
2409         if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2410                 free(encoder->private_->raw_bits_per_partition_unaligned);
2411                 encoder->private_->raw_bits_per_partition_unaligned = 0;
2412         }
2413         if(encoder->protected_->verify) {
2414                 for(i = 0; i < encoder->protected_->channels; i++) {
2415                         if(0 != encoder->private_->verify.input_fifo.data[i]) {
2416                                 free(encoder->private_->verify.input_fifo.data[i]);
2417                                 encoder->private_->verify.input_fifo.data[i] = 0;
2418                         }
2419                 }
2420         }
2421         FLAC__bitwriter_free(encoder->private_->frame);
2422 }
2423
2424 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2425 {
2426         FLAC__bool ok;
2427         unsigned i, channel;
2428
2429         FLAC__ASSERT(new_blocksize > 0);
2430         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2431         FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2432
2433         /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2434         if(new_blocksize <= encoder->private_->input_capacity)
2435                 return true;
2436
2437         ok = true;
2438
2439         /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx() and ..._intrin_sse2()
2440          * require that the input arrays (in our case the integer signals)
2441          * have a buffer of up to 3 zeroes in front (at negative indices) for
2442          * alignment purposes; we use 4 in front to keep the data well-aligned.
2443          */
2444
2445         for(i = 0; ok && i < encoder->protected_->channels; i++) {
2446                 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2447                 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2448                 encoder->private_->integer_signal[i] += 4;
2449 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2450 #if 0 /* @@@ currently unused */
2451                 if(encoder->protected_->max_lpc_order > 0)
2452                         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2453 #endif
2454 #endif
2455         }
2456         for(i = 0; ok && i < 2; i++) {
2457                 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]);
2458                 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2459                 encoder->private_->integer_signal_mid_side[i] += 4;
2460 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2461 #if 0 /* @@@ currently unused */
2462                 if(encoder->protected_->max_lpc_order > 0)
2463                         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]);
2464 #endif
2465 #endif
2466         }
2467 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2468         if(ok && encoder->protected_->max_lpc_order > 0) {
2469                 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2470                         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2471                 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2472         }
2473 #endif
2474         for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2475                 for(i = 0; ok && i < 2; i++) {
2476                         ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2477                 }
2478         }
2479         for(channel = 0; ok && channel < 2; channel++) {
2480                 for(i = 0; ok && i < 2; i++) {
2481                         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]);
2482                 }
2483         }
2484         /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2485         /*@@@ 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) */
2486         ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2487         if(encoder->protected_->do_escape_coding)
2488                 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2489
2490         /* now adjust the windows if the blocksize has changed */
2491 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2492         if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2493                 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2494                         switch(encoder->protected_->apodizations[i].type) {
2495                                 case FLAC__APODIZATION_BARTLETT:
2496                                         FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2497                                         break;
2498                                 case FLAC__APODIZATION_BARTLETT_HANN:
2499                                         FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2500                                         break;
2501                                 case FLAC__APODIZATION_BLACKMAN:
2502                                         FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2503                                         break;
2504                                 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2505                                         FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2506                                         break;
2507                                 case FLAC__APODIZATION_CONNES:
2508                                         FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2509                                         break;
2510                                 case FLAC__APODIZATION_FLATTOP:
2511                                         FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2512                                         break;
2513                                 case FLAC__APODIZATION_GAUSS:
2514                                         FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2515                                         break;
2516                                 case FLAC__APODIZATION_HAMMING:
2517                                         FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2518                                         break;
2519                                 case FLAC__APODIZATION_HANN:
2520                                         FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2521                                         break;
2522                                 case FLAC__APODIZATION_KAISER_BESSEL:
2523                                         FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2524                                         break;
2525                                 case FLAC__APODIZATION_NUTTALL:
2526                                         FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2527                                         break;
2528                                 case FLAC__APODIZATION_RECTANGLE:
2529                                         FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2530                                         break;
2531                                 case FLAC__APODIZATION_TRIANGLE:
2532                                         FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2533                                         break;
2534                                 case FLAC__APODIZATION_TUKEY:
2535                                         FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2536                                         break;
2537                                 case FLAC__APODIZATION_PARTIAL_TUKEY:
2538                                         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);
2539                                         break;
2540                                 case FLAC__APODIZATION_PUNCHOUT_TUKEY:
2541                                         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);
2542                                         break;
2543                                 case FLAC__APODIZATION_WELCH:
2544                                         FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2545                                         break;
2546                                 default:
2547                                         FLAC__ASSERT(0);
2548                                         /* double protection */
2549                                         FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2550                                         break;
2551                         }
2552                 }
2553         }
2554 #endif
2555
2556         if(ok)
2557                 encoder->private_->input_capacity = new_blocksize;
2558         else
2559                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2560
2561         return ok;
2562 }
2563
2564 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2565 {
2566         const FLAC__byte *buffer;
2567         size_t bytes;
2568
2569         FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2570
2571         if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2572                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2573                 return false;
2574         }
2575
2576         if(encoder->protected_->verify) {
2577                 encoder->private_->verify.output.data = buffer;
2578                 encoder->private_->verify.output.bytes = bytes;
2579                 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2580                         encoder->private_->verify.needs_magic_hack = true;
2581                 }
2582                 else {
2583                         if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2584                                 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2585                                 FLAC__bitwriter_clear(encoder->private_->frame);
2586                                 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2587                                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2588                                 return false;
2589                         }
2590                 }
2591         }
2592
2593         if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2594                 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2595                 FLAC__bitwriter_clear(encoder->private_->frame);
2596                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2597                 return false;
2598         }
2599
2600         FLAC__bitwriter_release_buffer(encoder->private_->frame);
2601         FLAC__bitwriter_clear(encoder->private_->frame);
2602
2603         if(samples > 0) {
2604                 encoder->private_->streaminfo.data.stream_info.min_framesize = flac_min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2605                 encoder->private_->streaminfo.data.stream_info.max_framesize = flac_max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2606         }
2607
2608         return true;
2609 }
2610
2611 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2612 {
2613         FLAC__StreamEncoderWriteStatus status;
2614         FLAC__uint64 output_position = 0;
2615
2616 #if FLAC__HAS_OGG == 0
2617         (void)is_last_block;
2618 #endif
2619
2620         /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2621         if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2622                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2623                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2624         }
2625
2626         /*
2627          * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2628          */
2629         if(samples == 0) {
2630                 FLAC__MetadataType type = (buffer[0] & 0x7f);
2631                 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2632                         encoder->protected_->streaminfo_offset = output_position;
2633                 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2634                         encoder->protected_->seektable_offset = output_position;
2635         }
2636
2637         /*
2638          * Mark the current seek point if hit (if audio_offset == 0 that
2639          * means we're still writing metadata and haven't hit the first
2640          * frame yet)
2641          */
2642         if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2643                 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2644                 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2645                 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2646                 FLAC__uint64 test_sample;
2647                 unsigned i;
2648                 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2649                         test_sample = encoder->private_->seek_table->points[i].sample_number;
2650                         if(test_sample > frame_last_sample) {
2651                                 break;
2652                         }
2653                         else if(test_sample >= frame_first_sample) {
2654                                 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2655                                 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2656                                 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2657                                 encoder->private_->first_seekpoint_to_check++;
2658                                 /* DO NOT: "break;" and here's why:
2659                                  * The seektable template may contain more than one target
2660                                  * sample for any given frame; we will keep looping, generating
2661                                  * duplicate seekpoints for them, and we'll clean it up later,
2662                                  * just before writing the seektable back to the metadata.
2663                                  */
2664                         }
2665                         else {
2666                                 encoder->private_->first_seekpoint_to_check++;
2667                         }
2668                 }
2669         }
2670
2671 #if FLAC__HAS_OGG
2672         if(encoder->private_->is_ogg) {
2673                 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2674                         &encoder->protected_->ogg_encoder_aspect,
2675                         buffer,
2676                         bytes,
2677                         samples,
2678                         encoder->private_->current_frame_number,
2679                         is_last_block,
2680                         (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2681                         encoder,
2682                         encoder->private_->client_data
2683                 );
2684         }
2685         else
2686 #endif
2687         status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2688
2689         if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2690                 encoder->private_->bytes_written += bytes;
2691                 encoder->private_->samples_written += samples;
2692                 /* we keep a high watermark on the number of frames written because
2693                  * when the encoder goes back to write metadata, 'current_frame'
2694                  * will drop back to 0.
2695                  */
2696                 encoder->private_->frames_written = flac_max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2697         }
2698         else
2699                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2700
2701         return status;
2702 }
2703
2704 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2705 void update_metadata_(const FLAC__StreamEncoder *encoder)
2706 {
2707         FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2708         const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2709         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2710         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2711         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2712         const unsigned bps = metadata->data.stream_info.bits_per_sample;
2713         FLAC__StreamEncoderSeekStatus seek_status;
2714
2715         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2716
2717         /* All this is based on intimate knowledge of the stream header
2718          * layout, but a change to the header format that would break this
2719          * would also break all streams encoded in the previous format.
2720          */
2721
2722         /*
2723          * Write MD5 signature
2724          */
2725         {
2726                 const unsigned md5_offset =
2727                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2728                         (
2729                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2730                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2731                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2732                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2733                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2734                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2735                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2736                                 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2737                         ) / 8;
2738
2739                 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2740                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2741                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2742                         return;
2743                 }
2744                 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2745                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2746                         return;
2747                 }
2748         }
2749
2750         /*
2751          * Write total samples
2752          */
2753         {
2754                 const unsigned total_samples_byte_offset =
2755                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2756                         (
2757                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2758                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2759                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2760                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2761                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2762                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2763                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2764                                 - 4
2765                         ) / 8;
2766
2767                 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2768                 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2769                 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2770                 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2771                 b[4] = (FLAC__byte)(samples & 0xFF);
2772                 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) {
2773                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2774                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2775                         return;
2776                 }
2777                 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2778                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2779                         return;
2780                 }
2781         }
2782
2783         /*
2784          * Write min/max framesize
2785          */
2786         {
2787                 const unsigned min_framesize_offset =
2788                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2789                         (
2790                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2791                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2792                         ) / 8;
2793
2794                 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2795                 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2796                 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2797                 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2798                 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2799                 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2800                 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) {
2801                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2802                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2803                         return;
2804                 }
2805                 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2806                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2807                         return;
2808                 }
2809         }
2810
2811         /*
2812          * Write seektable
2813          */
2814         if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2815                 unsigned i;
2816
2817                 FLAC__format_seektable_sort(encoder->private_->seek_table);
2818
2819                 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2820
2821                 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) {
2822                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2823                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2824                         return;
2825                 }
2826
2827                 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2828                         FLAC__uint64 xx;
2829                         unsigned x;
2830                         xx = encoder->private_->seek_table->points[i].sample_number;
2831                         b[7] = (FLAC__byte)xx; xx >>= 8;
2832                         b[6] = (FLAC__byte)xx; xx >>= 8;
2833                         b[5] = (FLAC__byte)xx; xx >>= 8;
2834                         b[4] = (FLAC__byte)xx; xx >>= 8;
2835                         b[3] = (FLAC__byte)xx; xx >>= 8;
2836                         b[2] = (FLAC__byte)xx; xx >>= 8;
2837                         b[1] = (FLAC__byte)xx; xx >>= 8;
2838                         b[0] = (FLAC__byte)xx; xx >>= 8;
2839                         xx = encoder->private_->seek_table->points[i].stream_offset;
2840                         b[15] = (FLAC__byte)xx; xx >>= 8;
2841                         b[14] = (FLAC__byte)xx; xx >>= 8;
2842                         b[13] = (FLAC__byte)xx; xx >>= 8;
2843                         b[12] = (FLAC__byte)xx; xx >>= 8;
2844                         b[11] = (FLAC__byte)xx; xx >>= 8;
2845                         b[10] = (FLAC__byte)xx; xx >>= 8;
2846                         b[9] = (FLAC__byte)xx; xx >>= 8;
2847                         b[8] = (FLAC__byte)xx; xx >>= 8;
2848                         x = encoder->private_->seek_table->points[i].frame_samples;
2849                         b[17] = (FLAC__byte)x; x >>= 8;
2850                         b[16] = (FLAC__byte)x; x >>= 8;
2851                         if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2852                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2853                                 return;
2854                         }
2855                 }
2856         }
2857 }
2858
2859 #if FLAC__HAS_OGG
2860 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2861 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2862 {
2863         /* the # of bytes in the 1st packet that precede the STREAMINFO */
2864         static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2865                 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2866                 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2867                 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2868                 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2869                 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2870                 FLAC__STREAM_SYNC_LENGTH
2871         ;
2872         FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2873         const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2874         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2875         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2876         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2877         ogg_page page;
2878
2879         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2880         FLAC__ASSERT(0 != encoder->private_->seek_callback);
2881
2882         /* Pre-check that client supports seeking, since we don't want the
2883          * ogg_helper code to ever have to deal with this condition.
2884          */
2885         if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2886                 return;
2887
2888         /* All this is based on intimate knowledge of the stream header
2889          * layout, but a change to the header format that would break this
2890          * would also break all streams encoded in the previous format.
2891          */
2892
2893         /**
2894          ** Write STREAMINFO stats
2895          **/
2896         simple_ogg_page__init(&page);
2897         if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2898                 simple_ogg_page__clear(&page);
2899                 return; /* state already set */
2900         }
2901
2902         /*
2903          * Write MD5 signature
2904          */
2905         {
2906                 const unsigned md5_offset =
2907                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2908                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2909                         (
2910                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2911                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2912                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2913                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2914                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2915                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2916                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2917                                 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2918                         ) / 8;
2919
2920                 if(md5_offset + 16 > (unsigned)page.body_len) {
2921                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2922                         simple_ogg_page__clear(&page);
2923                         return;
2924                 }
2925                 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2926         }
2927
2928         /*
2929          * Write total samples
2930          */
2931         {
2932                 const unsigned total_samples_byte_offset =
2933                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2934                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2935                         (
2936                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2937                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2938                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2939                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2940                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2941                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2942                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2943                                 - 4
2944                         ) / 8;
2945
2946                 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2947                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2948                         simple_ogg_page__clear(&page);
2949                         return;
2950                 }
2951                 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2952                 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2953                 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2954                 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2955                 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2956                 b[4] = (FLAC__byte)(samples & 0xFF);
2957                 memcpy(page.body + total_samples_byte_offset, b, 5);
2958         }
2959
2960         /*
2961          * Write min/max framesize
2962          */
2963         {
2964                 const unsigned min_framesize_offset =
2965                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2966                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2967                         (
2968                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2969                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2970                         ) / 8;
2971
2972                 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2973                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2974                         simple_ogg_page__clear(&page);
2975                         return;
2976                 }
2977                 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2978                 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2979                 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2980                 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2981                 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2982                 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2983                 memcpy(page.body + min_framesize_offset, b, 6);
2984         }
2985         if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2986                 simple_ogg_page__clear(&page);
2987                 return; /* state already set */
2988         }
2989         simple_ogg_page__clear(&page);
2990
2991         /*
2992          * Write seektable
2993          */
2994         if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2995                 unsigned i;
2996                 FLAC__byte *p;
2997
2998                 FLAC__format_seektable_sort(encoder->private_->seek_table);
2999
3000                 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
3001
3002                 simple_ogg_page__init(&page);
3003                 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
3004                         simple_ogg_page__clear(&page);
3005                         return; /* state already set */
3006                 }
3007
3008                 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
3009                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
3010                         simple_ogg_page__clear(&page);
3011                         return;
3012                 }
3013
3014                 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
3015                         FLAC__uint64 xx;
3016                         unsigned x;
3017                         xx = encoder->private_->seek_table->points[i].sample_number;
3018                         b[7] = (FLAC__byte)xx; xx >>= 8;
3019                         b[6] = (FLAC__byte)xx; xx >>= 8;
3020                         b[5] = (FLAC__byte)xx; xx >>= 8;
3021                         b[4] = (FLAC__byte)xx; xx >>= 8;
3022                         b[3] = (FLAC__byte)xx; xx >>= 8;
3023                         b[2] = (FLAC__byte)xx; xx >>= 8;
3024                         b[1] = (FLAC__byte)xx; xx >>= 8;
3025                         b[0] = (FLAC__byte)xx; xx >>= 8;
3026                         xx = encoder->private_->seek_table->points[i].stream_offset;
3027                         b[15] = (FLAC__byte)xx; xx >>= 8;
3028                         b[14] = (FLAC__byte)xx; xx >>= 8;
3029                         b[13] = (FLAC__byte)xx; xx >>= 8;
3030                         b[12] = (FLAC__byte)xx; xx >>= 8;
3031                         b[11] = (FLAC__byte)xx; xx >>= 8;
3032                         b[10] = (FLAC__byte)xx; xx >>= 8;
3033                         b[9] = (FLAC__byte)xx; xx >>= 8;
3034                         b[8] = (FLAC__byte)xx; xx >>= 8;
3035                         x = encoder->private_->seek_table->points[i].frame_samples;
3036                         b[17] = (FLAC__byte)x; x >>= 8;
3037                         b[16] = (FLAC__byte)x; x >>= 8;
3038                         memcpy(p, b, 18);
3039                 }
3040
3041                 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
3042                         simple_ogg_page__clear(&page);
3043                         return; /* state already set */
3044                 }
3045                 simple_ogg_page__clear(&page);
3046         }
3047 }
3048 #endif
3049
3050 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
3051 {
3052         FLAC__uint16 crc;
3053         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
3054
3055         /*
3056          * Accumulate raw signal to the MD5 signature
3057          */
3058         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)) {
3059                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3060                 return false;
3061         }
3062
3063         /*
3064          * Process the frame header and subframes into the frame bitbuffer
3065          */
3066         if(!process_subframes_(encoder, is_fractional_block)) {
3067                 /* the above function sets the state for us in case of an error */
3068                 return false;
3069         }
3070
3071         /*
3072          * Zero-pad the frame to a byte_boundary
3073          */
3074         if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
3075                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3076                 return false;
3077         }
3078
3079         /*
3080          * CRC-16 the whole thing
3081          */
3082         FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
3083         if(
3084                 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
3085                 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
3086         ) {
3087                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3088                 return false;
3089         }
3090
3091         /*
3092          * Write it
3093          */
3094         if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
3095                 /* the above function sets the state for us in case of an error */
3096                 return false;
3097         }
3098
3099         /*
3100          * Get ready for the next frame
3101          */
3102         encoder->private_->current_sample_number = 0;
3103         encoder->private_->current_frame_number++;
3104         encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
3105
3106         return true;
3107 }
3108
3109 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
3110 {
3111         FLAC__FrameHeader frame_header;
3112         unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
3113         FLAC__bool do_independent, do_mid_side;
3114
3115         /*
3116          * Calculate the min,max Rice partition orders
3117          */
3118         if(is_fractional_block) {
3119