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