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