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