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