libFLAC/stream_encoder.c : Fix MSVS profiler hot spot.
[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                 if(encoder->private_->cpuinfo.ia32.sse) {
895                         if(encoder->protected_->max_lpc_order < 4)
896                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
897                         else if(encoder->protected_->max_lpc_order < 8)
898                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
899                         else if(encoder->protected_->max_lpc_order < 12)
900                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
901                         else if(encoder->protected_->max_lpc_order < 16)
902                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_16;
903                         else
904                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
905                 }
906                 else if(encoder->private_->cpuinfo.ia32._3dnow)
907                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
908                 else
909                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
910                 if(encoder->private_->cpuinfo.ia32.mmx) {
911                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
912                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
913                 }
914                 else {
915                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
916                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
917                 }
918                 if(encoder->private_->cpuinfo.ia32.mmx && encoder->private_->cpuinfo.ia32.cmov)
919                         encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
920 #   endif /* FLAC__HAS_NASM */
921 #   ifdef FLAC__HAS_X86INTRIN
922                 if(encoder->private_->cpuinfo.ia32.sse2) {
923                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse2;
924                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_sse2;
925                 }
926 #    ifdef FLAC__SSE4_SUPPORTED
927                 if(encoder->private_->cpuinfo.ia32.sse41)
928                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_sse41;
929 #    endif
930 #   endif /* FLAC__HAS_X86INTRIN */
931 #  elif defined FLAC__CPU_X86_64
932                 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_X86_64);
933 #   ifdef FLAC__HAS_X86INTRIN
934                 if(encoder->protected_->max_lpc_order < 4)
935                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4;
936                 else if(encoder->protected_->max_lpc_order < 8)
937                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8;
938                 else if(encoder->protected_->max_lpc_order < 12)
939                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12;
940                 else if(encoder->protected_->max_lpc_order < 16)
941                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16;
942
943                 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse2;
944                 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_sse2;
945 #   endif /* FLAC__HAS_X86INTRIN */
946 #  endif /* FLAC__CPU_... */
947         }
948 # endif /* !FLAC__NO_ASM */
949 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
950 #if !defined FLAC__NO_ASM && defined FLAC__HAS_X86INTRIN
951         if(encoder->private_->cpuinfo.use_asm) {
952 # if defined FLAC__CPU_IA32
953 #  ifdef FLAC__SSSE3_SUPPORTED
954                 if(encoder->private_->cpuinfo.ia32.ssse3)
955                         encoder->private_->local_precompute_partition_info_sums = precompute_partition_info_sums_intrin_ssse3;
956                 else
957 #  endif
958                 if(encoder->private_->cpuinfo.ia32.sse2)
959                         encoder->private_->local_precompute_partition_info_sums = precompute_partition_info_sums_intrin_sse2;
960 # elif defined FLAC__CPU_X86_64
961 #  ifdef FLAC__SSSE3_SUPPORTED
962                 if(encoder->private_->cpuinfo.x86_64.ssse3)
963                         encoder->private_->local_precompute_partition_info_sums = precompute_partition_info_sums_intrin_ssse3;
964                 else
965 #  endif
966                         encoder->private_->local_precompute_partition_info_sums = precompute_partition_info_sums_intrin_sse2;
967 # endif /* FLAC__CPU_... */
968         }
969 #endif /* !FLAC__NO_ASM && FLAC__HAS_X86INTRIN */
970         /* finally override based on wide-ness if necessary */
971         if(encoder->private_->use_wide_by_block) {
972                 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
973         }
974
975         /* set state to OK; from here on, errors are fatal and we'll override the state then */
976         encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
977
978 #if FLAC__HAS_OGG
979         encoder->private_->is_ogg = is_ogg;
980         if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
981                 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
982                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
983         }
984 #endif
985
986         encoder->private_->read_callback = read_callback;
987         encoder->private_->write_callback = write_callback;
988         encoder->private_->seek_callback = seek_callback;
989         encoder->private_->tell_callback = tell_callback;
990         encoder->private_->metadata_callback = metadata_callback;
991         encoder->private_->client_data = client_data;
992
993         if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
994                 /* the above function sets the state for us in case of an error */
995                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
996         }
997
998         if(!FLAC__bitwriter_init(encoder->private_->frame)) {
999                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1000                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1001         }
1002
1003         /*
1004          * Set up the verify stuff if necessary
1005          */
1006         if(encoder->protected_->verify) {
1007                 /*
1008                  * First, set up the fifo which will hold the
1009                  * original signal to compare against
1010                  */
1011                 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
1012                 for(i = 0; i < encoder->protected_->channels; i++) {
1013                         if(0 == (encoder->private_->verify.input_fifo.data[i] = safe_malloc_mul_2op_p(sizeof(FLAC__int32), /*times*/encoder->private_->verify.input_fifo.size))) {
1014                                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1015                                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1016                         }
1017                 }
1018                 encoder->private_->verify.input_fifo.tail = 0;
1019
1020                 /*
1021                  * Now set up a stream decoder for verification
1022                  */
1023                 if(0 == encoder->private_->verify.decoder) {
1024                         encoder->private_->verify.decoder = FLAC__stream_decoder_new();
1025                         if(0 == encoder->private_->verify.decoder) {
1026                                 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1027                                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1028                         }
1029                 }
1030
1031                 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) {
1032                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1033                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1034                 }
1035         }
1036         encoder->private_->verify.error_stats.absolute_sample = 0;
1037         encoder->private_->verify.error_stats.frame_number = 0;
1038         encoder->private_->verify.error_stats.channel = 0;
1039         encoder->private_->verify.error_stats.sample = 0;
1040         encoder->private_->verify.error_stats.expected = 0;
1041         encoder->private_->verify.error_stats.got = 0;
1042
1043         /*
1044          * These must be done before we write any metadata, because that
1045          * calls the write_callback, which uses these values.
1046          */
1047         encoder->private_->first_seekpoint_to_check = 0;
1048         encoder->private_->samples_written = 0;
1049         encoder->protected_->streaminfo_offset = 0;
1050         encoder->protected_->seektable_offset = 0;
1051         encoder->protected_->audio_offset = 0;
1052
1053         /*
1054          * write the stream header
1055          */
1056         if(encoder->protected_->verify)
1057                 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1058         if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1059                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1060                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1061         }
1062         if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1063                 /* the above function sets the state for us in case of an error */
1064                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1065         }
1066
1067         /*
1068          * write the STREAMINFO metadata block
1069          */
1070         if(encoder->protected_->verify)
1071                 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1072         encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1073         encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1074         encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1075         encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1076         encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1077         encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1078         encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1079         encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1080         encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1081         encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1082         encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1083         memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1084         if(encoder->protected_->do_md5)
1085                 FLAC__MD5Init(&encoder->private_->md5context);
1086         if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1087                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1088                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1089         }
1090         if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1091                 /* the above function sets the state for us in case of an error */
1092                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1093         }
1094
1095         /*
1096          * Now that the STREAMINFO block is written, we can init this to an
1097          * absurdly-high value...
1098          */
1099         encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1100         /* ... and clear this to 0 */
1101         encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1102
1103         /*
1104          * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1105          * if not, we will write an empty one (FLAC__add_metadata_block()
1106          * automatically supplies the vendor string).
1107          *
1108          * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1109          * the STREAMINFO.  (In the case that metadata_has_vorbis_comment is
1110          * true it will have already insured that the metadata list is properly
1111          * ordered.)
1112          */
1113         if(!metadata_has_vorbis_comment) {
1114                 FLAC__StreamMetadata vorbis_comment;
1115                 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1116                 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1117                 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1118                 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1119                 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1120                 vorbis_comment.data.vorbis_comment.num_comments = 0;
1121                 vorbis_comment.data.vorbis_comment.comments = 0;
1122                 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1123                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1124                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1125                 }
1126                 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1127                         /* the above function sets the state for us in case of an error */
1128                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1129                 }
1130         }
1131
1132         /*
1133          * write the user's metadata blocks
1134          */
1135         for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1136                 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1137                 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1138                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1139                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1140                 }
1141                 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1142                         /* the above function sets the state for us in case of an error */
1143                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1144                 }
1145         }
1146
1147         /* now that all the metadata is written, we save the stream offset */
1148         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 */
1149                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1150                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1151         }
1152
1153         if(encoder->protected_->verify)
1154                 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1155
1156         return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1157 }
1158
1159 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1160         FLAC__StreamEncoder *encoder,
1161         FLAC__StreamEncoderWriteCallback write_callback,
1162         FLAC__StreamEncoderSeekCallback seek_callback,
1163         FLAC__StreamEncoderTellCallback tell_callback,
1164         FLAC__StreamEncoderMetadataCallback metadata_callback,
1165         void *client_data
1166 )
1167 {
1168         return init_stream_internal_(
1169                 encoder,
1170                 /*read_callback=*/0,
1171                 write_callback,
1172                 seek_callback,
1173                 tell_callback,
1174                 metadata_callback,
1175                 client_data,
1176                 /*is_ogg=*/false
1177         );
1178 }
1179
1180 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1181         FLAC__StreamEncoder *encoder,
1182         FLAC__StreamEncoderReadCallback read_callback,
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,
1193                 write_callback,
1194                 seek_callback,
1195                 tell_callback,
1196                 metadata_callback,
1197                 client_data,
1198                 /*is_ogg=*/true
1199         );
1200 }
1201
1202 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1203         FLAC__StreamEncoder *encoder,
1204         FILE *file,
1205         FLAC__StreamEncoderProgressCallback progress_callback,
1206         void *client_data,
1207         FLAC__bool is_ogg
1208 )
1209 {
1210         FLAC__StreamEncoderInitStatus init_status;
1211
1212         FLAC__ASSERT(0 != encoder);
1213         FLAC__ASSERT(0 != file);
1214
1215         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1216                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1217
1218         /* double protection */
1219         if(file == 0) {
1220                 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1221                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1222         }
1223
1224         /*
1225          * To make sure that our file does not go unclosed after an error, we
1226          * must assign the FILE pointer before any further error can occur in
1227          * this routine.
1228          */
1229         if(file == stdout)
1230                 file = get_binary_stdout_(); /* just to be safe */
1231
1232         encoder->private_->file = file;
1233
1234         encoder->private_->progress_callback = progress_callback;
1235         encoder->private_->bytes_written = 0;
1236         encoder->private_->samples_written = 0;
1237         encoder->private_->frames_written = 0;
1238
1239         init_status = init_stream_internal_(
1240                 encoder,
1241                 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1242                 file_write_callback_,
1243                 encoder->private_->file == stdout? 0 : file_seek_callback_,
1244                 encoder->private_->file == stdout? 0 : file_tell_callback_,
1245                 /*metadata_callback=*/0,
1246                 client_data,
1247                 is_ogg
1248         );
1249         if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1250                 /* the above function sets the state for us in case of an error */
1251                 return init_status;
1252         }
1253
1254         {
1255                 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1256
1257                 FLAC__ASSERT(blocksize != 0);
1258                 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1259         }
1260
1261         return init_status;
1262 }
1263
1264 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1265         FLAC__StreamEncoder *encoder,
1266         FILE *file,
1267         FLAC__StreamEncoderProgressCallback progress_callback,
1268         void *client_data
1269 )
1270 {
1271         return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1272 }
1273
1274 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1275         FLAC__StreamEncoder *encoder,
1276         FILE *file,
1277         FLAC__StreamEncoderProgressCallback progress_callback,
1278         void *client_data
1279 )
1280 {
1281         return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1282 }
1283
1284 static FLAC__StreamEncoderInitStatus init_file_internal_(
1285         FLAC__StreamEncoder *encoder,
1286         const char *filename,
1287         FLAC__StreamEncoderProgressCallback progress_callback,
1288         void *client_data,
1289         FLAC__bool is_ogg
1290 )
1291 {
1292         FILE *file;
1293
1294         FLAC__ASSERT(0 != encoder);
1295
1296         /*
1297          * To make sure that our file does not go unclosed after an error, we
1298          * have to do the same entrance checks here that are later performed
1299          * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1300          */
1301         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1302                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1303
1304         file = filename? flac_fopen(filename, "w+b") : stdout;
1305
1306         if(file == 0) {
1307                 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1308                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1309         }
1310
1311         return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1312 }
1313
1314 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1315         FLAC__StreamEncoder *encoder,
1316         const char *filename,
1317         FLAC__StreamEncoderProgressCallback progress_callback,
1318         void *client_data
1319 )
1320 {
1321         return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1322 }
1323
1324 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1325         FLAC__StreamEncoder *encoder,
1326         const char *filename,
1327         FLAC__StreamEncoderProgressCallback progress_callback,
1328         void *client_data
1329 )
1330 {
1331         return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1332 }
1333
1334 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1335 {
1336         FLAC__bool error = false;
1337
1338         FLAC__ASSERT(0 != encoder);
1339         FLAC__ASSERT(0 != encoder->private_);
1340         FLAC__ASSERT(0 != encoder->protected_);
1341
1342         if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1343                 return true;
1344
1345         if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1346                 if(encoder->private_->current_sample_number != 0) {
1347                         const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1348                         encoder->protected_->blocksize = encoder->private_->current_sample_number;
1349                         if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1350                                 error = true;
1351                 }
1352         }
1353
1354         if(encoder->protected_->do_md5)
1355                 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1356
1357         if(!encoder->private_->is_being_deleted) {
1358                 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1359                         if(encoder->private_->seek_callback) {
1360 #if FLAC__HAS_OGG
1361                                 if(encoder->private_->is_ogg)
1362                                         update_ogg_metadata_(encoder);
1363                                 else
1364 #endif
1365                                 update_metadata_(encoder);
1366
1367                                 /* check if an error occurred while updating metadata */
1368                                 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1369                                         error = true;
1370                         }
1371                         if(encoder->private_->metadata_callback)
1372                                 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1373                 }
1374
1375                 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1376                         if(!error)
1377                                 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1378                         error = true;
1379                 }
1380         }
1381
1382         if(0 != encoder->private_->file) {
1383                 if(encoder->private_->file != stdout)
1384                         fclose(encoder->private_->file);
1385                 encoder->private_->file = 0;
1386         }
1387
1388 #if FLAC__HAS_OGG
1389         if(encoder->private_->is_ogg)
1390                 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1391 #endif
1392
1393         free_(encoder);
1394         set_defaults_(encoder);
1395
1396         if(!error)
1397                 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1398
1399         return !error;
1400 }
1401
1402 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1403 {
1404         FLAC__ASSERT(0 != encoder);
1405         FLAC__ASSERT(0 != encoder->private_);
1406         FLAC__ASSERT(0 != encoder->protected_);
1407         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1408                 return false;
1409 #if FLAC__HAS_OGG
1410         /* can't check encoder->private_->is_ogg since that's not set until init time */
1411         FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1412         return true;
1413 #else
1414         (void)value;
1415         return false;
1416 #endif
1417 }
1418
1419 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1420 {
1421         FLAC__ASSERT(0 != encoder);
1422         FLAC__ASSERT(0 != encoder->private_);
1423         FLAC__ASSERT(0 != encoder->protected_);
1424         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1425                 return false;
1426 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1427         encoder->protected_->verify = value;
1428 #endif
1429         return true;
1430 }
1431
1432 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1433 {
1434         FLAC__ASSERT(0 != encoder);
1435         FLAC__ASSERT(0 != encoder->private_);
1436         FLAC__ASSERT(0 != encoder->protected_);
1437         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1438                 return false;
1439         encoder->protected_->streamable_subset = value;
1440         return true;
1441 }
1442
1443 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
1444 {
1445         FLAC__ASSERT(0 != encoder);
1446         FLAC__ASSERT(0 != encoder->private_);
1447         FLAC__ASSERT(0 != encoder->protected_);
1448         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1449                 return false;
1450         encoder->protected_->do_md5 = value;
1451         return true;
1452 }
1453
1454 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned 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_->channels = value;
1462         return true;
1463 }
1464
1465 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned 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_->bits_per_sample = value;
1473         return true;
1474 }
1475
1476 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(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_->sample_rate = value;
1484         return true;
1485 }
1486
1487 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1488 {
1489         FLAC__bool ok = true;
1490         FLAC__ASSERT(0 != encoder);
1491         FLAC__ASSERT(0 != encoder->private_);
1492         FLAC__ASSERT(0 != encoder->protected_);
1493         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1494                 return false;
1495         if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1496                 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1497         ok &= FLAC__stream_encoder_set_do_mid_side_stereo          (encoder, compression_levels_[value].do_mid_side_stereo);
1498         ok &= FLAC__stream_encoder_set_loose_mid_side_stereo       (encoder, compression_levels_[value].loose_mid_side_stereo);
1499 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1500 #if 0
1501         /* was: */
1502         ok &= FLAC__stream_encoder_set_apodization                 (encoder, compression_levels_[value].apodization);
1503         /* but it's too hard to specify the string in a locale-specific way */
1504 #else
1505         encoder->protected_->num_apodizations = 1;
1506         encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1507         encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1508 #endif
1509 #endif
1510         ok &= FLAC__stream_encoder_set_max_lpc_order               (encoder, compression_levels_[value].max_lpc_order);
1511         ok &= FLAC__stream_encoder_set_qlp_coeff_precision         (encoder, compression_levels_[value].qlp_coeff_precision);
1512         ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search    (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1513         ok &= FLAC__stream_encoder_set_do_escape_coding            (encoder, compression_levels_[value].do_escape_coding);
1514         ok &= FLAC__stream_encoder_set_do_exhaustive_model_search  (encoder, compression_levels_[value].do_exhaustive_model_search);
1515         ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1516         ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1517         ok &= FLAC__stream_encoder_set_rice_parameter_search_dist  (encoder, compression_levels_[value].rice_parameter_search_dist);
1518         return ok;
1519 }
1520
1521 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1522 {
1523         FLAC__ASSERT(0 != encoder);
1524         FLAC__ASSERT(0 != encoder->private_);
1525         FLAC__ASSERT(0 != encoder->protected_);
1526         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1527                 return false;
1528         encoder->protected_->blocksize = value;
1529         return true;
1530 }
1531
1532 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1533 {
1534         FLAC__ASSERT(0 != encoder);
1535         FLAC__ASSERT(0 != encoder->private_);
1536         FLAC__ASSERT(0 != encoder->protected_);
1537         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1538                 return false;
1539         encoder->protected_->do_mid_side_stereo = value;
1540         return true;
1541 }
1542
1543 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool 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_->loose_mid_side_stereo = value;
1551         return true;
1552 }
1553
1554 /*@@@@add to tests*/
1555 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1556 {
1557         FLAC__ASSERT(0 != encoder);
1558         FLAC__ASSERT(0 != encoder->private_);
1559         FLAC__ASSERT(0 != encoder->protected_);
1560         FLAC__ASSERT(0 != specification);
1561         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1562                 return false;
1563 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1564         (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1565 #else
1566         encoder->protected_->num_apodizations = 0;
1567         while(1) {
1568                 const char *s = strchr(specification, ';');
1569                 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1570                 if     (n==8  && 0 == strncmp("bartlett"     , specification, n))
1571                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1572                 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1573                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1574                 else if(n==8  && 0 == strncmp("blackman"     , specification, n))
1575                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1576                 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1577                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1578                 else if(n==6  && 0 == strncmp("connes"       , specification, n))
1579                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1580                 else if(n==7  && 0 == strncmp("flattop"      , specification, n))
1581                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1582                 else if(n>7   && 0 == strncmp("gauss("       , specification, 6)) {
1583                         FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1584                         if (stddev > 0.0 && stddev <= 0.5) {
1585                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1586                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1587                         }
1588                 }
1589                 else if(n==7  && 0 == strncmp("hamming"      , specification, n))
1590                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1591                 else if(n==4  && 0 == strncmp("hann"         , specification, n))
1592                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1593                 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1594                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1595                 else if(n==7  && 0 == strncmp("nuttall"      , specification, n))
1596                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1597                 else if(n==9  && 0 == strncmp("rectangle"    , specification, n))
1598                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1599                 else if(n==8  && 0 == strncmp("triangle"     , specification, n))
1600                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1601                 else if(n>7   && 0 == strncmp("tukey("       , specification, 6)) {
1602                         FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1603                         if (p >= 0.0 && p <= 1.0) {
1604                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1605                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1606                         }
1607                 }
1608                 else if(n==5  && 0 == strncmp("welch"        , specification, n))
1609                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1610                 if (encoder->protected_->num_apodizations == 32)
1611                         break;
1612                 if (s)
1613                         specification = s+1;
1614                 else
1615                         break;
1616         }
1617         if(encoder->protected_->num_apodizations == 0) {
1618                 encoder->protected_->num_apodizations = 1;
1619                 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1620                 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1621         }
1622 #endif
1623         return true;
1624 }
1625
1626 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1627 {
1628         FLAC__ASSERT(0 != encoder);
1629         FLAC__ASSERT(0 != encoder->private_);
1630         FLAC__ASSERT(0 != encoder->protected_);
1631         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1632                 return false;
1633         encoder->protected_->max_lpc_order = value;
1634         return true;
1635 }
1636
1637 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1638 {
1639         FLAC__ASSERT(0 != encoder);
1640         FLAC__ASSERT(0 != encoder->private_);
1641         FLAC__ASSERT(0 != encoder->protected_);
1642         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1643                 return false;
1644         encoder->protected_->qlp_coeff_precision = value;
1645         return true;
1646 }
1647
1648 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool 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_->do_qlp_coeff_prec_search = value;
1656         return true;
1657 }
1658
1659 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool 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 #if 0
1667         /*@@@ deprecated: */
1668         encoder->protected_->do_escape_coding = value;
1669 #else
1670         (void)value;
1671 #endif
1672         return true;
1673 }
1674
1675 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1676 {
1677         FLAC__ASSERT(0 != encoder);
1678         FLAC__ASSERT(0 != encoder->private_);
1679         FLAC__ASSERT(0 != encoder->protected_);
1680         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1681                 return false;
1682         encoder->protected_->do_exhaustive_model_search = value;
1683         return true;
1684 }
1685
1686 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1687 {
1688         FLAC__ASSERT(0 != encoder);
1689         FLAC__ASSERT(0 != encoder->private_);
1690         FLAC__ASSERT(0 != encoder->protected_);
1691         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1692                 return false;
1693         encoder->protected_->min_residual_partition_order = value;
1694         return true;
1695 }
1696
1697 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned 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_->max_residual_partition_order = value;
1705         return true;
1706 }
1707
1708 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(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 #if 0
1716         /*@@@ deprecated: */
1717         encoder->protected_->rice_parameter_search_dist = value;
1718 #else
1719         (void)value;
1720 #endif
1721         return true;
1722 }
1723
1724 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1725 {
1726         FLAC__ASSERT(0 != encoder);
1727         FLAC__ASSERT(0 != encoder->private_);
1728         FLAC__ASSERT(0 != encoder->protected_);
1729         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1730                 return false;
1731         encoder->protected_->total_samples_estimate = value;
1732         return true;
1733 }
1734
1735 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1736 {
1737         FLAC__ASSERT(0 != encoder);
1738         FLAC__ASSERT(0 != encoder->private_);
1739         FLAC__ASSERT(0 != encoder->protected_);
1740         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1741                 return false;
1742         if(0 == metadata)
1743                 num_blocks = 0;
1744         if(0 == num_blocks)
1745                 metadata = 0;
1746         /* realloc() does not do exactly what we want so... */
1747         if(encoder->protected_->metadata) {
1748                 free(encoder->protected_->metadata);
1749                 encoder->protected_->metadata = 0;
1750                 encoder->protected_->num_metadata_blocks = 0;
1751         }
1752         if(num_blocks) {
1753                 FLAC__StreamMetadata **m;
1754                 if(0 == (m = safe_malloc_mul_2op_p(sizeof(m[0]), /*times*/num_blocks)))
1755                         return false;
1756                 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1757                 encoder->protected_->metadata = m;
1758                 encoder->protected_->num_metadata_blocks = num_blocks;
1759         }
1760 #if FLAC__HAS_OGG
1761         if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1762                 return false;
1763 #endif
1764         return true;
1765 }
1766
1767 /*
1768  * These three functions are not static, but not publically exposed in
1769  * include/FLAC/ either.  They are used by the test suite.
1770  */
1771 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1772 {
1773         FLAC__ASSERT(0 != encoder);
1774         FLAC__ASSERT(0 != encoder->private_);
1775         FLAC__ASSERT(0 != encoder->protected_);
1776         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1777                 return false;
1778         encoder->private_->disable_constant_subframes = value;
1779         return true;
1780 }
1781
1782 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1783 {
1784         FLAC__ASSERT(0 != encoder);
1785         FLAC__ASSERT(0 != encoder->private_);
1786         FLAC__ASSERT(0 != encoder->protected_);
1787         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1788                 return false;
1789         encoder->private_->disable_fixed_subframes = value;
1790         return true;
1791 }
1792
1793 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_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_verbatim_subframes = value;
1801         return true;
1802 }
1803
1804 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1805 {
1806         FLAC__ASSERT(0 != encoder);
1807         FLAC__ASSERT(0 != encoder->private_);
1808         FLAC__ASSERT(0 != encoder->protected_);
1809         return encoder->protected_->state;
1810 }
1811
1812 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1813 {
1814         FLAC__ASSERT(0 != encoder);
1815         FLAC__ASSERT(0 != encoder->private_);
1816         FLAC__ASSERT(0 != encoder->protected_);
1817         if(encoder->protected_->verify)
1818                 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1819         else
1820                 return FLAC__STREAM_DECODER_UNINITIALIZED;
1821 }
1822
1823 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1824 {
1825         FLAC__ASSERT(0 != encoder);
1826         FLAC__ASSERT(0 != encoder->private_);
1827         FLAC__ASSERT(0 != encoder->protected_);
1828         if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1829                 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1830         else
1831                 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1832 }
1833
1834 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)
1835 {
1836         FLAC__ASSERT(0 != encoder);
1837         FLAC__ASSERT(0 != encoder->private_);
1838         FLAC__ASSERT(0 != encoder->protected_);
1839         if(0 != absolute_sample)
1840                 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1841         if(0 != frame_number)
1842                 *frame_number = encoder->private_->verify.error_stats.frame_number;
1843         if(0 != channel)
1844                 *channel = encoder->private_->verify.error_stats.channel;
1845         if(0 != sample)
1846                 *sample = encoder->private_->verify.error_stats.sample;
1847         if(0 != expected)
1848                 *expected = encoder->private_->verify.error_stats.expected;
1849         if(0 != got)
1850                 *got = encoder->private_->verify.error_stats.got;
1851 }
1852
1853 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1854 {
1855         FLAC__ASSERT(0 != encoder);
1856         FLAC__ASSERT(0 != encoder->private_);
1857         FLAC__ASSERT(0 != encoder->protected_);
1858         return encoder->protected_->verify;
1859 }
1860
1861 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1862 {
1863         FLAC__ASSERT(0 != encoder);
1864         FLAC__ASSERT(0 != encoder->private_);
1865         FLAC__ASSERT(0 != encoder->protected_);
1866         return encoder->protected_->streamable_subset;
1867 }
1868
1869 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
1870 {
1871         FLAC__ASSERT(0 != encoder);
1872         FLAC__ASSERT(0 != encoder->private_);
1873         FLAC__ASSERT(0 != encoder->protected_);
1874         return encoder->protected_->do_md5;
1875 }
1876
1877 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1878 {
1879         FLAC__ASSERT(0 != encoder);
1880         FLAC__ASSERT(0 != encoder->private_);
1881         FLAC__ASSERT(0 != encoder->protected_);
1882         return encoder->protected_->channels;
1883 }
1884
1885 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1886 {
1887         FLAC__ASSERT(0 != encoder);
1888         FLAC__ASSERT(0 != encoder->private_);
1889         FLAC__ASSERT(0 != encoder->protected_);
1890         return encoder->protected_->bits_per_sample;
1891 }
1892
1893 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1894 {
1895         FLAC__ASSERT(0 != encoder);
1896         FLAC__ASSERT(0 != encoder->private_);
1897         FLAC__ASSERT(0 != encoder->protected_);
1898         return encoder->protected_->sample_rate;
1899 }
1900
1901 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1902 {
1903         FLAC__ASSERT(0 != encoder);
1904         FLAC__ASSERT(0 != encoder->private_);
1905         FLAC__ASSERT(0 != encoder->protected_);
1906         return encoder->protected_->blocksize;
1907 }
1908
1909 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1910 {
1911         FLAC__ASSERT(0 != encoder);
1912         FLAC__ASSERT(0 != encoder->private_);
1913         FLAC__ASSERT(0 != encoder->protected_);
1914         return encoder->protected_->do_mid_side_stereo;
1915 }
1916
1917 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1918 {
1919         FLAC__ASSERT(0 != encoder);
1920         FLAC__ASSERT(0 != encoder->private_);
1921         FLAC__ASSERT(0 != encoder->protected_);
1922         return encoder->protected_->loose_mid_side_stereo;
1923 }
1924
1925 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1926 {
1927         FLAC__ASSERT(0 != encoder);
1928         FLAC__ASSERT(0 != encoder->private_);
1929         FLAC__ASSERT(0 != encoder->protected_);
1930         return encoder->protected_->max_lpc_order;
1931 }
1932
1933 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1934 {
1935         FLAC__ASSERT(0 != encoder);
1936         FLAC__ASSERT(0 != encoder->private_);
1937         FLAC__ASSERT(0 != encoder->protected_);
1938         return encoder->protected_->qlp_coeff_precision;
1939 }
1940
1941 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1942 {
1943         FLAC__ASSERT(0 != encoder);
1944         FLAC__ASSERT(0 != encoder->private_);
1945         FLAC__ASSERT(0 != encoder->protected_);
1946         return encoder->protected_->do_qlp_coeff_prec_search;
1947 }
1948
1949 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1950 {
1951         FLAC__ASSERT(0 != encoder);
1952         FLAC__ASSERT(0 != encoder->private_);
1953         FLAC__ASSERT(0 != encoder->protected_);
1954         return encoder->protected_->do_escape_coding;
1955 }
1956
1957 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1958 {
1959         FLAC__ASSERT(0 != encoder);
1960         FLAC__ASSERT(0 != encoder->private_);
1961         FLAC__ASSERT(0 != encoder->protected_);
1962         return encoder->protected_->do_exhaustive_model_search;
1963 }
1964
1965 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1966 {
1967         FLAC__ASSERT(0 != encoder);
1968         FLAC__ASSERT(0 != encoder->private_);
1969         FLAC__ASSERT(0 != encoder->protected_);
1970         return encoder->protected_->min_residual_partition_order;
1971 }
1972
1973 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1974 {
1975         FLAC__ASSERT(0 != encoder);
1976         FLAC__ASSERT(0 != encoder->private_);
1977         FLAC__ASSERT(0 != encoder->protected_);
1978         return encoder->protected_->max_residual_partition_order;
1979 }
1980
1981 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1982 {
1983         FLAC__ASSERT(0 != encoder);
1984         FLAC__ASSERT(0 != encoder->private_);
1985         FLAC__ASSERT(0 != encoder->protected_);
1986         return encoder->protected_->rice_parameter_search_dist;
1987 }
1988
1989 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1990 {
1991         FLAC__ASSERT(0 != encoder);
1992         FLAC__ASSERT(0 != encoder->private_);
1993         FLAC__ASSERT(0 != encoder->protected_);
1994         return encoder->protected_->total_samples_estimate;
1995 }
1996
1997 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1998 {
1999         unsigned i, j = 0, channel;
2000         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2001
2002         FLAC__ASSERT(0 != encoder);
2003         FLAC__ASSERT(0 != encoder->private_);
2004         FLAC__ASSERT(0 != encoder->protected_);
2005         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2006
2007         do {
2008                 const unsigned n = flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
2009
2010                 if(encoder->protected_->verify)
2011                         append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
2012
2013                 for(channel = 0; channel < channels; channel++)
2014                         memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
2015
2016                 if(encoder->protected_->do_mid_side_stereo) {
2017                         FLAC__ASSERT(channels == 2);
2018                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2019                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2020                                 encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
2021                                 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' ! */
2022                         }
2023                 }
2024                 else
2025                         j += n;
2026
2027                 encoder->private_->current_sample_number += n;
2028
2029                 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2030                 if(encoder->private_->current_sample_number > blocksize) {
2031                         FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
2032                         FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2033                         if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2034                                 return false;
2035                         /* move unprocessed overread samples to beginnings of arrays */
2036                         for(channel = 0; channel < channels; channel++)
2037                                 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2038                         if(encoder->protected_->do_mid_side_stereo) {
2039                                 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2040                                 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2041                         }
2042                         encoder->private_->current_sample_number = 1;
2043                 }
2044         } while(j < samples);
2045
2046         return true;
2047 }
2048
2049 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2050 {
2051         unsigned i, j, k, channel;
2052         FLAC__int32 x, mid, side;
2053         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2054
2055         FLAC__ASSERT(0 != encoder);
2056         FLAC__ASSERT(0 != encoder->private_);
2057         FLAC__ASSERT(0 != encoder->protected_);
2058         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2059
2060         j = k = 0;
2061         /*
2062          * we have several flavors of the same basic loop, optimized for
2063          * different conditions:
2064          */
2065         if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2066                 /*
2067                  * stereo coding: unroll channel loop
2068                  */
2069                 do {
2070                         if(encoder->protected_->verify)
2071                                 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2072
2073                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2074                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2075                                 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2076                                 x = buffer[k++];
2077                                 encoder->private_->integer_signal[1][i] = x;
2078                                 mid += x;
2079                                 side -= x;
2080                                 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2081                                 encoder->private_->integer_signal_mid_side[1][i] = side;
2082                                 encoder->private_->integer_signal_mid_side[0][i] = mid;
2083                         }
2084                         encoder->private_->current_sample_number = i;
2085                         /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2086                         if(i > blocksize) {
2087                                 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2088                                         return false;
2089                                 /* move unprocessed overread samples to beginnings of arrays */
2090                                 FLAC__ASSERT(i == blocksize+OVERREAD_);
2091                                 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2092                                 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
2093                                 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
2094                                 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2095                                 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2096                                 encoder->private_->current_sample_number = 1;
2097                         }
2098                 } while(j < samples);
2099         }
2100         else {
2101                 /*
2102                  * independent channel coding: buffer each channel in inner loop
2103                  */
2104                 do {
2105                         if(encoder->protected_->verify)
2106                                 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2107
2108                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2109                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2110                                 for(channel = 0; channel < channels; channel++)
2111                                         encoder->private_->integer_signal[channel][i] = buffer[k++];
2112                         }
2113                         encoder->private_->current_sample_number = i;
2114                         /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2115                         if(i > blocksize) {
2116                                 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2117                                         return false;
2118                                 /* move unprocessed overread samples to beginnings of arrays */
2119                                 FLAC__ASSERT(i == blocksize+OVERREAD_);
2120                                 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2121                                 for(channel = 0; channel < channels; channel++)
2122                                         encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2123                                 encoder->private_->current_sample_number = 1;
2124                         }
2125                 } while(j < samples);
2126         }
2127
2128         return true;
2129 }
2130
2131 /***********************************************************************
2132  *
2133  * Private class methods
2134  *
2135  ***********************************************************************/
2136
2137 void set_defaults_(FLAC__StreamEncoder *encoder)
2138 {
2139         FLAC__ASSERT(0 != encoder);
2140
2141 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2142         encoder->protected_->verify = true;
2143 #else
2144         encoder->protected_->verify = false;
2145 #endif
2146         encoder->protected_->streamable_subset = true;
2147         encoder->protected_->do_md5 = true;
2148         encoder->protected_->do_mid_side_stereo = false;
2149         encoder->protected_->loose_mid_side_stereo = false;
2150         encoder->protected_->channels = 2;
2151         encoder->protected_->bits_per_sample = 16;
2152         encoder->protected_->sample_rate = 44100;
2153         encoder->protected_->blocksize = 0;
2154 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2155         encoder->protected_->num_apodizations = 1;
2156         encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2157         encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2158 #endif
2159         encoder->protected_->max_lpc_order = 0;
2160         encoder->protected_->qlp_coeff_precision = 0;
2161         encoder->protected_->do_qlp_coeff_prec_search = false;
2162         encoder->protected_->do_exhaustive_model_search = false;
2163         encoder->protected_->do_escape_coding = false;
2164         encoder->protected_->min_residual_partition_order = 0;
2165         encoder->protected_->max_residual_partition_order = 0;
2166         encoder->protected_->rice_parameter_search_dist = 0;
2167         encoder->protected_->total_samples_estimate = 0;
2168         encoder->protected_->metadata = 0;
2169         encoder->protected_->num_metadata_blocks = 0;
2170
2171         encoder->private_->seek_table = 0;
2172         encoder->private_->disable_constant_subframes = false;
2173         encoder->private_->disable_fixed_subframes = false;
2174         encoder->private_->disable_verbatim_subframes = false;
2175 #if FLAC__HAS_OGG
2176         encoder->private_->is_ogg = false;
2177 #endif
2178         encoder->private_->read_callback = 0;
2179         encoder->private_->write_callback = 0;
2180         encoder->private_->seek_callback = 0;
2181         encoder->private_->tell_callback = 0;
2182         encoder->private_->metadata_callback = 0;
2183         encoder->private_->progress_callback = 0;
2184         encoder->private_->client_data = 0;
2185
2186 #if FLAC__HAS_OGG
2187         FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2188 #endif
2189
2190         FLAC__stream_encoder_set_compression_level(encoder, 5);
2191 }
2192
2193 void free_(FLAC__StreamEncoder *encoder)
2194 {
2195         unsigned i, channel;
2196
2197         FLAC__ASSERT(0 != encoder);
2198         if(encoder->protected_->metadata) {
2199                 free(encoder->protected_->metadata);
2200                 encoder->protected_->metadata = 0;
2201                 encoder->protected_->num_metadata_blocks = 0;
2202         }
2203         for(i = 0; i < encoder->protected_->channels; i++) {
2204                 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2205                         free(encoder->private_->integer_signal_unaligned[i]);
2206                         encoder->private_->integer_signal_unaligned[i] = 0;
2207                 }
2208 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2209                 if(0 != encoder->private_->real_signal_unaligned[i]) {
2210                         free(encoder->private_->real_signal_unaligned[i]);
2211                         encoder->private_->real_signal_unaligned[i] = 0;
2212                 }
2213 #endif
2214         }
2215         for(i = 0; i < 2; i++) {
2216                 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2217                         free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2218                         encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2219                 }
2220 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2221                 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2222                         free(encoder->private_->real_signal_mid_side_unaligned[i]);
2223                         encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2224                 }
2225 #endif
2226         }
2227 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2228         for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2229                 if(0 != encoder->private_->window_unaligned[i]) {
2230                         free(encoder->private_->window_unaligned[i]);
2231                         encoder->private_->window_unaligned[i] = 0;
2232                 }
2233         }
2234         if(0 != encoder->private_->windowed_signal_unaligned) {
2235                 free(encoder->private_->windowed_signal_unaligned);
2236                 encoder->private_->windowed_signal_unaligned = 0;
2237         }
2238 #endif
2239         for(channel = 0; channel < encoder->protected_->channels; channel++) {
2240                 for(i = 0; i < 2; i++) {
2241                         if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2242                                 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2243                                 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2244                         }
2245                 }
2246         }
2247         for(channel = 0; channel < 2; channel++) {
2248                 for(i = 0; i < 2; i++) {
2249                         if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2250                                 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2251                                 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2252                         }
2253                 }
2254         }
2255         if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2256                 free(encoder->private_->abs_residual_partition_sums_unaligned);
2257                 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2258         }
2259         if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2260                 free(encoder->private_->raw_bits_per_partition_unaligned);
2261                 encoder->private_->raw_bits_per_partition_unaligned = 0;
2262         }
2263         if(encoder->protected_->verify) {
2264                 for(i = 0; i < encoder->protected_->channels; i++) {
2265                         if(0 != encoder->private_->verify.input_fifo.data[i]) {
2266                                 free(encoder->private_->verify.input_fifo.data[i]);
2267                                 encoder->private_->verify.input_fifo.data[i] = 0;
2268                         }
2269                 }
2270         }
2271         FLAC__bitwriter_free(encoder->private_->frame);
2272 }
2273
2274 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2275 {
2276         FLAC__bool ok;
2277         unsigned i, channel;
2278
2279         FLAC__ASSERT(new_blocksize > 0);
2280         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2281         FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2282
2283         /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2284         if(new_blocksize <= encoder->private_->input_capacity)
2285                 return true;
2286
2287         ok = true;
2288
2289         /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx() and ..._intrin_sse2()
2290          * require that the input arrays (in our case the integer signals)
2291          * have a buffer of up to 3 zeroes in front (at negative indices) for
2292          * alignment purposes; we use 4 in front to keep the data well-aligned.
2293          */
2294
2295         for(i = 0; ok && i < encoder->protected_->channels; i++) {
2296                 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2297                 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2298                 encoder->private_->integer_signal[i] += 4;
2299 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2300 #if 0 /* @@@ currently unused */
2301                 if(encoder->protected_->max_lpc_order > 0)
2302                         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2303 #endif
2304 #endif
2305         }
2306         for(i = 0; ok && i < 2; i++) {
2307                 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]);
2308                 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2309                 encoder->private_->integer_signal_mid_side[i] += 4;
2310 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2311 #if 0 /* @@@ currently unused */
2312                 if(encoder->protected_->max_lpc_order > 0)
2313                         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]);
2314 #endif
2315 #endif
2316         }
2317 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2318         if(ok && encoder->protected_->max_lpc_order > 0) {
2319                 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2320                         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2321                 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2322         }
2323 #endif
2324         for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2325                 for(i = 0; ok && i < 2; i++) {
2326                         ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2327                 }
2328         }
2329         for(channel = 0; ok && channel < 2; channel++) {
2330                 for(i = 0; ok && i < 2; i++) {
2331                         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]);
2332                 }
2333         }
2334         /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2335         /*@@@ 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) */
2336         ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2337         if(encoder->protected_->do_escape_coding)
2338                 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2339
2340         /* now adjust the windows if the blocksize has changed */
2341 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2342         if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2343                 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2344                         switch(encoder->protected_->apodizations[i].type) {
2345                                 case FLAC__APODIZATION_BARTLETT:
2346                                         FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2347                                         break;
2348                                 case FLAC__APODIZATION_BARTLETT_HANN:
2349                                         FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2350                                         break;
2351                                 case FLAC__APODIZATION_BLACKMAN:
2352                                         FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2353                                         break;
2354                                 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2355                                         FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2356                                         break;
2357                                 case FLAC__APODIZATION_CONNES:
2358                                         FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2359                                         break;
2360                                 case FLAC__APODIZATION_FLATTOP:
2361                                         FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2362                                         break;
2363                                 case FLAC__APODIZATION_GAUSS:
2364                                         FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2365                                         break;
2366                                 case FLAC__APODIZATION_HAMMING:
2367                                         FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2368                                         break;
2369                                 case FLAC__APODIZATION_HANN:
2370                                         FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2371                                         break;
2372                                 case FLAC__APODIZATION_KAISER_BESSEL:
2373                                         FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2374                                         break;
2375                                 case FLAC__APODIZATION_NUTTALL:
2376                                         FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2377                                         break;
2378                                 case FLAC__APODIZATION_RECTANGLE:
2379                                         FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2380                                         break;
2381                                 case FLAC__APODIZATION_TRIANGLE:
2382                                         FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2383                                         break;
2384                                 case FLAC__APODIZATION_TUKEY:
2385                                         FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2386                                         break;
2387                                 case FLAC__APODIZATION_WELCH:
2388                                         FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2389                                         break;
2390                                 default:
2391                                         FLAC__ASSERT(0);
2392                                         /* double protection */
2393                                         FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2394                                         break;
2395                         }
2396                 }
2397         }
2398 #endif
2399
2400         if(ok)
2401                 encoder->private_->input_capacity = new_blocksize;
2402         else
2403                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2404
2405         return ok;
2406 }
2407
2408 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2409 {
2410         const FLAC__byte *buffer;
2411         size_t bytes;
2412
2413         FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2414
2415         if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2416                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2417                 return false;
2418         }
2419
2420         if(encoder->protected_->verify) {
2421                 encoder->private_->verify.output.data = buffer;
2422                 encoder->private_->verify.output.bytes = bytes;
2423                 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2424                         encoder->private_->verify.needs_magic_hack = true;
2425                 }
2426                 else {
2427                         if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2428                                 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2429                                 FLAC__bitwriter_clear(encoder->private_->frame);
2430                                 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2431                                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2432                                 return false;
2433                         }
2434                 }
2435         }
2436
2437         if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2438                 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2439                 FLAC__bitwriter_clear(encoder->private_->frame);
2440                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2441                 return false;
2442         }
2443
2444         FLAC__bitwriter_release_buffer(encoder->private_->frame);
2445         FLAC__bitwriter_clear(encoder->private_->frame);
2446
2447         if(samples > 0) {
2448                 encoder->private_->streaminfo.data.stream_info.min_framesize = flac_min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2449                 encoder->private_->streaminfo.data.stream_info.max_framesize = flac_max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2450         }
2451
2452         return true;
2453 }
2454
2455 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2456 {
2457         FLAC__StreamEncoderWriteStatus status;
2458         FLAC__uint64 output_position = 0;
2459
2460 #if FLAC__HAS_OGG == 0
2461         (void)is_last_block;
2462 #endif
2463
2464         /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2465         if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2466                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2467                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2468         }
2469
2470         /*
2471          * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2472          */
2473         if(samples == 0) {
2474                 FLAC__MetadataType type = (buffer[0] & 0x7f);
2475                 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2476                         encoder->protected_->streaminfo_offset = output_position;
2477                 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2478                         encoder->protected_->seektable_offset = output_position;
2479         }
2480
2481         /*
2482          * Mark the current seek point if hit (if audio_offset == 0 that
2483          * means we're still writing metadata and haven't hit the first
2484          * frame yet)
2485          */
2486         if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2487                 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2488                 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2489                 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2490                 FLAC__uint64 test_sample;
2491                 unsigned i;
2492                 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2493                         test_sample = encoder->private_->seek_table->points[i].sample_number;
2494                         if(test_sample > frame_last_sample) {
2495                                 break;
2496                         }
2497                         else if(test_sample >= frame_first_sample) {
2498                                 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2499                                 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2500                                 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2501                                 encoder->private_->first_seekpoint_to_check++;
2502                                 /* DO NOT: "break;" and here's why:
2503                                  * The seektable template may contain more than one target
2504                                  * sample for any given frame; we will keep looping, generating
2505                                  * duplicate seekpoints for them, and we'll clean it up later,
2506                                  * just before writing the seektable back to the metadata.
2507                                  */
2508                         }
2509                         else {
2510                                 encoder->private_->first_seekpoint_to_check++;
2511                         }
2512                 }
2513         }
2514
2515 #if FLAC__HAS_OGG
2516         if(encoder->private_->is_ogg) {
2517                 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2518                         &encoder->protected_->ogg_encoder_aspect,
2519                         buffer,
2520                         bytes,
2521                         samples,
2522                         encoder->private_->current_frame_number,
2523                         is_last_block,
2524                         (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2525                         encoder,
2526                         encoder->private_->client_data
2527                 );
2528         }
2529         else
2530 #endif
2531         status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2532
2533         if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2534                 encoder->private_->bytes_written += bytes;
2535                 encoder->private_->samples_written += samples;
2536                 /* we keep a high watermark on the number of frames written because
2537                  * when the encoder goes back to write metadata, 'current_frame'
2538                  * will drop back to 0.
2539                  */
2540                 encoder->private_->frames_written = flac_max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2541         }
2542         else
2543                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2544
2545         return status;
2546 }
2547
2548 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2549 void update_metadata_(const FLAC__StreamEncoder *encoder)
2550 {
2551         FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2552         const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2553         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2554         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2555         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2556         const unsigned bps = metadata->data.stream_info.bits_per_sample;
2557         FLAC__StreamEncoderSeekStatus seek_status;
2558
2559         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2560
2561         /* All this is based on intimate knowledge of the stream header
2562          * layout, but a change to the header format that would break this
2563          * would also break all streams encoded in the previous format.
2564          */
2565
2566         /*
2567          * Write MD5 signature
2568          */
2569         {
2570                 const unsigned md5_offset =
2571                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2572                         (
2573                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2574                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2575                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2576                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2577                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2578                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2579                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2580                                 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2581                         ) / 8;
2582
2583                 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2584                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2585                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2586                         return;
2587                 }
2588                 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2589                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2590                         return;
2591                 }
2592         }
2593
2594         /*
2595          * Write total samples
2596          */
2597         {
2598                 const unsigned total_samples_byte_offset =
2599                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2600                         (
2601                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2602                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2603                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2604                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2605                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2606                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2607                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2608                                 - 4
2609                         ) / 8;
2610
2611                 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2612                 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2613                 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2614                 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2615                 b[4] = (FLAC__byte)(samples & 0xFF);
2616                 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) {
2617                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2618                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2619                         return;
2620                 }
2621                 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2622                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2623                         return;
2624                 }
2625         }
2626
2627         /*
2628          * Write min/max framesize
2629          */
2630         {
2631                 const unsigned min_framesize_offset =
2632                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2633                         (
2634                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2635                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2636                         ) / 8;
2637
2638                 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2639                 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2640                 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2641                 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2642                 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2643                 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2644                 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) {
2645                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2646                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2647                         return;
2648                 }
2649                 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2650                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2651                         return;
2652                 }
2653         }
2654
2655         /*
2656          * Write seektable
2657          */
2658         if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2659                 unsigned i;
2660
2661                 FLAC__format_seektable_sort(encoder->private_->seek_table);
2662
2663                 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2664
2665                 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) {
2666                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2667                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2668                         return;
2669                 }
2670
2671                 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2672                         FLAC__uint64 xx;
2673                         unsigned x;
2674                         xx = encoder->private_->seek_table->points[i].sample_number;
2675                         b[7] = (FLAC__byte)xx; xx >>= 8;
2676                         b[6] = (FLAC__byte)xx; xx >>= 8;
2677                         b[5] = (FLAC__byte)xx; xx >>= 8;
2678                         b[4] = (FLAC__byte)xx; xx >>= 8;
2679                         b[3] = (FLAC__byte)xx; xx >>= 8;
2680                         b[2] = (FLAC__byte)xx; xx >>= 8;
2681                         b[1] = (FLAC__byte)xx; xx >>= 8;
2682                         b[0] = (FLAC__byte)xx; xx >>= 8;
2683                         xx = encoder->private_->seek_table->points[i].stream_offset;
2684                         b[15] = (FLAC__byte)xx; xx >>= 8;
2685                         b[14] = (FLAC__byte)xx; xx >>= 8;
2686                         b[13] = (FLAC__byte)xx; xx >>= 8;
2687                         b[12] = (FLAC__byte)xx; xx >>= 8;
2688                         b[11] = (FLAC__byte)xx; xx >>= 8;
2689                         b[10] = (FLAC__byte)xx; xx >>= 8;
2690                         b[9] = (FLAC__byte)xx; xx >>= 8;
2691                         b[8] = (FLAC__byte)xx; xx >>= 8;
2692                         x = encoder->private_->seek_table->points[i].frame_samples;
2693                         b[17] = (FLAC__byte)x; x >>= 8;
2694                         b[16] = (FLAC__byte)x; x >>= 8;
2695                         if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2696                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2697                                 return;
2698                         }
2699                 }
2700         }
2701 }
2702
2703 #if FLAC__HAS_OGG
2704 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2705 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2706 {
2707         /* the # of bytes in the 1st packet that precede the STREAMINFO */
2708         static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2709                 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2710                 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2711                 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2712                 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2713                 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2714                 FLAC__STREAM_SYNC_LENGTH
2715         ;
2716         FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2717         const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2718         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2719         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2720         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2721         ogg_page page;
2722
2723         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2724         FLAC__ASSERT(0 != encoder->private_->seek_callback);
2725
2726         /* Pre-check that client supports seeking, since we don't want the
2727          * ogg_helper code to ever have to deal with this condition.
2728          */
2729         if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2730                 return;
2731
2732         /* All this is based on intimate knowledge of the stream header
2733          * layout, but a change to the header format that would break this
2734          * would also break all streams encoded in the previous format.
2735          */
2736
2737         /**
2738          ** Write STREAMINFO stats
2739          **/
2740         simple_ogg_page__init(&page);
2741         if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2742                 simple_ogg_page__clear(&page);
2743                 return; /* state already set */
2744         }
2745
2746         /*
2747          * Write MD5 signature
2748          */
2749         {
2750                 const unsigned md5_offset =
2751                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2752                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2753                         (
2754                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2755                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2756                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2757                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2758                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2759                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2760                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2761                                 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2762                         ) / 8;
2763
2764                 if(md5_offset + 16 > (unsigned)page.body_len) {
2765                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2766                         simple_ogg_page__clear(&page);
2767                         return;
2768                 }
2769                 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2770         }
2771
2772         /*
2773          * Write total samples
2774          */
2775         {
2776                 const unsigned total_samples_byte_offset =
2777                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2778                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2779                         (
2780                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2781                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2782                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2783                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2784                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2785                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2786                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2787                                 - 4
2788                         ) / 8;
2789
2790                 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2791                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2792                         simple_ogg_page__clear(&page);
2793                         return;
2794                 }
2795                 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2796                 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2797                 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2798                 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2799                 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2800                 b[4] = (FLAC__byte)(samples & 0xFF);
2801                 memcpy(page.body + total_samples_byte_offset, b, 5);
2802         }
2803
2804         /*
2805          * Write min/max framesize
2806          */
2807         {
2808                 const unsigned min_framesize_offset =
2809                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2810                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2811                         (
2812                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2813                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2814                         ) / 8;
2815
2816                 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2817                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2818                         simple_ogg_page__clear(&page);
2819                         return;
2820                 }
2821                 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2822                 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2823                 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2824                 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2825                 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2826                 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2827                 memcpy(page.body + min_framesize_offset, b, 6);
2828         }
2829         if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2830                 simple_ogg_page__clear(&page);
2831                 return; /* state already set */
2832         }
2833         simple_ogg_page__clear(&page);
2834
2835         /*
2836          * Write seektable
2837          */
2838         if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2839                 unsigned i;
2840                 FLAC__byte *p;
2841
2842                 FLAC__format_seektable_sort(encoder->private_->seek_table);
2843
2844                 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2845
2846                 simple_ogg_page__init(&page);
2847                 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2848                         simple_ogg_page__clear(&page);
2849                         return; /* state already set */
2850                 }
2851
2852                 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
2853                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2854                         simple_ogg_page__clear(&page);
2855                         return;
2856                 }
2857
2858                 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
2859                         FLAC__uint64 xx;
2860                         unsigned x;
2861                         xx = encoder->private_->seek_table->points[i].sample_number;
2862                         b[7] = (FLAC__byte)xx; xx >>= 8;
2863                         b[6] = (FLAC__byte)xx; xx >>= 8;
2864                         b[5] = (FLAC__byte)xx; xx >>= 8;
2865                         b[4] = (FLAC__byte)xx; xx >>= 8;
2866                         b[3] = (FLAC__byte)xx; xx >>= 8;
2867                         b[2] = (FLAC__byte)xx; xx >>= 8;
2868                         b[1] = (FLAC__byte)xx; xx >>= 8;
2869                         b[0] = (FLAC__byte)xx; xx >>= 8;
2870                         xx = encoder->private_->seek_table->points[i].stream_offset;
2871                         b[15] = (FLAC__byte)xx; xx >>= 8;
2872                         b[14] = (FLAC__byte)xx; xx >>= 8;
2873                         b[13] = (FLAC__byte)xx; xx >>= 8;
2874                         b[12] = (FLAC__byte)xx; xx >>= 8;
2875                         b[11] = (FLAC__byte)xx; xx >>= 8;
2876                         b[10] = (FLAC__byte)xx; xx >>= 8;
2877                         b[9] = (FLAC__byte)xx; xx >>= 8;
2878                         b[8] = (FLAC__byte)xx; xx >>= 8;
2879                         x = encoder->private_->seek_table->points[i].frame_samples;
2880                         b[17] = (FLAC__byte)x; x >>= 8;
2881                         b[16] = (FLAC__byte)x; x >>= 8;
2882                         memcpy(p, b, 18);
2883                 }
2884
2885                 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2886                         simple_ogg_page__clear(&page);
2887                         return; /* state already set */
2888                 }
2889                 simple_ogg_page__clear(&page);
2890         }
2891 }
2892 #endif
2893
2894 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
2895 {
2896         FLAC__uint16 crc;
2897         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2898
2899         /*
2900          * Accumulate raw signal to the MD5 signature
2901          */
2902         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)) {
2903                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2904                 return false;
2905         }
2906
2907         /*
2908          * Process the frame header and subframes into the frame bitbuffer
2909          */
2910         if(!process_subframes_(encoder, is_fractional_block)) {
2911                 /* the above function sets the state for us in case of an error */
2912                 return false;
2913         }
2914
2915         /*
2916          * Zero-pad the frame to a byte_boundary
2917          */
2918         if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
2919                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2920                 return false;
2921         }
2922
2923         /*
2924          * CRC-16 the whole thing
2925          */
2926         FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2927         if(
2928                 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
2929                 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
2930         ) {
2931                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2932                 return false;
2933         }
2934
2935         /*
2936          * Write it
2937          */
2938         if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
2939                 /* the above function sets the state for us in case of an error */
2940                 return false;
2941         }
2942
2943         /*
2944          * Get ready for the next frame
2945          */
2946         encoder->private_->current_sample_number = 0;
2947         encoder->private_->current_frame_number++;
2948         encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
2949
2950         return true;
2951 }
2952
2953 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
2954 {
2955         FLAC__FrameHeader frame_header;
2956         unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
2957         FLAC__bool do_independent, do_mid_side;
2958
2959         /*
2960          * Calculate the min,max Rice partition orders
2961          */
2962         if(is_fractional_block) {
2963                 max_partition_order = 0;
2964         }
2965         else {
2966                 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
2967                 max_partition_order = flac_min(max_partition_order, encoder->protected_->max_residual_partition_order);
2968         }
2969         min_partition_order = flac_min(min_partition_order, max_partition_order);
2970
2971         /*
2972          * Setup the frame
2973          */
2974         frame_header.blocksize = encoder->protected_->blocksize;
2975         frame_header.sample_rate = encoder->protected_->sample_rate;
2976         frame_header.channels = encoder->protected_->channels;
2977         frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
2978         frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
2979         frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2980         frame_header.number.frame_number = encoder->private_->current_frame_number;
2981
2982         /*
2983          * Figure out what channel assignments to try
2984          */
2985         if(encoder->protected_->do_mid_side_stereo) {
2986                 if(encoder->protected_->loose_mid_side_stereo) {
2987                         if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
2988                                 do_independent = true;
2989                                 do_mid_side = true;
2990                         }
2991                         else {
2992                                 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
2993                                 do_mid_side = !do_independent;
2994                         }
2995                 }
2996                 else {
2997                         do_independent = true;
2998                         do_mid_side = true;
2999                 }
3000         }
3001         else {
3002                 do_independent = true;
3003                 do_mid_side = false;
3004         }
3005
3006         FLAC__ASSERT(do_independent || do_mid_side);
3007
3008         /*
3009          * Check for wasted bits; set effective bps for each subframe
3010          */
3011         if(do_independent) {
3012                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3013                         const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
3014                         encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
3015                         encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
3016                 }
3017         }
3018         if(do_mid_side) {
3019                 FLAC__ASSERT(encoder->protected_->channels == 2);
3020                 for(channel = 0; channel < 2; channel++) {
3021                         const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
3022                         encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
3023                         encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
3024                 }
3025         }
3026
3027         /*
3028          * First do a normal encoding pass of each independent channel
3029          */
3030         if(do_independent) {
3031                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3032                         if(!
3033                                 process_subframe_(
3034                                         encoder,
3035                                         min_partition_order,
3036                                         max_partition_order,
3037                                         &frame_header,
3038                                         encoder->private_->subframe_bps[channel],
3039                                         encoder->private_->integer_signal[channel],
3040                                         encoder->private_->subframe_workspace_ptr[channel],
3041                                         encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3042                                         encoder->private_->residual_workspace[channel],
3043                                         encoder->private_->best_subframe+channel,
3044                                         encoder->private_->best_subframe_bits+channel
3045                                 )
3046                         )
3047                                 return false;
3048                 }
3049         }
3050
3051         /*
3052          * Now do mid and side channels if requested
3053          */
3054         if(do_mid_side) {
3055                 FLAC__ASSERT(encoder->protected_->channels == 2);
3056
3057                 for(channel = 0; channel < 2; channel++) {
3058                         if(!
3059                                 process_subframe_(
3060                                         encoder,
3061                                         min_partition_order,
3062                                         max_partition_order,
3063                                         &frame_header,
3064                                         encoder->private_->subframe_bps_mid_side[channel],
3065                                         encoder->private_->integer_signal_mid_side[channel],
3066                                         encoder->private_->subframe_workspace_ptr_mid_side[channel],
3067                                         encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3068                                         encoder->private_->residual_workspace_mid_side[channel],
3069                                         encoder->private_->best_subframe_mid_side+channel,
3070                                         encoder->private_->best_subframe_bits_mid_side+channel
3071                                 )
3072                         )
3073                                 return false;
3074                 }
3075         }
3076
3077         /*
3078          * Compose the frame bitbuffer
3079          */
3080         if(do_mid_side) {
3081                 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3082                 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3083                 FLAC__ChannelAssignment channel_assignment;
3084
3085                 FLAC__ASSERT(encoder->protected_->channels == 2);
3086
3087                 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3088                         channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3089                 }
3090                 else {
3091                         unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3092                         unsigned min_bits;
3093                         int ca;
3094
3095                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3096                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE   == 1);
3097                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE  == 2);
3098                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE    == 3);
3099                         FLAC__ASSERT(do_independent && do_mid_side);
3100
3101                         /* We have to figure out which channel assignent results in the smallest frame */
3102                         bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits         [1];
3103                         bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE  ] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits_mid_side[1];
3104                         bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits         [1] + encoder->private_->best_subframe_bits_mid_side[1];
3105                         bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE   ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3106
3107                         channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3108                         min_bits = bits[channel_assignment];
3109                         for(ca = 1; ca <= 3; ca++) {
3110                                 if(bits[ca] < min_bits) {
3111                                         min_bits = bits[ca];
3112                                         channel_assignment = (FLAC__ChannelAssignment)ca;
3113                                 }
3114                         }
3115                 }
3116
3117                 frame_header.channel_assignment = channel_assignment;
3118
3119                 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3120                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3121                         return false;
3122                 }
3123
3124                 switch(channel_assignment) {
3125                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3126                                 left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3127                                 right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
3128                                 break;
3129                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3130                                 left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3131                                 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3132                                 break;