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