Fix FLAC__stream_decoder_delete() and FLAC__stream_encoder_delete()
[platform/upstream/flac.git] / src / libFLAC / stream_encoder.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008,2009  Josh Coalson
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * - Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *
11  * - Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  *
15  * - Neither the name of the Xiph.org Foundation nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #if HAVE_CONFIG_H
33 #  include <config.h>
34 #endif
35
36 #if defined _MSC_VER || defined __MINGW32__
37 #include <io.h> /* for _setmode() */
38 #include <fcntl.h> /* for _O_BINARY */
39 #endif
40 #if defined __CYGWIN__ || defined __EMX__
41 #include <io.h> /* for setmode(), O_BINARY */
42 #include <fcntl.h> /* for _O_BINARY */
43 #endif
44 #include <limits.h>
45 #include <stdio.h>
46 #include <stdlib.h> /* for malloc() */
47 #include <string.h> /* for memcpy() */
48 #include <sys/types.h> /* for off_t */
49 #include "FLAC/assert.h"
50 #include "FLAC/stream_decoder.h"
51 #include "share/alloc.h"
52 #include "share/compat.h"
53 #include "protected/stream_encoder.h"
54 #include "private/bitwriter.h"
55 #include "private/bitmath.h"
56 #include "private/crc.h"
57 #include "private/cpu.h"
58 #include "private/fixed.h"
59 #include "private/format.h"
60 #include "private/lpc.h"
61 #include "private/md5.h"
62 #include "private/memory.h"
63 #include "private/macros.h"
64 #if FLAC__HAS_OGG
65 #include "private/ogg_helper.h"
66 #include "private/ogg_mapping.h"
67 #endif
68 #include "private/stream_encoder_framing.h"
69 #include "private/window.h"
70
71
72 /* Exact Rice codeword length calculation is off by default.  The simple
73  * (and fast) estimation (of how many bits a residual value will be
74  * encoded with) in this encoder is very good, almost always yielding
75  * compression within 0.1% of exact calculation.
76  */
77 #undef EXACT_RICE_BITS_CALCULATION
78 /* Rice parameter searching is off by default.  The simple (and fast)
79  * parameter estimation in this encoder is very good, almost always
80  * yielding compression within 0.1% of the optimal parameters.
81  */
82 #undef ENABLE_RICE_PARAMETER_SEARCH
83
84
85 typedef struct {
86         FLAC__int32 *data[FLAC__MAX_CHANNELS];
87         unsigned size; /* of each data[] in samples */
88         unsigned tail;
89 } verify_input_fifo;
90
91 typedef struct {
92         const FLAC__byte *data;
93         unsigned capacity;
94         unsigned bytes;
95 } verify_output;
96
97 typedef enum {
98         ENCODER_IN_MAGIC = 0,
99         ENCODER_IN_METADATA = 1,
100         ENCODER_IN_AUDIO = 2
101 } EncoderStateHint;
102
103 static struct CompressionLevels {
104         FLAC__bool do_mid_side_stereo;
105         FLAC__bool loose_mid_side_stereo;
106         unsigned max_lpc_order;
107         unsigned qlp_coeff_precision;
108         FLAC__bool do_qlp_coeff_prec_search;
109         FLAC__bool do_escape_coding;
110         FLAC__bool do_exhaustive_model_search;
111         unsigned min_residual_partition_order;
112         unsigned max_residual_partition_order;
113         unsigned rice_parameter_search_dist;
114 } compression_levels_[] = {
115         { false, false,  0, 0, false, false, false, 0, 3, 0 },
116         { true , true ,  0, 0, false, false, false, 0, 3, 0 },
117         { true , false,  0, 0, false, false, false, 0, 3, 0 },
118         { false, false,  6, 0, false, false, false, 0, 4, 0 },
119         { true , true ,  8, 0, false, false, false, 0, 4, 0 },
120         { true , false,  8, 0, false, false, false, 0, 5, 0 },
121         { true , false,  8, 0, false, false, false, 0, 6, 0 },
122         { true , false,  8, 0, false, false, true , 0, 6, 0 },
123         { true , false, 12, 0, false, false, true , 0, 6, 0 }
124 };
125
126
127 /***********************************************************************
128  *
129  * Private class method prototypes
130  *
131  ***********************************************************************/
132
133 static void set_defaults_(FLAC__StreamEncoder *encoder);
134 static void free_(FLAC__StreamEncoder *encoder);
135 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
136 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
137 static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
138 static void update_metadata_(const FLAC__StreamEncoder *encoder);
139 #if FLAC__HAS_OGG
140 static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
141 #endif
142 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
143 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
144
145 static FLAC__bool process_subframe_(
146         FLAC__StreamEncoder *encoder,
147         unsigned min_partition_order,
148         unsigned max_partition_order,
149         const FLAC__FrameHeader *frame_header,
150         unsigned subframe_bps,
151         const FLAC__int32 integer_signal[],
152         FLAC__Subframe *subframe[2],
153         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
154         FLAC__int32 *residual[2],
155         unsigned *best_subframe,
156         unsigned *best_bits
157 );
158
159 static FLAC__bool add_subframe_(
160         FLAC__StreamEncoder *encoder,
161         unsigned blocksize,
162         unsigned subframe_bps,
163         const FLAC__Subframe *subframe,
164         FLAC__BitWriter *frame
165 );
166
167 static unsigned evaluate_constant_subframe_(
168         FLAC__StreamEncoder *encoder,
169         const FLAC__int32 signal,
170         unsigned blocksize,
171         unsigned subframe_bps,
172         FLAC__Subframe *subframe
173 );
174
175 static unsigned evaluate_fixed_subframe_(
176         FLAC__StreamEncoder *encoder,
177         const FLAC__int32 signal[],
178         FLAC__int32 residual[],
179         FLAC__uint64 abs_residual_partition_sums[],
180         unsigned raw_bits_per_partition[],
181         unsigned blocksize,
182         unsigned subframe_bps,
183         unsigned order,
184         unsigned rice_parameter,
185         unsigned rice_parameter_limit,
186         unsigned min_partition_order,
187         unsigned max_partition_order,
188         FLAC__bool do_escape_coding,
189         unsigned rice_parameter_search_dist,
190         FLAC__Subframe *subframe,
191         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
192 );
193
194 #ifndef FLAC__INTEGER_ONLY_LIBRARY
195 static unsigned evaluate_lpc_subframe_(
196         FLAC__StreamEncoder *encoder,
197         const FLAC__int32 signal[],
198         FLAC__int32 residual[],
199         FLAC__uint64 abs_residual_partition_sums[],
200         unsigned raw_bits_per_partition[],
201         const FLAC__real lp_coeff[],
202         unsigned blocksize,
203         unsigned subframe_bps,
204         unsigned order,
205         unsigned qlp_coeff_precision,
206         unsigned rice_parameter,
207         unsigned rice_parameter_limit,
208         unsigned min_partition_order,
209         unsigned max_partition_order,
210         FLAC__bool do_escape_coding,
211         unsigned rice_parameter_search_dist,
212         FLAC__Subframe *subframe,
213         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
214 );
215 #endif
216
217 static unsigned evaluate_verbatim_subframe_(
218         FLAC__StreamEncoder *encoder,
219         const FLAC__int32 signal[],
220         unsigned blocksize,
221         unsigned subframe_bps,
222         FLAC__Subframe *subframe
223 );
224
225 static unsigned find_best_partition_order_(
226         struct FLAC__StreamEncoderPrivate *private_,
227         const FLAC__int32 residual[],
228         FLAC__uint64 abs_residual_partition_sums[],
229         unsigned raw_bits_per_partition[],
230         unsigned residual_samples,
231         unsigned predictor_order,
232         unsigned rice_parameter,
233         unsigned rice_parameter_limit,
234         unsigned min_partition_order,
235         unsigned max_partition_order,
236         unsigned bps,
237         FLAC__bool do_escape_coding,
238         unsigned rice_parameter_search_dist,
239         FLAC__EntropyCodingMethod *best_ecm
240 );
241
242 static void precompute_partition_info_sums_(
243         const FLAC__int32 residual[],
244         FLAC__uint64 abs_residual_partition_sums[],
245         unsigned residual_samples,
246         unsigned predictor_order,
247         unsigned min_partition_order,
248         unsigned max_partition_order,
249         unsigned bps
250 );
251
252 static void precompute_partition_info_escapes_(
253         const FLAC__int32 residual[],
254         unsigned raw_bits_per_partition[],
255         unsigned residual_samples,
256         unsigned predictor_order,
257         unsigned min_partition_order,
258         unsigned max_partition_order
259 );
260
261 static FLAC__bool set_partitioned_rice_(
262 #ifdef EXACT_RICE_BITS_CALCULATION
263         const FLAC__int32 residual[],
264 #endif
265         const FLAC__uint64 abs_residual_partition_sums[],
266         const unsigned raw_bits_per_partition[],
267         const unsigned residual_samples,
268         const unsigned predictor_order,
269         const unsigned suggested_rice_parameter,
270         const unsigned rice_parameter_limit,
271         const unsigned rice_parameter_search_dist,
272         const unsigned partition_order,
273         const FLAC__bool search_for_escapes,
274         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
275         unsigned *bits
276 );
277
278 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
279
280 /* verify-related routines: */
281 static void append_to_verify_fifo_(
282         verify_input_fifo *fifo,
283         const FLAC__int32 * const input[],
284         unsigned input_offset,
285         unsigned channels,
286         unsigned wide_samples
287 );
288
289 static void append_to_verify_fifo_interleaved_(
290         verify_input_fifo *fifo,
291         const FLAC__int32 input[],
292         unsigned input_offset,
293         unsigned channels,
294         unsigned wide_samples
295 );
296
297 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
298 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
299 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
300 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
301
302 static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
303 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
304 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
305 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);
306 static FILE *get_binary_stdout_(void);
307
308
309 /***********************************************************************
310  *
311  * Private class data
312  *
313  ***********************************************************************/
314
315 typedef struct FLAC__StreamEncoderPrivate {
316         unsigned input_capacity;                          /* current size (in samples) of the signal and residual buffers */
317         FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS];  /* the integer version of the input signal */
318         FLAC__int32 *integer_signal_mid_side[2];          /* the integer version of the mid-side input signal (stereo only) */
319 #ifndef FLAC__INTEGER_ONLY_LIBRARY
320         FLAC__real *real_signal[FLAC__MAX_CHANNELS];      /* (@@@ currently unused) the floating-point version of the input signal */
321         FLAC__real *real_signal_mid_side[2];              /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
322         FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
323         FLAC__real *windowed_signal;                      /* the integer_signal[] * current window[] */
324 #endif
325         unsigned subframe_bps[FLAC__MAX_CHANNELS];        /* the effective bits per sample of the input signal (stream bps - wasted bits) */
326         unsigned subframe_bps_mid_side[2];                /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
327         FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
328         FLAC__int32 *residual_workspace_mid_side[2][2];
329         FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
330         FLAC__Subframe subframe_workspace_mid_side[2][2];
331         FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
332         FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
333         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
334         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
335         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
336         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
337         unsigned best_subframe[FLAC__MAX_CHANNELS];       /* index (0 or 1) into 2nd dimension of the above workspaces */
338         unsigned best_subframe_mid_side[2];
339         unsigned best_subframe_bits[FLAC__MAX_CHANNELS];  /* size in bits of the best subframe for each channel */
340         unsigned best_subframe_bits_mid_side[2];
341         FLAC__uint64 *abs_residual_partition_sums;        /* workspace where the sum of abs(candidate residual) for each partition is stored */
342         unsigned *raw_bits_per_partition;                 /* workspace where the sum of silog2(candidate residual) for each partition is stored */
343         FLAC__BitWriter *frame;                           /* the current frame being worked on */
344         unsigned loose_mid_side_stereo_frames;            /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
345         unsigned loose_mid_side_stereo_frame_count;       /* number of frames using the current channel assignment */
346         FLAC__ChannelAssignment last_channel_assignment;
347         FLAC__StreamMetadata streaminfo;                  /* scratchpad for STREAMINFO as it is built */
348         FLAC__StreamMetadata_SeekTable *seek_table;       /* pointer into encoder->protected_->metadata_ where the seek table is */
349         unsigned current_sample_number;
350         unsigned current_frame_number;
351         FLAC__MD5Context md5context;
352         FLAC__CPUInfo cpuinfo;
353 #ifndef FLAC__INTEGER_ONLY_LIBRARY
354         unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
355 #else
356         unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
357 #endif
358 #ifndef FLAC__INTEGER_ONLY_LIBRARY
359         void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
360         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[]);
361         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[]);
362         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[]);
363 #endif
364         FLAC__bool use_wide_by_block;          /* use slow 64-bit versions of some functions because of the block size */
365         FLAC__bool use_wide_by_partition;      /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
366         FLAC__bool use_wide_by_order;          /* use slow 64-bit versions of some functions because of the lpc order */
367         FLAC__bool disable_constant_subframes;
368         FLAC__bool disable_fixed_subframes;
369         FLAC__bool disable_verbatim_subframes;
370 #if FLAC__HAS_OGG
371         FLAC__bool is_ogg;
372 #endif
373         FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
374         FLAC__StreamEncoderSeekCallback seek_callback;
375         FLAC__StreamEncoderTellCallback tell_callback;
376         FLAC__StreamEncoderWriteCallback write_callback;
377         FLAC__StreamEncoderMetadataCallback metadata_callback;
378         FLAC__StreamEncoderProgressCallback progress_callback;
379         void *client_data;
380         unsigned first_seekpoint_to_check;
381         FILE *file;                            /* only used when encoding to a file */
382         FLAC__uint64 bytes_written;
383         FLAC__uint64 samples_written;
384         unsigned frames_written;
385         unsigned total_frames_estimate;
386         /* unaligned (original) pointers to allocated data */
387         FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
388         FLAC__int32 *integer_signal_mid_side_unaligned[2];
389 #ifndef FLAC__INTEGER_ONLY_LIBRARY
390         FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
391         FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
392         FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
393         FLAC__real *windowed_signal_unaligned;
394 #endif
395         FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
396         FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
397         FLAC__uint64 *abs_residual_partition_sums_unaligned;
398         unsigned *raw_bits_per_partition_unaligned;
399         /*
400          * These fields have been moved here from private function local
401          * declarations merely to save stack space during encoding.
402          */
403 #ifndef FLAC__INTEGER_ONLY_LIBRARY
404         FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
405 #endif
406         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
407         /*
408          * The data for the verify section
409          */
410         struct {
411                 FLAC__StreamDecoder *decoder;
412                 EncoderStateHint state_hint;
413                 FLAC__bool needs_magic_hack;
414                 verify_input_fifo input_fifo;
415                 verify_output output;
416                 struct {
417                         FLAC__uint64 absolute_sample;
418                         unsigned frame_number;
419                         unsigned channel;
420                         unsigned sample;
421                         FLAC__int32 expected;
422                         FLAC__int32 got;
423                 } error_stats;
424         } verify;
425         FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
426 } FLAC__StreamEncoderPrivate;
427
428 /***********************************************************************
429  *
430  * Public static class data
431  *
432  ***********************************************************************/
433
434 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
435         "FLAC__STREAM_ENCODER_OK",
436         "FLAC__STREAM_ENCODER_UNINITIALIZED",
437         "FLAC__STREAM_ENCODER_OGG_ERROR",
438         "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
439         "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
440         "FLAC__STREAM_ENCODER_CLIENT_ERROR",
441         "FLAC__STREAM_ENCODER_IO_ERROR",
442         "FLAC__STREAM_ENCODER_FRAMING_ERROR",
443         "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
444 };
445
446 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
447         "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
448         "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
449         "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
450         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
451         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
452         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
453         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
454         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
455         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
456         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
457         "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
458         "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
459         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
460         "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
461 };
462
463 FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
464         "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
465         "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
466         "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
467         "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
468 };
469
470 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
471         "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
472         "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
473 };
474
475 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
476         "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
477         "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
478         "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
479 };
480
481 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
482         "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
483         "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
484         "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
485 };
486
487 /* Number of samples that will be overread to watch for end of stream.  By
488  * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
489  * always try to read blocksize+1 samples before encoding a block, so that
490  * even if the stream has a total sample count that is an integral multiple
491  * of the blocksize, we will still notice when we are encoding the last
492  * block.  This is needed, for example, to correctly set the end-of-stream
493  * marker in Ogg FLAC.
494  *
495  * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
496  * not really any reason to change it.
497  */
498 static const unsigned OVERREAD_ = 1;
499
500 /***********************************************************************
501  *
502  * Class constructor/destructor
503  *
504  */
505 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
506 {
507         FLAC__StreamEncoder *encoder;
508         unsigned i;
509
510         FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
511
512         encoder = calloc(1, sizeof(FLAC__StreamEncoder));
513         if(encoder == 0) {
514                 return 0;
515         }
516
517         encoder->protected_ = calloc(1, sizeof(FLAC__StreamEncoderProtected));
518         if(encoder->protected_ == 0) {
519                 free(encoder);
520                 return 0;
521         }
522
523         encoder->private_ = calloc(1, sizeof(FLAC__StreamEncoderPrivate));
524         if(encoder->private_ == 0) {
525                 free(encoder->protected_);
526                 free(encoder);
527                 return 0;
528         }
529
530         encoder->private_->frame = FLAC__bitwriter_new();
531         if(encoder->private_->frame == 0) {
532                 free(encoder->private_);
533                 free(encoder->protected_);
534                 free(encoder);
535                 return 0;
536         }
537
538         encoder->private_->file = 0;
539
540         set_defaults_(encoder);
541
542         encoder->private_->is_being_deleted = false;
543
544         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
545                 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
546                 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
547         }
548         for(i = 0; i < 2; i++) {
549                 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
550                 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
551         }
552         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
553                 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
554                 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
555         }
556         for(i = 0; i < 2; i++) {
557                 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
558                 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
559         }
560
561         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
562                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
563                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
564         }
565         for(i = 0; i < 2; i++) {
566                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
567                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
568         }
569         for(i = 0; i < 2; i++)
570                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
571
572         encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
573
574         return encoder;
575 }
576
577 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
578 {
579         unsigned i;
580
581         if (encoder == NULL)
582                 return ;
583
584         FLAC__ASSERT(0 != encoder->protected_);
585         FLAC__ASSERT(0 != encoder->private_);
586         FLAC__ASSERT(0 != encoder->private_->frame);
587
588         encoder->private_->is_being_deleted = true;
589
590         (void)FLAC__stream_encoder_finish(encoder);
591
592         if(0 != encoder->private_->verify.decoder)
593                 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
594
595         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
596                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
597                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
598         }
599         for(i = 0; i < 2; i++) {
600                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
601                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
602         }
603         for(i = 0; i < 2; i++)
604                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
605
606         FLAC__bitwriter_delete(encoder->private_->frame);
607         free(encoder->private_);
608         free(encoder->protected_);
609         free(encoder);
610 }
611
612 /***********************************************************************
613  *
614  * Public class methods
615  *
616  ***********************************************************************/
617
618 static FLAC__StreamEncoderInitStatus init_stream_internal_(
619         FLAC__StreamEncoder *encoder,
620         FLAC__StreamEncoderReadCallback read_callback,
621         FLAC__StreamEncoderWriteCallback write_callback,
622         FLAC__StreamEncoderSeekCallback seek_callback,
623         FLAC__StreamEncoderTellCallback tell_callback,
624         FLAC__StreamEncoderMetadataCallback metadata_callback,
625         void *client_data,
626         FLAC__bool is_ogg
627 )
628 {
629         unsigned i;
630         FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
631
632         FLAC__ASSERT(0 != encoder);
633
634         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
635                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
636
637 #if !FLAC__HAS_OGG
638         if(is_ogg)
639                 return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
640 #endif
641
642         if(0 == write_callback || (seek_callback && 0 == tell_callback))
643                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
644
645         if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
646                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
647
648         if(encoder->protected_->channels != 2) {
649                 encoder->protected_->do_mid_side_stereo = false;
650                 encoder->protected_->loose_mid_side_stereo = false;
651         }
652         else if(!encoder->protected_->do_mid_side_stereo)
653                 encoder->protected_->loose_mid_side_stereo = false;
654
655         if(encoder->protected_->bits_per_sample >= 32)
656                 encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
657
658         if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
659                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
660
661         if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
662                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
663
664         if(encoder->protected_->blocksize == 0) {
665                 if(encoder->protected_->max_lpc_order == 0)
666                         encoder->protected_->blocksize = 1152;
667                 else
668                         encoder->protected_->blocksize = 4096;
669         }
670
671         if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
672                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
673
674         if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
675                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
676
677         if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
678                 return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
679
680         if(encoder->protected_->qlp_coeff_precision == 0) {
681                 if(encoder->protected_->bits_per_sample < 16) {
682                         /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
683                         /* @@@ until then we'll make a guess */
684                         encoder->protected_->qlp_coeff_precision = flac_max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
685                 }
686                 else if(encoder->protected_->bits_per_sample == 16) {
687                         if(encoder->protected_->blocksize <= 192)
688                                 encoder->protected_->qlp_coeff_precision = 7;
689                         else if(encoder->protected_->blocksize <= 384)
690                                 encoder->protected_->qlp_coeff_precision = 8;
691                         else if(encoder->protected_->blocksize <= 576)
692                                 encoder->protected_->qlp_coeff_precision = 9;
693                         else if(encoder->protected_->blocksize <= 1152)
694                                 encoder->protected_->qlp_coeff_precision = 10;
695                         else if(encoder->protected_->blocksize <= 2304)
696                                 encoder->protected_->qlp_coeff_precision = 11;
697                         else if(encoder->protected_->blocksize <= 4608)
698                                 encoder->protected_->qlp_coeff_precision = 12;
699                         else
700                                 encoder->protected_->qlp_coeff_precision = 13;
701                 }
702                 else {
703                         if(encoder->protected_->blocksize <= 384)
704                                 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
705                         else if(encoder->protected_->blocksize <= 1152)
706                                 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
707                         else
708                                 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
709                 }
710                 FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
711         }
712         else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
713                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
714
715         if(encoder->protected_->streamable_subset) {
716                 if(!FLAC__format_blocksize_is_subset(encoder->protected_->blocksize, encoder->protected_->sample_rate))
717                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
718                 if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
719                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
720                 if(
721                         encoder->protected_->bits_per_sample != 8 &&
722                         encoder->protected_->bits_per_sample != 12 &&
723                         encoder->protected_->bits_per_sample != 16 &&
724                         encoder->protected_->bits_per_sample != 20 &&
725                         encoder->protected_->bits_per_sample != 24
726                 )
727                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
728                 if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
729                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
730                 if(
731                         encoder->protected_->sample_rate <= 48000 &&
732                         (
733                                 encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
734                                 encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
735                         )
736                 ) {
737                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
738                 }
739         }
740
741         if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
742                 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
743         if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
744                 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
745
746 #if FLAC__HAS_OGG
747         /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
748         if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
749                 unsigned i;
750                 for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
751                         if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
752                                 FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
753                                 for( ; i > 0; i--)
754                                         encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
755                                 encoder->protected_->metadata[0] = vc;
756                                 break;
757                         }
758                 }
759         }
760 #endif
761         /* keep track of any SEEKTABLE block */
762         if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
763                 unsigned i;
764                 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
765                         if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
766                                 encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
767                                 break; /* take only the first one */
768                         }
769                 }
770         }
771
772         /* validate metadata */
773         if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
774                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
775         metadata_has_seektable = false;
776         metadata_has_vorbis_comment = false;
777         metadata_picture_has_type1 = false;
778         metadata_picture_has_type2 = false;
779         for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
780                 const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
781                 if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
782                         return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
783                 else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
784                         if(metadata_has_seektable) /* only one is allowed */
785                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
786                         metadata_has_seektable = true;
787                         if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
788                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
789                 }
790                 else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
791                         if(metadata_has_vorbis_comment) /* only one is allowed */
792                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
793                         metadata_has_vorbis_comment = true;
794                 }
795                 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
796                         if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
797                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
798                 }
799                 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
800                         if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
801                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
802                         if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
803                                 if(metadata_picture_has_type1) /* there should only be 1 per stream */
804                                         return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
805                                 metadata_picture_has_type1 = true;
806                                 /* standard icon must be 32x32 pixel PNG */
807                                 if(
808                                         m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
809                                         (
810                                                 (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
811                                                 m->data.picture.width != 32 ||
812                                                 m->data.picture.height != 32
813                                         )
814                                 )
815                                         return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
816                         }
817                         else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
818                                 if(metadata_picture_has_type2) /* there should only be 1 per stream */
819                                         return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
820                                 metadata_picture_has_type2 = true;
821                         }
822                 }
823         }
824
825         encoder->private_->input_capacity = 0;
826         for(i = 0; i < encoder->protected_->channels; i++) {
827                 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
828 #ifndef FLAC__INTEGER_ONLY_LIBRARY
829                 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
830 #endif
831         }
832         for(i = 0; i < 2; i++) {
833                 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
834 #ifndef FLAC__INTEGER_ONLY_LIBRARY
835                 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
836 #endif
837         }
838 #ifndef FLAC__INTEGER_ONLY_LIBRARY
839         for(i = 0; i < encoder->protected_->num_apodizations; i++)
840                 encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
841         encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
842 #endif
843         for(i = 0; i < encoder->protected_->channels; i++) {
844                 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
845                 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
846                 encoder->private_->best_subframe[i] = 0;
847         }
848         for(i = 0; i < 2; i++) {
849                 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
850                 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
851                 encoder->private_->best_subframe_mid_side[i] = 0;
852         }
853         encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
854         encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
855 #ifndef FLAC__INTEGER_ONLY_LIBRARY
856         encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
857 #else
858         /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
859         /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
860         FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
861         FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
862         FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
863         FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
864         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);
865 #endif
866         if(encoder->private_->loose_mid_side_stereo_frames == 0)
867                 encoder->private_->loose_mid_side_stereo_frames = 1;
868         encoder->private_->loose_mid_side_stereo_frame_count = 0;
869         encoder->private_->current_sample_number = 0;
870         encoder->private_->current_frame_number = 0;
871
872         encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
873         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? */
874         encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
875
876         /*
877          * get the CPU info and set the function pointers
878          */
879         FLAC__cpu_info(&encoder->private_->cpuinfo);
880         /* first default to the non-asm routines */
881 #ifndef FLAC__INTEGER_ONLY_LIBRARY
882         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
883 #endif
884         encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
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                 if(encoder->private_->cpuinfo.data.ia32.sse) {
898                         if(encoder->protected_->max_lpc_order < 4)
899                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
900                         else if(encoder->protected_->max_lpc_order < 8)
901                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
902                         else if(encoder->protected_->max_lpc_order < 12)
903                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
904                         else
905                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
906                 }
907                 else if(encoder->private_->cpuinfo.data.ia32._3dnow)
908                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
909                 else
910                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
911                 if(encoder->private_->cpuinfo.data.ia32.mmx) {
912                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
913                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
914                 }
915                 else {
916                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
917                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
918                 }
919                 if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
920                         encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
921 #   endif /* FLAC__HAS_NASM */
922 #  endif /* FLAC__CPU_IA32 */
923         }
924 # endif /* !FLAC__NO_ASM */
925 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
926         /* finally override based on wide-ness if necessary */
927         if(encoder->private_->use_wide_by_block) {
928                 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
929         }
930
931         /* set state to OK; from here on, errors are fatal and we'll override the state then */
932         encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
933
934 #if FLAC__HAS_OGG
935         encoder->private_->is_ogg = is_ogg;
936         if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
937                 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
938                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
939         }
940 #endif
941
942         encoder->private_->read_callback = read_callback;
943         encoder->private_->write_callback = write_callback;
944         encoder->private_->seek_callback = seek_callback;
945         encoder->private_->tell_callback = tell_callback;
946         encoder->private_->metadata_callback = metadata_callback;
947         encoder->private_->client_data = client_data;
948
949         if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
950                 /* the above function sets the state for us in case of an error */
951                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
952         }
953
954         if(!FLAC__bitwriter_init(encoder->private_->frame)) {
955                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
956                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
957         }
958
959         /*
960          * Set up the verify stuff if necessary
961          */
962         if(encoder->protected_->verify) {
963                 /*
964                  * First, set up the fifo which will hold the
965                  * original signal to compare against
966                  */
967                 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
968                 for(i = 0; i < encoder->protected_->channels; i++) {
969                         if(0 == (encoder->private_->verify.input_fifo.data[i] = safe_malloc_mul_2op_(sizeof(FLAC__int32), /*times*/encoder->private_->verify.input_fifo.size))) {
970                                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
971                                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
972                         }
973                 }
974                 encoder->private_->verify.input_fifo.tail = 0;
975
976                 /*
977                  * Now set up a stream decoder for verification
978                  */
979                 if(0 == encoder->private_->verify.decoder) {
980                         encoder->private_->verify.decoder = FLAC__stream_decoder_new();
981                         if(0 == encoder->private_->verify.decoder) {
982                                 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
983                                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
984                         }
985                 }
986
987                 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) {
988                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
989                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
990                 }
991         }
992         encoder->private_->verify.error_stats.absolute_sample = 0;
993         encoder->private_->verify.error_stats.frame_number = 0;
994         encoder->private_->verify.error_stats.channel = 0;
995         encoder->private_->verify.error_stats.sample = 0;
996         encoder->private_->verify.error_stats.expected = 0;
997         encoder->private_->verify.error_stats.got = 0;
998
999         /*
1000          * These must be done before we write any metadata, because that
1001          * calls the write_callback, which uses these values.
1002          */
1003         encoder->private_->first_seekpoint_to_check = 0;
1004         encoder->private_->samples_written = 0;
1005         encoder->protected_->streaminfo_offset = 0;
1006         encoder->protected_->seektable_offset = 0;
1007         encoder->protected_->audio_offset = 0;
1008
1009         /*
1010          * write the stream header
1011          */
1012         if(encoder->protected_->verify)
1013                 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1014         if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1015                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1016                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1017         }
1018         if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1019                 /* the above function sets the state for us in case of an error */
1020                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1021         }
1022
1023         /*
1024          * write the STREAMINFO metadata block
1025          */
1026         if(encoder->protected_->verify)
1027                 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1028         encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1029         encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1030         encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1031         encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1032         encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1033         encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1034         encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1035         encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1036         encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1037         encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1038         encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1039         memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1040         if(encoder->protected_->do_md5)
1041                 FLAC__MD5Init(&encoder->private_->md5context);
1042         if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1043                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1044                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1045         }
1046         if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1047                 /* the above function sets the state for us in case of an error */
1048                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1049         }
1050
1051         /*
1052          * Now that the STREAMINFO block is written, we can init this to an
1053          * absurdly-high value...
1054          */
1055         encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1056         /* ... and clear this to 0 */
1057         encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1058
1059         /*
1060          * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1061          * if not, we will write an empty one (FLAC__add_metadata_block()
1062          * automatically supplies the vendor string).
1063          *
1064          * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1065          * the STREAMINFO.  (In the case that metadata_has_vorbis_comment is
1066          * true it will have already insured that the metadata list is properly
1067          * ordered.)
1068          */
1069         if(!metadata_has_vorbis_comment) {
1070                 FLAC__StreamMetadata vorbis_comment;
1071                 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1072                 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1073                 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1074                 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1075                 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1076                 vorbis_comment.data.vorbis_comment.num_comments = 0;
1077                 vorbis_comment.data.vorbis_comment.comments = 0;
1078                 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1079                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1080                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1081                 }
1082                 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1083                         /* the above function sets the state for us in case of an error */
1084                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1085                 }
1086         }
1087
1088         /*
1089          * write the user's metadata blocks
1090          */
1091         for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1092                 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1093                 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1094                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1095                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1096                 }
1097                 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1098                         /* the above function sets the state for us in case of an error */
1099                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1100                 }
1101         }
1102
1103         /* now that all the metadata is written, we save the stream offset */
1104         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 */
1105                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1106                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1107         }
1108
1109         if(encoder->protected_->verify)
1110                 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1111
1112         return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1113 }
1114
1115 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1116         FLAC__StreamEncoder *encoder,
1117         FLAC__StreamEncoderWriteCallback write_callback,
1118         FLAC__StreamEncoderSeekCallback seek_callback,
1119         FLAC__StreamEncoderTellCallback tell_callback,
1120         FLAC__StreamEncoderMetadataCallback metadata_callback,
1121         void *client_data
1122 )
1123 {
1124         return init_stream_internal_(
1125                 encoder,
1126                 /*read_callback=*/0,
1127                 write_callback,
1128                 seek_callback,
1129                 tell_callback,
1130                 metadata_callback,
1131                 client_data,
1132                 /*is_ogg=*/false
1133         );
1134 }
1135
1136 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1137         FLAC__StreamEncoder *encoder,
1138         FLAC__StreamEncoderReadCallback read_callback,
1139         FLAC__StreamEncoderWriteCallback write_callback,
1140         FLAC__StreamEncoderSeekCallback seek_callback,
1141         FLAC__StreamEncoderTellCallback tell_callback,
1142         FLAC__StreamEncoderMetadataCallback metadata_callback,
1143         void *client_data
1144 )
1145 {
1146         return init_stream_internal_(
1147                 encoder,
1148                 read_callback,
1149                 write_callback,
1150                 seek_callback,
1151                 tell_callback,
1152                 metadata_callback,
1153                 client_data,
1154                 /*is_ogg=*/true
1155         );
1156 }
1157
1158 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1159         FLAC__StreamEncoder *encoder,
1160         FILE *file,
1161         FLAC__StreamEncoderProgressCallback progress_callback,
1162         void *client_data,
1163         FLAC__bool is_ogg
1164 )
1165 {
1166         FLAC__StreamEncoderInitStatus init_status;
1167
1168         FLAC__ASSERT(0 != encoder);
1169         FLAC__ASSERT(0 != file);
1170
1171         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1172                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1173
1174         /* double protection */
1175         if(file == 0) {
1176                 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1177                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1178         }
1179
1180         /*
1181          * To make sure that our file does not go unclosed after an error, we
1182          * must assign the FILE pointer before any further error can occur in
1183          * this routine.
1184          */
1185         if(file == stdout)
1186                 file = get_binary_stdout_(); /* just to be safe */
1187
1188         encoder->private_->file = file;
1189
1190         encoder->private_->progress_callback = progress_callback;
1191         encoder->private_->bytes_written = 0;
1192         encoder->private_->samples_written = 0;
1193         encoder->private_->frames_written = 0;
1194
1195         init_status = init_stream_internal_(
1196                 encoder,
1197                 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1198                 file_write_callback_,
1199                 encoder->private_->file == stdout? 0 : file_seek_callback_,
1200                 encoder->private_->file == stdout? 0 : file_tell_callback_,
1201                 /*metadata_callback=*/0,
1202                 client_data,
1203                 is_ogg
1204         );
1205         if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1206                 /* the above function sets the state for us in case of an error */
1207                 return init_status;
1208         }
1209
1210         {
1211                 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1212
1213                 FLAC__ASSERT(blocksize != 0);
1214                 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1215         }
1216
1217         return init_status;
1218 }
1219
1220 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1221         FLAC__StreamEncoder *encoder,
1222         FILE *file,
1223         FLAC__StreamEncoderProgressCallback progress_callback,
1224         void *client_data
1225 )
1226 {
1227         return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1228 }
1229
1230 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1231         FLAC__StreamEncoder *encoder,
1232         FILE *file,
1233         FLAC__StreamEncoderProgressCallback progress_callback,
1234         void *client_data
1235 )
1236 {
1237         return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1238 }
1239
1240 static FLAC__StreamEncoderInitStatus init_file_internal_(
1241         FLAC__StreamEncoder *encoder,
1242         const char *filename,
1243         FLAC__StreamEncoderProgressCallback progress_callback,
1244         void *client_data,
1245         FLAC__bool is_ogg
1246 )
1247 {
1248         FILE *file;
1249
1250         FLAC__ASSERT(0 != encoder);
1251
1252         /*
1253          * To make sure that our file does not go unclosed after an error, we
1254          * have to do the same entrance checks here that are later performed
1255          * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1256          */
1257         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1258                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1259
1260         file = filename? fopen(filename, "w+b") : stdout;
1261
1262         if(file == 0) {
1263                 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1264                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1265         }
1266
1267         return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1268 }
1269
1270 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1271         FLAC__StreamEncoder *encoder,
1272         const char *filename,
1273         FLAC__StreamEncoderProgressCallback progress_callback,
1274         void *client_data
1275 )
1276 {
1277         return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1278 }
1279
1280 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1281         FLAC__StreamEncoder *encoder,
1282         const char *filename,
1283         FLAC__StreamEncoderProgressCallback progress_callback,
1284         void *client_data
1285 )
1286 {
1287         return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1288 }
1289
1290 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1291 {
1292         FLAC__bool error = false;
1293
1294         FLAC__ASSERT(0 != encoder);
1295         FLAC__ASSERT(0 != encoder->private_);
1296         FLAC__ASSERT(0 != encoder->protected_);
1297
1298         if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1299                 return true;
1300
1301         if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1302                 if(encoder->private_->current_sample_number != 0) {
1303                         const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1304                         encoder->protected_->blocksize = encoder->private_->current_sample_number;
1305                         if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1306                                 error = true;
1307                 }
1308         }
1309
1310         if(encoder->protected_->do_md5)
1311                 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1312
1313         if(!encoder->private_->is_being_deleted) {
1314                 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1315                         if(encoder->private_->seek_callback) {
1316 #if FLAC__HAS_OGG
1317                                 if(encoder->private_->is_ogg)
1318                                         update_ogg_metadata_(encoder);
1319                                 else
1320 #endif
1321                                 update_metadata_(encoder);
1322
1323                                 /* check if an error occurred while updating metadata */
1324                                 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1325                                         error = true;
1326                         }
1327                         if(encoder->private_->metadata_callback)
1328                                 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1329                 }
1330
1331                 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1332                         if(!error)
1333                                 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1334                         error = true;
1335                 }
1336         }
1337
1338         if(0 != encoder->private_->file) {
1339                 if(encoder->private_->file != stdout)
1340                         fclose(encoder->private_->file);
1341                 encoder->private_->file = 0;
1342         }
1343
1344 #if FLAC__HAS_OGG
1345         if(encoder->private_->is_ogg)
1346                 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1347 #endif
1348
1349         free_(encoder);
1350         set_defaults_(encoder);
1351
1352         if(!error)
1353                 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1354
1355         return !error;
1356 }
1357
1358 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1359 {
1360         FLAC__ASSERT(0 != encoder);
1361         FLAC__ASSERT(0 != encoder->private_);
1362         FLAC__ASSERT(0 != encoder->protected_);
1363         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1364                 return false;
1365 #if FLAC__HAS_OGG
1366         /* can't check encoder->private_->is_ogg since that's not set until init time */
1367         FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1368         return true;
1369 #else
1370         (void)value;
1371         return false;
1372 #endif
1373 }
1374
1375 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1376 {
1377         FLAC__ASSERT(0 != encoder);
1378         FLAC__ASSERT(0 != encoder->private_);
1379         FLAC__ASSERT(0 != encoder->protected_);
1380         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1381                 return false;
1382 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1383         encoder->protected_->verify = value;
1384 #endif
1385         return true;
1386 }
1387
1388 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1389 {
1390         FLAC__ASSERT(0 != encoder);
1391         FLAC__ASSERT(0 != encoder->private_);
1392         FLAC__ASSERT(0 != encoder->protected_);
1393         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1394                 return false;
1395         encoder->protected_->streamable_subset = value;
1396         return true;
1397 }
1398
1399 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
1400 {
1401         FLAC__ASSERT(0 != encoder);
1402         FLAC__ASSERT(0 != encoder->private_);
1403         FLAC__ASSERT(0 != encoder->protected_);
1404         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1405                 return false;
1406         encoder->protected_->do_md5 = value;
1407         return true;
1408 }
1409
1410 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1411 {
1412         FLAC__ASSERT(0 != encoder);
1413         FLAC__ASSERT(0 != encoder->private_);
1414         FLAC__ASSERT(0 != encoder->protected_);
1415         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1416                 return false;
1417         encoder->protected_->channels = value;
1418         return true;
1419 }
1420
1421 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1422 {
1423         FLAC__ASSERT(0 != encoder);
1424         FLAC__ASSERT(0 != encoder->private_);
1425         FLAC__ASSERT(0 != encoder->protected_);
1426         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1427                 return false;
1428         encoder->protected_->bits_per_sample = value;
1429         return true;
1430 }
1431
1432 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1433 {
1434         FLAC__ASSERT(0 != encoder);
1435         FLAC__ASSERT(0 != encoder->private_);
1436         FLAC__ASSERT(0 != encoder->protected_);
1437         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1438                 return false;
1439         encoder->protected_->sample_rate = value;
1440         return true;
1441 }
1442
1443 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1444 {
1445         FLAC__bool ok = true;
1446         FLAC__ASSERT(0 != encoder);
1447         FLAC__ASSERT(0 != encoder->private_);
1448         FLAC__ASSERT(0 != encoder->protected_);
1449         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1450                 return false;
1451         if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1452                 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1453         ok &= FLAC__stream_encoder_set_do_mid_side_stereo          (encoder, compression_levels_[value].do_mid_side_stereo);
1454         ok &= FLAC__stream_encoder_set_loose_mid_side_stereo       (encoder, compression_levels_[value].loose_mid_side_stereo);
1455 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1456 #if 0
1457         /* was: */
1458         ok &= FLAC__stream_encoder_set_apodization                 (encoder, compression_levels_[value].apodization);
1459         /* but it's too hard to specify the string in a locale-specific way */
1460 #else
1461         encoder->protected_->num_apodizations = 1;
1462         encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1463         encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1464 #endif
1465 #endif
1466         ok &= FLAC__stream_encoder_set_max_lpc_order               (encoder, compression_levels_[value].max_lpc_order);
1467         ok &= FLAC__stream_encoder_set_qlp_coeff_precision         (encoder, compression_levels_[value].qlp_coeff_precision);
1468         ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search    (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1469         ok &= FLAC__stream_encoder_set_do_escape_coding            (encoder, compression_levels_[value].do_escape_coding);
1470         ok &= FLAC__stream_encoder_set_do_exhaustive_model_search  (encoder, compression_levels_[value].do_exhaustive_model_search);
1471         ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1472         ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1473         ok &= FLAC__stream_encoder_set_rice_parameter_search_dist  (encoder, compression_levels_[value].rice_parameter_search_dist);
1474         return ok;
1475 }
1476
1477 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1478 {
1479         FLAC__ASSERT(0 != encoder);
1480         FLAC__ASSERT(0 != encoder->private_);
1481         FLAC__ASSERT(0 != encoder->protected_);
1482         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1483                 return false;
1484         encoder->protected_->blocksize = value;
1485         return true;
1486 }
1487
1488 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(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_mid_side_stereo = value;
1496         return true;
1497 }
1498
1499 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool 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_->loose_mid_side_stereo = value;
1507         return true;
1508 }
1509
1510 /*@@@@add to tests*/
1511 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1512 {
1513         FLAC__ASSERT(0 != encoder);
1514         FLAC__ASSERT(0 != encoder->private_);
1515         FLAC__ASSERT(0 != encoder->protected_);
1516         FLAC__ASSERT(0 != specification);
1517         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1518                 return false;
1519 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1520         (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1521 #else
1522         encoder->protected_->num_apodizations = 0;
1523         while(1) {
1524                 const char *s = strchr(specification, ';');
1525                 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1526                 if     (n==8  && 0 == strncmp("bartlett"     , specification, n))
1527                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1528                 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1529                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1530                 else if(n==8  && 0 == strncmp("blackman"     , specification, n))
1531                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1532                 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1533                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1534                 else if(n==6  && 0 == strncmp("connes"       , specification, n))
1535                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1536                 else if(n==7  && 0 == strncmp("flattop"      , specification, n))
1537                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1538                 else if(n>7   && 0 == strncmp("gauss("       , specification, 6)) {
1539                         FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1540                         if (stddev > 0.0 && stddev <= 0.5) {
1541                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1542                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1543                         }
1544                 }
1545                 else if(n==7  && 0 == strncmp("hamming"      , specification, n))
1546                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1547                 else if(n==4  && 0 == strncmp("hann"         , specification, n))
1548                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1549                 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1550                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1551                 else if(n==7  && 0 == strncmp("nuttall"      , specification, n))
1552                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1553                 else if(n==9  && 0 == strncmp("rectangle"    , specification, n))
1554                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1555                 else if(n==8  && 0 == strncmp("triangle"     , specification, n))
1556                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1557                 else if(n>7   && 0 == strncmp("tukey("       , specification, 6)) {
1558                         FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1559                         if (p >= 0.0 && p <= 1.0) {
1560                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1561                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1562                         }
1563                 }
1564                 else if(n==5  && 0 == strncmp("welch"        , specification, n))
1565                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1566                 if (encoder->protected_->num_apodizations == 32)
1567                         break;
1568                 if (s)
1569                         specification = s+1;
1570                 else
1571                         break;
1572         }
1573         if(encoder->protected_->num_apodizations == 0) {
1574                 encoder->protected_->num_apodizations = 1;
1575                 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1576                 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1577         }
1578 #endif
1579         return true;
1580 }
1581
1582 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1583 {
1584         FLAC__ASSERT(0 != encoder);
1585         FLAC__ASSERT(0 != encoder->private_);
1586         FLAC__ASSERT(0 != encoder->protected_);
1587         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1588                 return false;
1589         encoder->protected_->max_lpc_order = value;
1590         return true;
1591 }
1592
1593 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1594 {
1595         FLAC__ASSERT(0 != encoder);
1596         FLAC__ASSERT(0 != encoder->private_);
1597         FLAC__ASSERT(0 != encoder->protected_);
1598         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1599                 return false;
1600         encoder->protected_->qlp_coeff_precision = value;
1601         return true;
1602 }
1603
1604 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1605 {
1606         FLAC__ASSERT(0 != encoder);
1607         FLAC__ASSERT(0 != encoder->private_);
1608         FLAC__ASSERT(0 != encoder->protected_);
1609         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1610                 return false;
1611         encoder->protected_->do_qlp_coeff_prec_search = value;
1612         return true;
1613 }
1614
1615 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1616 {
1617         FLAC__ASSERT(0 != encoder);
1618         FLAC__ASSERT(0 != encoder->private_);
1619         FLAC__ASSERT(0 != encoder->protected_);
1620         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1621                 return false;
1622 #if 0
1623         /*@@@ deprecated: */
1624         encoder->protected_->do_escape_coding = value;
1625 #else
1626         (void)value;
1627 #endif
1628         return true;
1629 }
1630
1631 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1632 {
1633         FLAC__ASSERT(0 != encoder);
1634         FLAC__ASSERT(0 != encoder->private_);
1635         FLAC__ASSERT(0 != encoder->protected_);
1636         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1637                 return false;
1638         encoder->protected_->do_exhaustive_model_search = value;
1639         return true;
1640 }
1641
1642 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1643 {
1644         FLAC__ASSERT(0 != encoder);
1645         FLAC__ASSERT(0 != encoder->private_);
1646         FLAC__ASSERT(0 != encoder->protected_);
1647         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1648                 return false;
1649         encoder->protected_->min_residual_partition_order = value;
1650         return true;
1651 }
1652
1653 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1654 {
1655         FLAC__ASSERT(0 != encoder);
1656         FLAC__ASSERT(0 != encoder->private_);
1657         FLAC__ASSERT(0 != encoder->protected_);
1658         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1659                 return false;
1660         encoder->protected_->max_residual_partition_order = value;
1661         return true;
1662 }
1663
1664 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1665 {
1666         FLAC__ASSERT(0 != encoder);
1667         FLAC__ASSERT(0 != encoder->private_);
1668         FLAC__ASSERT(0 != encoder->protected_);
1669         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1670                 return false;
1671 #if 0
1672         /*@@@ deprecated: */
1673         encoder->protected_->rice_parameter_search_dist = value;
1674 #else
1675         (void)value;
1676 #endif
1677         return true;
1678 }
1679
1680 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1681 {
1682         FLAC__ASSERT(0 != encoder);
1683         FLAC__ASSERT(0 != encoder->private_);
1684         FLAC__ASSERT(0 != encoder->protected_);
1685         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1686                 return false;
1687         encoder->protected_->total_samples_estimate = value;
1688         return true;
1689 }
1690
1691 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1692 {
1693         FLAC__ASSERT(0 != encoder);
1694         FLAC__ASSERT(0 != encoder->private_);
1695         FLAC__ASSERT(0 != encoder->protected_);
1696         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1697                 return false;
1698         if(0 == metadata)
1699                 num_blocks = 0;
1700         if(0 == num_blocks)
1701                 metadata = 0;
1702         /* realloc() does not do exactly what we want so... */
1703         if(encoder->protected_->metadata) {
1704                 free(encoder->protected_->metadata);
1705                 encoder->protected_->metadata = 0;
1706                 encoder->protected_->num_metadata_blocks = 0;
1707         }
1708         if(num_blocks) {
1709                 FLAC__StreamMetadata **m;
1710                 if(0 == (m = safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
1711                         return false;
1712                 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1713                 encoder->protected_->metadata = m;
1714                 encoder->protected_->num_metadata_blocks = num_blocks;
1715         }
1716 #if FLAC__HAS_OGG
1717         if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1718                 return false;
1719 #endif
1720         return true;
1721 }
1722
1723 /*
1724  * These three functions are not static, but not publically exposed in
1725  * include/FLAC/ either.  They are used by the test suite.
1726  */
1727 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1728 {
1729         FLAC__ASSERT(0 != encoder);
1730         FLAC__ASSERT(0 != encoder->private_);
1731         FLAC__ASSERT(0 != encoder->protected_);
1732         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1733                 return false;
1734         encoder->private_->disable_constant_subframes = value;
1735         return true;
1736 }
1737
1738 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1739 {
1740         FLAC__ASSERT(0 != encoder);
1741         FLAC__ASSERT(0 != encoder->private_);
1742         FLAC__ASSERT(0 != encoder->protected_);
1743         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1744                 return false;
1745         encoder->private_->disable_fixed_subframes = value;
1746         return true;
1747 }
1748
1749 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1750 {
1751         FLAC__ASSERT(0 != encoder);
1752         FLAC__ASSERT(0 != encoder->private_);
1753         FLAC__ASSERT(0 != encoder->protected_);
1754         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1755                 return false;
1756         encoder->private_->disable_verbatim_subframes = value;
1757         return true;
1758 }
1759
1760 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1761 {
1762         FLAC__ASSERT(0 != encoder);
1763         FLAC__ASSERT(0 != encoder->private_);
1764         FLAC__ASSERT(0 != encoder->protected_);
1765         return encoder->protected_->state;
1766 }
1767
1768 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1769 {
1770         FLAC__ASSERT(0 != encoder);
1771         FLAC__ASSERT(0 != encoder->private_);
1772         FLAC__ASSERT(0 != encoder->protected_);
1773         if(encoder->protected_->verify)
1774                 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1775         else
1776                 return FLAC__STREAM_DECODER_UNINITIALIZED;
1777 }
1778
1779 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1780 {
1781         FLAC__ASSERT(0 != encoder);
1782         FLAC__ASSERT(0 != encoder->private_);
1783         FLAC__ASSERT(0 != encoder->protected_);
1784         if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1785                 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1786         else
1787                 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1788 }
1789
1790 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)
1791 {
1792         FLAC__ASSERT(0 != encoder);
1793         FLAC__ASSERT(0 != encoder->private_);
1794         FLAC__ASSERT(0 != encoder->protected_);
1795         if(0 != absolute_sample)
1796                 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1797         if(0 != frame_number)
1798                 *frame_number = encoder->private_->verify.error_stats.frame_number;
1799         if(0 != channel)
1800                 *channel = encoder->private_->verify.error_stats.channel;
1801         if(0 != sample)
1802                 *sample = encoder->private_->verify.error_stats.sample;
1803         if(0 != expected)
1804                 *expected = encoder->private_->verify.error_stats.expected;
1805         if(0 != got)
1806                 *got = encoder->private_->verify.error_stats.got;
1807 }
1808
1809 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1810 {
1811         FLAC__ASSERT(0 != encoder);
1812         FLAC__ASSERT(0 != encoder->private_);
1813         FLAC__ASSERT(0 != encoder->protected_);
1814         return encoder->protected_->verify;
1815 }
1816
1817 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1818 {
1819         FLAC__ASSERT(0 != encoder);
1820         FLAC__ASSERT(0 != encoder->private_);
1821         FLAC__ASSERT(0 != encoder->protected_);
1822         return encoder->protected_->streamable_subset;
1823 }
1824
1825 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
1826 {
1827         FLAC__ASSERT(0 != encoder);
1828         FLAC__ASSERT(0 != encoder->private_);
1829         FLAC__ASSERT(0 != encoder->protected_);
1830         return encoder->protected_->do_md5;
1831 }
1832
1833 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1834 {
1835         FLAC__ASSERT(0 != encoder);
1836         FLAC__ASSERT(0 != encoder->private_);
1837         FLAC__ASSERT(0 != encoder->protected_);
1838         return encoder->protected_->channels;
1839 }
1840
1841 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1842 {
1843         FLAC__ASSERT(0 != encoder);
1844         FLAC__ASSERT(0 != encoder->private_);
1845         FLAC__ASSERT(0 != encoder->protected_);
1846         return encoder->protected_->bits_per_sample;
1847 }
1848
1849 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(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_->sample_rate;
1855 }
1856
1857 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1858 {
1859         FLAC__ASSERT(0 != encoder);
1860         FLAC__ASSERT(0 != encoder->private_);
1861         FLAC__ASSERT(0 != encoder->protected_);
1862         return encoder->protected_->blocksize;
1863 }
1864
1865 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1866 {
1867         FLAC__ASSERT(0 != encoder);
1868         FLAC__ASSERT(0 != encoder->private_);
1869         FLAC__ASSERT(0 != encoder->protected_);
1870         return encoder->protected_->do_mid_side_stereo;
1871 }
1872
1873 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1874 {
1875         FLAC__ASSERT(0 != encoder);
1876         FLAC__ASSERT(0 != encoder->private_);
1877         FLAC__ASSERT(0 != encoder->protected_);
1878         return encoder->protected_->loose_mid_side_stereo;
1879 }
1880
1881 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1882 {
1883         FLAC__ASSERT(0 != encoder);
1884         FLAC__ASSERT(0 != encoder->private_);
1885         FLAC__ASSERT(0 != encoder->protected_);
1886         return encoder->protected_->max_lpc_order;
1887 }
1888
1889 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1890 {
1891         FLAC__ASSERT(0 != encoder);
1892         FLAC__ASSERT(0 != encoder->private_);
1893         FLAC__ASSERT(0 != encoder->protected_);
1894         return encoder->protected_->qlp_coeff_precision;
1895 }
1896
1897 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1898 {
1899         FLAC__ASSERT(0 != encoder);
1900         FLAC__ASSERT(0 != encoder->private_);
1901         FLAC__ASSERT(0 != encoder->protected_);
1902         return encoder->protected_->do_qlp_coeff_prec_search;
1903 }
1904
1905 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1906 {
1907         FLAC__ASSERT(0 != encoder);
1908         FLAC__ASSERT(0 != encoder->private_);
1909         FLAC__ASSERT(0 != encoder->protected_);
1910         return encoder->protected_->do_escape_coding;
1911 }
1912
1913 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1914 {
1915         FLAC__ASSERT(0 != encoder);
1916         FLAC__ASSERT(0 != encoder->private_);
1917         FLAC__ASSERT(0 != encoder->protected_);
1918         return encoder->protected_->do_exhaustive_model_search;
1919 }
1920
1921 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1922 {
1923         FLAC__ASSERT(0 != encoder);
1924         FLAC__ASSERT(0 != encoder->private_);
1925         FLAC__ASSERT(0 != encoder->protected_);
1926         return encoder->protected_->min_residual_partition_order;
1927 }
1928
1929 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1930 {
1931         FLAC__ASSERT(0 != encoder);
1932         FLAC__ASSERT(0 != encoder->private_);
1933         FLAC__ASSERT(0 != encoder->protected_);
1934         return encoder->protected_->max_residual_partition_order;
1935 }
1936
1937 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1938 {
1939         FLAC__ASSERT(0 != encoder);
1940         FLAC__ASSERT(0 != encoder->private_);
1941         FLAC__ASSERT(0 != encoder->protected_);
1942         return encoder->protected_->rice_parameter_search_dist;
1943 }
1944
1945 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1946 {
1947         FLAC__ASSERT(0 != encoder);
1948         FLAC__ASSERT(0 != encoder->private_);
1949         FLAC__ASSERT(0 != encoder->protected_);
1950         return encoder->protected_->total_samples_estimate;
1951 }
1952
1953 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1954 {
1955         unsigned i, j = 0, channel;
1956         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1957
1958         FLAC__ASSERT(0 != encoder);
1959         FLAC__ASSERT(0 != encoder->private_);
1960         FLAC__ASSERT(0 != encoder->protected_);
1961         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1962
1963         do {
1964                 const unsigned n = flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
1965
1966                 if(encoder->protected_->verify)
1967                         append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
1968
1969                 for(channel = 0; channel < channels; channel++)
1970                         memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
1971
1972                 if(encoder->protected_->do_mid_side_stereo) {
1973                         FLAC__ASSERT(channels == 2);
1974                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
1975                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1976                                 encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
1977                                 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' ! */
1978                         }
1979                 }
1980                 else
1981                         j += n;
1982
1983                 encoder->private_->current_sample_number += n;
1984
1985                 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
1986                 if(encoder->private_->current_sample_number > blocksize) {
1987                         FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
1988                         FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
1989                         if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
1990                                 return false;
1991                         /* move unprocessed overread samples to beginnings of arrays */
1992                         for(channel = 0; channel < channels; channel++)
1993                                 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
1994                         if(encoder->protected_->do_mid_side_stereo) {
1995                                 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
1996                                 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
1997                         }
1998                         encoder->private_->current_sample_number = 1;
1999                 }
2000         } while(j < samples);
2001
2002         return true;
2003 }
2004
2005 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2006 {
2007         unsigned i, j, k, channel;
2008         FLAC__int32 x, mid, side;
2009         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2010
2011         FLAC__ASSERT(0 != encoder);
2012         FLAC__ASSERT(0 != encoder->private_);
2013         FLAC__ASSERT(0 != encoder->protected_);
2014         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2015
2016         j = k = 0;
2017         /*
2018          * we have several flavors of the same basic loop, optimized for
2019          * different conditions:
2020          */
2021         if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2022                 /*
2023                  * stereo coding: unroll channel loop
2024                  */
2025                 do {
2026                         if(encoder->protected_->verify)
2027                                 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2028
2029                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2030                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2031                                 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2032                                 x = buffer[k++];
2033                                 encoder->private_->integer_signal[1][i] = x;
2034                                 mid += x;
2035                                 side -= x;
2036                                 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2037                                 encoder->private_->integer_signal_mid_side[1][i] = side;
2038                                 encoder->private_->integer_signal_mid_side[0][i] = mid;
2039                         }
2040                         encoder->private_->current_sample_number = i;
2041                         /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2042                         if(i > blocksize) {
2043                                 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2044                                         return false;
2045                                 /* move unprocessed overread samples to beginnings of arrays */
2046                                 FLAC__ASSERT(i == blocksize+OVERREAD_);
2047                                 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2048                                 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
2049                                 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
2050                                 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2051                                 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2052                                 encoder->private_->current_sample_number = 1;
2053                         }
2054                 } while(j < samples);
2055         }
2056         else {
2057                 /*
2058                  * independent channel coding: buffer each channel in inner loop
2059                  */
2060                 do {
2061                         if(encoder->protected_->verify)
2062                                 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2063
2064                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2065                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2066                                 for(channel = 0; channel < channels; channel++)
2067                                         encoder->private_->integer_signal[channel][i] = buffer[k++];
2068                         }
2069                         encoder->private_->current_sample_number = i;
2070                         /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2071                         if(i > blocksize) {
2072                                 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2073                                         return false;
2074                                 /* move unprocessed overread samples to beginnings of arrays */
2075                                 FLAC__ASSERT(i == blocksize+OVERREAD_);
2076                                 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2077                                 for(channel = 0; channel < channels; channel++)
2078                                         encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2079                                 encoder->private_->current_sample_number = 1;
2080                         }
2081                 } while(j < samples);
2082         }
2083
2084         return true;
2085 }
2086
2087 /***********************************************************************
2088  *
2089  * Private class methods
2090  *
2091  ***********************************************************************/
2092
2093 void set_defaults_(FLAC__StreamEncoder *encoder)
2094 {
2095         FLAC__ASSERT(0 != encoder);
2096
2097 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2098         encoder->protected_->verify = true;
2099 #else
2100         encoder->protected_->verify = false;
2101 #endif
2102         encoder->protected_->streamable_subset = true;
2103         encoder->protected_->do_md5 = true;
2104         encoder->protected_->do_mid_side_stereo = false;
2105         encoder->protected_->loose_mid_side_stereo = false;
2106         encoder->protected_->channels = 2;
2107         encoder->protected_->bits_per_sample = 16;
2108         encoder->protected_->sample_rate = 44100;
2109         encoder->protected_->blocksize = 0;
2110 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2111         encoder->protected_->num_apodizations = 1;
2112         encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2113         encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2114 #endif
2115         encoder->protected_->max_lpc_order = 0;
2116         encoder->protected_->qlp_coeff_precision = 0;
2117         encoder->protected_->do_qlp_coeff_prec_search = false;
2118         encoder->protected_->do_exhaustive_model_search = false;
2119         encoder->protected_->do_escape_coding = false;
2120         encoder->protected_->min_residual_partition_order = 0;
2121         encoder->protected_->max_residual_partition_order = 0;
2122         encoder->protected_->rice_parameter_search_dist = 0;
2123         encoder->protected_->total_samples_estimate = 0;
2124         encoder->protected_->metadata = 0;
2125         encoder->protected_->num_metadata_blocks = 0;
2126
2127         encoder->private_->seek_table = 0;
2128         encoder->private_->disable_constant_subframes = false;
2129         encoder->private_->disable_fixed_subframes = false;
2130         encoder->private_->disable_verbatim_subframes = false;
2131 #if FLAC__HAS_OGG
2132         encoder->private_->is_ogg = false;
2133 #endif
2134         encoder->private_->read_callback = 0;
2135         encoder->private_->write_callback = 0;
2136         encoder->private_->seek_callback = 0;
2137         encoder->private_->tell_callback = 0;
2138         encoder->private_->metadata_callback = 0;
2139         encoder->private_->progress_callback = 0;
2140         encoder->private_->client_data = 0;
2141
2142 #if FLAC__HAS_OGG
2143         FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2144 #endif
2145
2146         FLAC__stream_encoder_set_compression_level(encoder, 5);
2147 }
2148
2149 void free_(FLAC__StreamEncoder *encoder)
2150 {
2151         unsigned i, channel;
2152
2153         FLAC__ASSERT(0 != encoder);
2154         if(encoder->protected_->metadata) {
2155                 free(encoder->protected_->metadata);
2156                 encoder->protected_->metadata = 0;
2157                 encoder->protected_->num_metadata_blocks = 0;
2158         }
2159         for(i = 0; i < encoder->protected_->channels; i++) {
2160                 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2161                         free(encoder->private_->integer_signal_unaligned[i]);
2162                         encoder->private_->integer_signal_unaligned[i] = 0;
2163                 }
2164 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2165                 if(0 != encoder->private_->real_signal_unaligned[i]) {
2166                         free(encoder->private_->real_signal_unaligned[i]);
2167                         encoder->private_->real_signal_unaligned[i] = 0;
2168                 }
2169 #endif
2170         }
2171         for(i = 0; i < 2; i++) {
2172                 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2173                         free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2174                         encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2175                 }
2176 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2177                 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2178                         free(encoder->private_->real_signal_mid_side_unaligned[i]);
2179                         encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2180                 }
2181 #endif
2182         }
2183 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2184         for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2185                 if(0 != encoder->private_->window_unaligned[i]) {
2186                         free(encoder->private_->window_unaligned[i]);
2187                         encoder->private_->window_unaligned[i] = 0;
2188                 }
2189         }
2190         if(0 != encoder->private_->windowed_signal_unaligned) {
2191                 free(encoder->private_->windowed_signal_unaligned);
2192                 encoder->private_->windowed_signal_unaligned = 0;
2193         }
2194 #endif
2195         for(channel = 0; channel < encoder->protected_->channels; channel++) {
2196                 for(i = 0; i < 2; i++) {
2197                         if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2198                                 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2199                                 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2200                         }
2201                 }
2202         }
2203         for(channel = 0; channel < 2; channel++) {
2204                 for(i = 0; i < 2; i++) {
2205                         if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2206                                 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2207                                 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2208                         }
2209                 }
2210         }
2211         if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2212                 free(encoder->private_->abs_residual_partition_sums_unaligned);
2213                 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2214         }
2215         if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2216                 free(encoder->private_->raw_bits_per_partition_unaligned);
2217                 encoder->private_->raw_bits_per_partition_unaligned = 0;
2218         }
2219         if(encoder->protected_->verify) {
2220                 for(i = 0; i < encoder->protected_->channels; i++) {
2221                         if(0 != encoder->private_->verify.input_fifo.data[i]) {
2222                                 free(encoder->private_->verify.input_fifo.data[i]);
2223                                 encoder->private_->verify.input_fifo.data[i] = 0;
2224                         }
2225                 }
2226         }
2227         FLAC__bitwriter_free(encoder->private_->frame);
2228 }
2229
2230 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2231 {
2232         FLAC__bool ok;
2233         unsigned i, channel;
2234
2235         FLAC__ASSERT(new_blocksize > 0);
2236         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2237         FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2238
2239         /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2240         if(new_blocksize <= encoder->private_->input_capacity)
2241                 return true;
2242
2243         ok = true;
2244
2245         /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
2246          * requires that the input arrays (in our case the integer signals)
2247          * have a buffer of up to 3 zeroes in front (at negative indices) for
2248          * alignment purposes; we use 4 in front to keep the data well-aligned.
2249          */
2250
2251         for(i = 0; ok && i < encoder->protected_->channels; i++) {
2252                 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2253                 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2254                 encoder->private_->integer_signal[i] += 4;
2255 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2256 #if 0 /* @@@ currently unused */
2257                 if(encoder->protected_->max_lpc_order > 0)
2258                         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2259 #endif
2260 #endif
2261         }
2262         for(i = 0; ok && i < 2; i++) {
2263                 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]);
2264                 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2265                 encoder->private_->integer_signal_mid_side[i] += 4;
2266 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2267 #if 0 /* @@@ currently unused */
2268                 if(encoder->protected_->max_lpc_order > 0)
2269                         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]);
2270 #endif
2271 #endif
2272         }
2273 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2274         if(ok && encoder->protected_->max_lpc_order > 0) {
2275                 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2276                         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2277                 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2278         }
2279 #endif
2280         for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2281                 for(i = 0; ok && i < 2; i++) {
2282                         ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2283                 }
2284         }
2285         for(channel = 0; ok && channel < 2; channel++) {
2286                 for(i = 0; ok && i < 2; i++) {
2287                         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]);
2288                 }
2289         }
2290         /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2291         /*@@@ 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) */
2292         ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2293         if(encoder->protected_->do_escape_coding)
2294                 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2295
2296         /* now adjust the windows if the blocksize has changed */
2297 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2298         if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2299                 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2300                         switch(encoder->protected_->apodizations[i].type) {
2301                                 case FLAC__APODIZATION_BARTLETT:
2302                                         FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2303                                         break;
2304                                 case FLAC__APODIZATION_BARTLETT_HANN:
2305                                         FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2306                                         break;
2307                                 case FLAC__APODIZATION_BLACKMAN:
2308                                         FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2309                                         break;
2310                                 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2311                                         FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2312                                         break;
2313                                 case FLAC__APODIZATION_CONNES:
2314                                         FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2315                                         break;
2316                                 case FLAC__APODIZATION_FLATTOP:
2317                                         FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2318                                         break;
2319                                 case FLAC__APODIZATION_GAUSS:
2320                                         FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2321                                         break;
2322                                 case FLAC__APODIZATION_HAMMING:
2323                                         FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2324                                         break;
2325                                 case FLAC__APODIZATION_HANN:
2326                                         FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2327                                         break;
2328                                 case FLAC__APODIZATION_KAISER_BESSEL:
2329                                         FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2330                                         break;
2331                                 case FLAC__APODIZATION_NUTTALL:
2332                                         FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2333                                         break;
2334                                 case FLAC__APODIZATION_RECTANGLE:
2335                                         FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2336                                         break;
2337                                 case FLAC__APODIZATION_TRIANGLE:
2338                                         FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2339                                         break;
2340                                 case FLAC__APODIZATION_TUKEY:
2341                                         FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2342                                         break;
2343                                 case FLAC__APODIZATION_WELCH:
2344                                         FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2345                                         break;
2346                                 default:
2347                                         FLAC__ASSERT(0);
2348                                         /* double protection */
2349                                         FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2350                                         break;
2351                         }
2352                 }
2353         }
2354 #endif
2355
2356         if(ok)
2357                 encoder->private_->input_capacity = new_blocksize;
2358         else
2359                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2360
2361         return ok;
2362 }
2363
2364 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2365 {
2366         const FLAC__byte *buffer;
2367         size_t bytes;
2368
2369         FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2370
2371         if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2372                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2373                 return false;
2374         }
2375
2376         if(encoder->protected_->verify) {
2377                 encoder->private_->verify.output.data = buffer;
2378                 encoder->private_->verify.output.bytes = bytes;
2379                 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2380                         encoder->private_->verify.needs_magic_hack = true;
2381                 }
2382                 else {
2383                         if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2384                                 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2385                                 FLAC__bitwriter_clear(encoder->private_->frame);
2386                                 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2387                                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2388                                 return false;
2389                         }
2390                 }
2391         }
2392
2393         if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2394                 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2395                 FLAC__bitwriter_clear(encoder->private_->frame);
2396                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2397                 return false;
2398         }
2399
2400         FLAC__bitwriter_release_buffer(encoder->private_->frame);
2401         FLAC__bitwriter_clear(encoder->private_->frame);
2402
2403         if(samples > 0) {
2404                 encoder->private_->streaminfo.data.stream_info.min_framesize = flac_min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2405                 encoder->private_->streaminfo.data.stream_info.max_framesize = flac_max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2406         }
2407
2408         return true;
2409 }
2410
2411 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2412 {
2413         FLAC__StreamEncoderWriteStatus status;
2414         FLAC__uint64 output_position = 0;
2415
2416         /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2417         if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2418                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2419                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2420         }
2421
2422         /*
2423          * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2424          */
2425         if(samples == 0) {
2426                 FLAC__MetadataType type = (buffer[0] & 0x7f);
2427                 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2428                         encoder->protected_->streaminfo_offset = output_position;
2429                 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2430                         encoder->protected_->seektable_offset = output_position;
2431         }
2432
2433         /*
2434          * Mark the current seek point if hit (if audio_offset == 0 that
2435          * means we're still writing metadata and haven't hit the first
2436          * frame yet)
2437          */
2438         if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2439                 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2440                 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2441                 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2442                 FLAC__uint64 test_sample;
2443                 unsigned i;
2444                 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2445                         test_sample = encoder->private_->seek_table->points[i].sample_number;
2446                         if(test_sample > frame_last_sample) {
2447                                 break;
2448                         }
2449                         else if(test_sample >= frame_first_sample) {
2450                                 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2451                                 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2452                                 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2453                                 encoder->private_->first_seekpoint_to_check++;
2454                                 /* DO NOT: "break;" and here's why:
2455                                  * The seektable template may contain more than one target
2456                                  * sample for any given frame; we will keep looping, generating
2457                                  * duplicate seekpoints for them, and we'll clean it up later,
2458                                  * just before writing the seektable back to the metadata.
2459                                  */
2460                         }
2461                         else {
2462                                 encoder->private_->first_seekpoint_to_check++;
2463                         }
2464                 }
2465         }
2466
2467 #if FLAC__HAS_OGG
2468         if(encoder->private_->is_ogg) {
2469                 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2470                         &encoder->protected_->ogg_encoder_aspect,
2471                         buffer,
2472                         bytes,
2473                         samples,
2474                         encoder->private_->current_frame_number,
2475                         is_last_block,
2476                         (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2477                         encoder,
2478                         encoder->private_->client_data
2479                 );
2480         }
2481         else
2482 #endif
2483         status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2484
2485         if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2486                 encoder->private_->bytes_written += bytes;
2487                 encoder->private_->samples_written += samples;
2488                 /* we keep a high watermark on the number of frames written because
2489                  * when the encoder goes back to write metadata, 'current_frame'
2490                  * will drop back to 0.
2491                  */
2492                 encoder->private_->frames_written = flac_max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2493         }
2494         else
2495                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2496
2497         return status;
2498 }
2499
2500 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2501 void update_metadata_(const FLAC__StreamEncoder *encoder)
2502 {
2503         FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2504         const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2505         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2506         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2507         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2508         const unsigned bps = metadata->data.stream_info.bits_per_sample;
2509         FLAC__StreamEncoderSeekStatus seek_status;
2510
2511         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2512
2513         /* All this is based on intimate knowledge of the stream header
2514          * layout, but a change to the header format that would break this
2515          * would also break all streams encoded in the previous format.
2516          */
2517
2518         /*
2519          * Write MD5 signature
2520          */
2521         {
2522                 const unsigned md5_offset =
2523                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2524                         (
2525                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2526                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2527                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2528                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2529                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2530                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2531                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2532                                 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2533                         ) / 8;
2534
2535                 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2536                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2537                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2538                         return;
2539                 }
2540                 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2541                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2542                         return;
2543                 }
2544         }
2545
2546         /*
2547          * Write total samples
2548          */
2549         {
2550                 const unsigned total_samples_byte_offset =
2551                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2552                         (
2553                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2554                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2555                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2556                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2557                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2558                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2559                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2560                                 - 4
2561                         ) / 8;
2562
2563                 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2564                 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2565                 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2566                 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2567                 b[4] = (FLAC__byte)(samples & 0xFF);
2568                 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) {
2569                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2570                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2571                         return;
2572                 }
2573                 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2574                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2575                         return;
2576                 }
2577         }
2578
2579         /*
2580          * Write min/max framesize
2581          */
2582         {
2583                 const unsigned min_framesize_offset =
2584                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2585                         (
2586                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2587                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2588                         ) / 8;
2589
2590                 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2591                 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2592                 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2593                 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2594                 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2595                 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2596                 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) {
2597                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2598                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2599                         return;
2600                 }
2601                 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2602                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2603                         return;
2604                 }
2605         }
2606
2607         /*
2608          * Write seektable
2609          */
2610         if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2611                 unsigned i;
2612
2613                 FLAC__format_seektable_sort(encoder->private_->seek_table);
2614
2615                 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2616
2617                 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) {
2618                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2619                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2620                         return;
2621                 }
2622
2623                 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2624                         FLAC__uint64 xx;
2625                         unsigned x;
2626                         xx = encoder->private_->seek_table->points[i].sample_number;
2627                         b[7] = (FLAC__byte)xx; xx >>= 8;
2628                         b[6] = (FLAC__byte)xx; xx >>= 8;
2629                         b[5] = (FLAC__byte)xx; xx >>= 8;
2630                         b[4] = (FLAC__byte)xx; xx >>= 8;
2631                         b[3] = (FLAC__byte)xx; xx >>= 8;
2632                         b[2] = (FLAC__byte)xx; xx >>= 8;
2633                         b[1] = (FLAC__byte)xx; xx >>= 8;
2634                         b[0] = (FLAC__byte)xx; xx >>= 8;
2635                         xx = encoder->private_->seek_table->points[i].stream_offset;
2636                         b[15] = (FLAC__byte)xx; xx >>= 8;
2637                         b[14] = (FLAC__byte)xx; xx >>= 8;
2638                         b[13] = (FLAC__byte)xx; xx >>= 8;
2639                         b[12] = (FLAC__byte)xx; xx >>= 8;
2640                         b[11] = (FLAC__byte)xx; xx >>= 8;
2641                         b[10] = (FLAC__byte)xx; xx >>= 8;
2642                         b[9] = (FLAC__byte)xx; xx >>= 8;
2643                         b[8] = (FLAC__byte)xx; xx >>= 8;
2644                         x = encoder->private_->seek_table->points[i].frame_samples;
2645                         b[17] = (FLAC__byte)x; x >>= 8;
2646                         b[16] = (FLAC__byte)x; x >>= 8;
2647                         if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2648                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2649                                 return;
2650                         }
2651                 }
2652         }
2653 }
2654
2655 #if FLAC__HAS_OGG
2656 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2657 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2658 {
2659         /* the # of bytes in the 1st packet that precede the STREAMINFO */
2660         static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2661                 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2662                 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2663                 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2664                 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2665                 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2666                 FLAC__STREAM_SYNC_LENGTH
2667         ;
2668         FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2669         const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2670         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2671         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2672         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2673         ogg_page page;
2674
2675         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2676         FLAC__ASSERT(0 != encoder->private_->seek_callback);
2677
2678         /* Pre-check that client supports seeking, since we don't want the
2679          * ogg_helper code to ever have to deal with this condition.
2680          */
2681         if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2682                 return;
2683
2684         /* All this is based on intimate knowledge of the stream header
2685          * layout, but a change to the header format that would break this
2686          * would also break all streams encoded in the previous format.
2687          */
2688
2689         /**
2690          ** Write STREAMINFO stats
2691          **/
2692         simple_ogg_page__init(&page);
2693         if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2694                 simple_ogg_page__clear(&page);
2695                 return; /* state already set */
2696         }
2697
2698         /*
2699          * Write MD5 signature
2700          */
2701         {
2702                 const unsigned md5_offset =
2703                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2704                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2705                         (
2706                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2707                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2708                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2709                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2710                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2711                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2712                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2713                                 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2714                         ) / 8;
2715
2716                 if(md5_offset + 16 > (unsigned)page.body_len) {
2717                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2718                         simple_ogg_page__clear(&page);
2719                         return;
2720                 }
2721                 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2722         }
2723
2724         /*
2725          * Write total samples
2726          */
2727         {
2728                 const unsigned total_samples_byte_offset =
2729                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2730                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2731                         (
2732                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2733                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2734                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2735                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2736                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2737                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2738                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2739                                 - 4
2740                         ) / 8;
2741
2742                 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2743                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2744                         simple_ogg_page__clear(&page);
2745                         return;
2746                 }
2747                 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2748                 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2749                 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2750                 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2751                 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2752                 b[4] = (FLAC__byte)(samples & 0xFF);
2753                 memcpy(page.body + total_samples_byte_offset, b, 5);
2754         }
2755
2756         /*
2757          * Write min/max framesize
2758          */
2759         {
2760                 const unsigned min_framesize_offset =
2761                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2762                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2763                         (
2764                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2765                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2766                         ) / 8;
2767
2768                 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2769                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2770                         simple_ogg_page__clear(&page);
2771                         return;
2772                 }
2773                 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2774                 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2775                 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2776                 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2777                 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2778                 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2779                 memcpy(page.body + min_framesize_offset, b, 6);
2780         }
2781         if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2782                 simple_ogg_page__clear(&page);
2783                 return; /* state already set */
2784         }
2785         simple_ogg_page__clear(&page);
2786
2787         /*
2788          * Write seektable
2789          */
2790         if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2791                 unsigned i;
2792                 FLAC__byte *p;
2793
2794                 FLAC__format_seektable_sort(encoder->private_->seek_table);
2795
2796                 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2797
2798                 simple_ogg_page__init(&page);
2799                 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2800                         simple_ogg_page__clear(&page);
2801                         return; /* state already set */
2802                 }
2803
2804                 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
2805                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2806                         simple_ogg_page__clear(&page);
2807                         return;
2808                 }
2809
2810                 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
2811                         FLAC__uint64 xx;
2812                         unsigned x;
2813                         xx = encoder->private_->seek_table->points[i].sample_number;
2814                         b[7] = (FLAC__byte)xx; xx >>= 8;
2815                         b[6] = (FLAC__byte)xx; xx >>= 8;
2816                         b[5] = (FLAC__byte)xx; xx >>= 8;
2817                         b[4] = (FLAC__byte)xx; xx >>= 8;
2818                         b[3] = (FLAC__byte)xx; xx >>= 8;
2819                         b[2] = (FLAC__byte)xx; xx >>= 8;
2820                         b[1] = (FLAC__byte)xx; xx >>= 8;
2821                         b[0] = (FLAC__byte)xx; xx >>= 8;
2822                         xx = encoder->private_->seek_table->points[i].stream_offset;
2823                         b[15] = (FLAC__byte)xx; xx >>= 8;
2824                         b[14] = (FLAC__byte)xx; xx >>= 8;
2825                         b[13] = (FLAC__byte)xx; xx >>= 8;
2826                         b[12] = (FLAC__byte)xx; xx >>= 8;
2827                         b[11] = (FLAC__byte)xx; xx >>= 8;
2828                         b[10] = (FLAC__byte)xx; xx >>= 8;
2829                         b[9] = (FLAC__byte)xx; xx >>= 8;
2830                         b[8] = (FLAC__byte)xx; xx >>= 8;
2831                         x = encoder->private_->seek_table->points[i].frame_samples;
2832                         b[17] = (FLAC__byte)x; x >>= 8;
2833                         b[16] = (FLAC__byte)x; x >>= 8;
2834                         memcpy(p, b, 18);
2835                 }
2836
2837                 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2838                         simple_ogg_page__clear(&page);
2839                         return; /* state already set */
2840                 }
2841                 simple_ogg_page__clear(&page);
2842         }
2843 }
2844 #endif
2845
2846 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
2847 {
2848         FLAC__uint16 crc;
2849         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2850
2851         /*
2852          * Accumulate raw signal to the MD5 signature
2853          */
2854         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)) {
2855                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2856                 return false;
2857         }
2858
2859         /*
2860          * Process the frame header and subframes into the frame bitbuffer
2861          */
2862         if(!process_subframes_(encoder, is_fractional_block)) {
2863                 /* the above function sets the state for us in case of an error */
2864                 return false;
2865         }
2866
2867         /*
2868          * Zero-pad the frame to a byte_boundary
2869          */
2870         if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
2871                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2872                 return false;
2873         }
2874
2875         /*
2876          * CRC-16 the whole thing
2877          */
2878         FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2879         if(
2880                 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
2881                 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
2882         ) {
2883                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2884                 return false;
2885         }
2886
2887         /*
2888          * Write it
2889          */
2890         if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
2891                 /* the above function sets the state for us in case of an error */
2892                 return false;
2893         }
2894
2895         /*
2896          * Get ready for the next frame
2897          */
2898         encoder->private_->current_sample_number = 0;
2899         encoder->private_->current_frame_number++;
2900         encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
2901
2902         return true;
2903 }
2904
2905 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
2906 {
2907         FLAC__FrameHeader frame_header;
2908         unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
2909         FLAC__bool do_independent, do_mid_side;
2910
2911         /*
2912          * Calculate the min,max Rice partition orders
2913          */
2914         if(is_fractional_block) {
2915                 max_partition_order = 0;
2916         }
2917         else {
2918                 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
2919                 max_partition_order = flac_min(max_partition_order, encoder->protected_->max_residual_partition_order);
2920         }
2921         min_partition_order = flac_min(min_partition_order, max_partition_order);
2922
2923         /*
2924          * Setup the frame
2925          */
2926         frame_header.blocksize = encoder->protected_->blocksize;
2927         frame_header.sample_rate = encoder->protected_->sample_rate;
2928         frame_header.channels = encoder->protected_->channels;
2929         frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
2930         frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
2931         frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2932         frame_header.number.frame_number = encoder->private_->current_frame_number;
2933
2934         /*
2935          * Figure out what channel assignments to try
2936          */
2937         if(encoder->protected_->do_mid_side_stereo) {
2938                 if(encoder->protected_->loose_mid_side_stereo) {
2939                         if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
2940                                 do_independent = true;
2941                                 do_mid_side = true;
2942                         }
2943                         else {
2944                                 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
2945                                 do_mid_side = !do_independent;
2946                         }
2947                 }
2948                 else {
2949                         do_independent = true;
2950                         do_mid_side = true;
2951                 }
2952         }
2953         else {
2954                 do_independent = true;
2955                 do_mid_side = false;
2956         }
2957
2958         FLAC__ASSERT(do_independent || do_mid_side);
2959
2960         /*
2961          * Check for wasted bits; set effective bps for each subframe
2962          */
2963         if(do_independent) {
2964                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2965                         const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
2966                         encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
2967                         encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
2968                 }
2969         }
2970         if(do_mid_side) {
2971                 FLAC__ASSERT(encoder->protected_->channels == 2);
2972                 for(channel = 0; channel < 2; channel++) {
2973                         const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
2974                         encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
2975                         encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
2976                 }
2977         }
2978
2979         /*
2980          * First do a normal encoding pass of each independent channel
2981          */
2982         if(do_independent) {
2983                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2984                         if(!
2985                                 process_subframe_(
2986                                         encoder,
2987                                         min_partition_order,
2988                                         max_partition_order,
2989                                         &frame_header,
2990                                         encoder->private_->subframe_bps[channel],
2991                                         encoder->private_->integer_signal[channel],
2992                                         encoder->private_->subframe_workspace_ptr[channel],
2993                                         encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
2994                                         encoder->private_->residual_workspace[channel],
2995                                         encoder->private_->best_subframe+channel,
2996                                         encoder->private_->best_subframe_bits+channel
2997                                 )
2998                         )
2999                                 return false;
3000                 }
3001         }
3002
3003         /*
3004          * Now do mid and side channels if requested
3005          */
3006         if(do_mid_side) {
3007                 FLAC__ASSERT(encoder->protected_->channels == 2);
3008
3009                 for(channel = 0; channel < 2; channel++) {
3010                         if(!
3011                                 process_subframe_(
3012                                         encoder,
3013                                         min_partition_order,
3014                                         max_partition_order,
3015                                         &frame_header,
3016                                         encoder->private_->subframe_bps_mid_side[channel],
3017                                         encoder->private_->integer_signal_mid_side[channel],
3018                                         encoder->private_->subframe_workspace_ptr_mid_side[channel],
3019                                         encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3020                                         encoder->private_->residual_workspace_mid_side[channel],
3021                                         encoder->private_->best_subframe_mid_side+channel,
3022                                         encoder->private_->best_subframe_bits_mid_side+channel
3023                                 )
3024                         )
3025                                 return false;
3026                 }
3027         }
3028
3029         /*
3030          * Compose the frame bitbuffer
3031          */
3032         if(do_mid_side) {
3033                 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3034                 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3035                 FLAC__ChannelAssignment channel_assignment;
3036
3037                 FLAC__ASSERT(encoder->protected_->channels == 2);
3038
3039                 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3040                         channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3041                 }
3042                 else {
3043                         unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3044                         unsigned min_bits;
3045                         int ca;
3046
3047                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3048                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE   == 1);
3049                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE  == 2);
3050                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE    == 3);
3051                         FLAC__ASSERT(do_independent && do_mid_side);
3052
3053                         /* We have to figure out which channel assignent results in the smallest frame */
3054                         bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits         [1];
3055                         bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE  ] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits_mid_side[1];
3056                         bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits         [1] + encoder->private_->best_subframe_bits_mid_side[1];
3057                         bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE   ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3058
3059                         channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3060                         min_bits = bits[channel_assignment];
3061                         for(ca = 1; ca <= 3; ca++) {
3062                                 if(bits[ca] < min_bits) {
3063                                         min_bits = bits[ca];
3064                                         channel_assignment = (FLAC__ChannelAssignment)ca;
3065                                 }
3066                         }
3067                 }
3068
3069                 frame_header.channel_assignment = channel_assignment;
3070
3071                 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3072                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3073                         return false;
3074                 }
3075
3076                 switch(channel_assignment) {
3077                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3078                                 left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3079                                 right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
3080                                 break;
3081                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3082                                 left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3083                                 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3084                                 break;
3085                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3086                                 left_subframe  = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3087                                 right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
3088                                 break;
3089                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3090                                 left_subframe  = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3091                                 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3092                                 break;
3093                         default:
3094                                 FLAC__ASSERT(0);
3095                 }
3096
3097                 switch(channel_assignment) {
3098                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3099                                 left_bps  = encoder->private_->subframe_bps         [0];
3100                                 right_bps = encoder->private_->subframe_bps         [1];
3101                                 break;
3102                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3103                                 left_bps  = encoder->private_->subframe_bps         [0];
3104                                 right_bps = encoder->private_->subframe_bps_mid_side[1];
3105                                 break;
3106                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3107                                 left_bps  = encoder->private_->subframe_bps_mid_side[1];
3108                                 right_bps = encoder->private_->subframe_bps         [1];
3109                                 break;
3110                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3111                                 left_bps  = encoder->private_->subframe_bps_mid_side[0];
3112                                 right_bps = encoder->private_->subframe_bps_mid_side[1];
3113                                 break;
3114                         default:
3115                                 FLAC__ASSERT(0);
3116                 }
3117
3118                 /* note that encoder_add_subframe_ sets the state for us in case of an error */
3119                 if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3120                         return false;
3121                 if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3122                         return false;
3123         }
3124         else {
3125                 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3126                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3127                         return false;
3128                 }
3129
3130                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3131                         if(!add_subframe_(encoder, frame_header.blocksize, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame)) {
3132                                 /* the above function sets the state for us in case of an error */
3133                                 return false;
3134                         }
3135                 }
3136         }
3137
3138         if(encoder->protected_->loose_mid_side_stereo) {
3139                 encoder->private_->loose_mid_side_stereo_frame_count++;
3140                 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3141                         encoder->private_->loose_mid_side_stereo_frame_count = 0;
3142         }
3143
3144         encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3145
3146         return true;
3147 }
3148
3149 FLAC__bool process_subframe_(
3150         FLAC__StreamEncoder *encoder,
3151         unsigned min_partition_order,
3152         unsigned max_partition_order,
3153         const FLAC__FrameHeader *frame_header,
3154         unsigned subframe_bps,
3155         const FLAC__int32 integer_signal[],
3156         FLAC__Subframe *subframe[2],
3157         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3158         FLAC__int32 *residual[2],
3159         unsigned *best_subframe,
3160         unsigned *best_bits
3161 )
3162 {
3163 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3164         FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3165 #else
3166         FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3167 #endif
3168 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3169         FLAC__double lpc_residual_bits_per_sample;
3170         FLAC__real autoc[FLAC__MAX_LPC_ORDER+1]; /* WATCHOUT: the size is important even though encoder->protected_->max_lpc_order might be less; some asm routines need all the space */
3171         FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3172         unsigned min_lpc_order, max_lpc_order, lpc_order;
3173         unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3174 #endif
3175         unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3176         unsigned rice_parameter;
3177         unsigned _candidate_bits, _best_bits;
3178         unsigned _best_subframe;
3179         /* only use RICE2 partitions if stream bps > 16 */
3180         const unsigned rice_parameter_limit = FLAC__stream_encoder_get_bits_per_sample(encoder) > 16? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
3181
3182         FLAC__ASSERT(frame_header->blocksize > 0);
3183
3184         /* verbatim subframe is the baseline against which we measure other compressed subframes */
3185         _best_subframe = 0;
3186         if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3187                 _best_bits = UINT_MAX;
3188         else
3189                 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3190
3191         if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3192                 unsigned signal_is_constant = false;
3193                 guess_fixed_order = encoder->private_->local_fixed_compute_best_predictor(integer_signal+FLAC__MAX_FIXED_ORDER, frame_header->blocksize-FLAC__MAX_FIXED_ORDER, fixed_residual_bits_per_sample);
3194                 /* check for constant subframe */
3195                 if(
3196                         !encoder->private_->disable_constant_subframes &&
3197 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3198                         fixed_residual_bits_per_sample[1] == 0.0
3199 #else
3200                         fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3201 #endif
3202                 ) {
3203                         /* the above means it's possible all samples are the same value; now double-check it: */
3204                         unsigned i;
3205                         signal_is_constant = true;
3206                         for(i = 1; i < frame_header->blocksize; i++) {
3207                                 if(integer_signal[0] != integer_signal[i]) {
3208                                         signal_is_constant = false;
3209                                         break;
3210                                 }
3211                         }
3212                 }
3213                 if(signal_is_constant) {
3214                         _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3215                         if(_candidate_bits < _best_bits) {
3216                                 _best_subframe = !_best_subframe;
3217                                 _best_bits = _candidate_bits;
3218                         }
3219                 }
3220                 else {
3221                         if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3222                                 /* encode fixed */
3223                                 if(encoder->protected_->do_exhaustive_model_search) {
3224                                         min_fixed_order = 0;
3225                                         max_fixed_order = FLAC__MAX_FIXED_ORDER;
3226                                 }
3227                                 else {
3228                                         min_fixed_order = max_fixed_order = guess_fixed_order;
3229                                 }
3230                                 if(max_fixed_order >= frame_header->blocksize)
3231                                         max_fixed_order = frame_header->blocksize - 1;
3232                                 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3233 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3234                                         if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3235                                                 continue; /* don't even try */
3236                                         rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > 0.0)? (unsigned)(fixed_residual_bits_per_sample[fixed_order]+0.5) : 0; /* 0.5 is for rounding */
3237 #else
3238                                         if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3239                                                 continue; /* don't even try */
3240                                         rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > FLAC__FP_ZERO)? (unsigned)FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]+FLAC__FP_ONE_HALF) : 0; /* 0.5 is for rounding */
3241 #endif
3242                                         rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3243                                         if(rice_parameter >= rice_parameter_limit) {
3244 #ifdef DEBUG_VERBOSE
3245                                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
3246 #endif
3247                                                 rice_parameter = rice_parameter_limit - 1;
3248                                         }
3249                                         _candidate_bits =
3250                                                 evaluate_fixed_subframe_(
3251                                                         encoder,
3252                                                         integer_signal,
3253                                                         residual[!_best_subframe],
3254                                                         encoder->private_->abs_residual_partition_sums,
3255                                                         encoder->private_->raw_bits_per_partition,
3256                                                         frame_header->blocksize,
3257                                                         subframe_bps,
3258                                                         fixed_order,
3259                                                         rice_parameter,
3260                                                         rice_parameter_limit,
3261                                                         min_partition_order,
3262                                                         max_partition_order,
3263                                                         encoder->protected_->do_escape_coding,
3264                                                         encoder->protected_->rice_parameter_search_dist,
3265                                                         subframe[!_best_subframe],
3266                                                         partitioned_rice_contents[!_best_subframe]
3267                                                 );
3268                                         if(_candidate_bits < _best_bits) {
3269                                                 _best_subframe = !_best_subframe;
3270                                                 _best_bits = _candidate_bits;
3271                                         }
3272                                 }
3273                         }
3274
3275 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3276                         /* encode lpc */
3277                         if(encoder->protected_->max_lpc_order > 0) {
3278                                 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3279                                         max_lpc_order = frame_header->blocksize-1;
3280                                 else
3281                                         max_lpc_order = encoder->protected_->max_lpc_order;
3282                                 if(max_lpc_order > 0) {
3283                                         unsigned a;
3284                                         for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3285                                                 FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3286                                                 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3287                                                 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3288                                                 if(autoc[0] != 0.0) {
3289                                                         FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3290                                                         if(encoder->protected_->do_exhaustive_model_search) {
3291                                                                 min_lpc_order = 1;
3292                                                         }
3293                                                         else {
3294                                                                 const unsigned guess_lpc_order =
3295                                                                         FLAC__lpc_compute_best_order(
3296                                                                                 lpc_error,
3297                                                                                 max_lpc_order,
3298                                                                                 frame_header->blocksize,
3299                                                                                 subframe_bps + (
3300                                                                                         encoder->protected_->do_qlp_coeff_prec_search?
3301                                                                                                 FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
3302                                                                                                 encoder->protected_->qlp_coeff_precision
3303                                                                                 )
3304                                                                         );
3305                                                                 min_lpc_order = max_lpc_order = guess_lpc_order;
3306                                                         }
3307                                                         if(max_lpc_order >= frame_header->blocksize)
3308                                                                 max_lpc_order = frame_header->blocksize - 1;
3309                                                         for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
3310                                                                 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
3311                                                                 if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
3312                                                                         continue; /* don't even try */
3313                                                                 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
3314                                                                 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3315                                                                 if(rice_parameter >= rice_parameter_limit) {
3316 #ifdef DEBUG_VERBOSE
3317                                                                         fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
3318 #endif
3319                                                                         rice_parameter = rice_parameter_limit - 1;
3320                                                                 }
3321                                                                 if(encoder->protected_->do_qlp_coeff_prec_search) {
3322                                                                         min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
3323                                                                         /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
3324                                                                         if(subframe_bps <= 17) {
3325                                                                                 max_qlp_coeff_precision = flac_min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
3326                                                                                 max_qlp_coeff_precision = flac_max(max_qlp_coeff_precision, min_qlp_coeff_precision);
3327                                                                         }
3328                                                                         else
3329                                                                                 max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
3330                                                                 }
3331                                                                 else {
3332                                                                         min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
3333                                                                 }
3334                                                                 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
3335                                                                         _candidate_bits =
3336                                                                                 evaluate_lpc_subframe_(
3337                                                                                         encoder,
3338                                                                                         integer_signal,
3339                                                                                         residual[!_best_subframe],
3340                                                                                         encoder->private_->abs_residual_partition_sums,
3341                                                                                         encoder->private_->raw_bits_per_partition,
3342                                                                                         encoder->private_->lp_coeff[lpc_order-1],
3343                                                                                         frame_header->blocksize,
3344                                                                                         subframe_bps,
3345                                                                                         lpc_order,
3346                                                                                         qlp_coeff_precision,
3347                                                                                         rice_parameter,
3348                                                                                         rice_parameter_limit,
3349                                                                                         min_partition_order,
3350                                                                                         max_partition_order,
3351                                                                                         encoder->protected_->do_escape_coding,
3352                                                                                         encoder->protected_->rice_parameter_search_dist,
3353                                                                                         subframe[!_best_subframe],
3354                                                                                         partitioned_rice_contents[!_best_subframe]
3355                                                                                 );
3356                                                                         if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
3357                                                                                 if(_candidate_bits < _best_bits) {
3358                                                                                         _best_subframe = !_best_subframe;
3359                                                                                         _best_bits = _candidate_bits;
3360                                                                                 }
3361                                                                         }
3362                                                                 }
3363                                                         }
3364                                                 }
3365                                         }
3366                                 }
3367                         }
3368 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3369                 }
3370         }
3371
3372         /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3373         if(_best_bits == UINT_MAX) {
3374                 FLAC__ASSERT(_best_subframe == 0);
3375                 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3376         }
3377
3378         *best_subframe = _best_subframe;
3379         *best_bits = _best_bits;
3380
3381         return true;
3382 }
3383
3384 FLAC__bool add_subframe_(
3385         FLAC__StreamEncoder *encoder,
3386         unsigned blocksize,
3387         unsigned subframe_bps,
3388         const FLAC__Subframe *subframe,
3389         FLAC__BitWriter *frame
3390 )
3391 {
3392         switch(subframe->type) {
3393                 case FLAC__SUBFRAME_TYPE_CONSTANT:
3394                         if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3395                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3396                                 return false;
3397                         }
3398                         break;
3399                 case FLAC__SUBFRAME_TYPE_FIXED:
3400                         if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3401                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3402                                 return false;
3403                         }
3404                         break;
3405                 case FLAC__SUBFRAME_TYPE_LPC:
3406                         if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3407                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3408                                 return false;
3409                         }
3410                         break;
3411                 case FLAC__SUBFRAME_TYPE_VERBATIM:
3412                         if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3413                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3414                                 return false;
3415                         }
3416                         break;
3417                 default:
3418                         FLAC__ASSERT(0);
3419         }
3420
3421         return true;
3422 }
3423
3424 #define SPOTCHECK_ESTIMATE 0
3425 #if SPOTCHECK_ESTIMATE
3426 static void spotcheck_subframe_estimate_(
3427         FLAC__StreamEncoder *encoder,
3428         unsigned blocksize,
3429         unsigned subframe_bps,
3430         const FLAC__Subframe *subframe,
3431         unsigned estimate
3432 )
3433 {
3434         FLAC__bool ret;
3435         FLAC__BitWriter *frame = FLAC__bitwriter_new();
3436         if(frame == 0) {
3437                 fprintf(stderr, "EST: can't allocate frame\n");
3438                 return;
3439         }
3440         if(!FLAC__bitwriter_init(frame)) {
3441                 fprintf(stderr, "EST: can't init frame\n");
3442                 return;
3443         }
3444         ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
3445         FLAC__ASSERT(ret);
3446         {
3447                 const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
3448                 if(estimate != actual)
3449                         fprintf(stderr, "EST: bad, frame#%u sub#%%d type=%8s est=%u, actual=%u, delta=%d\n", encoder->private_->current_frame_number, FLAC__SubframeTypeString[subframe->type], estimate, actual, (int)actual-(int)estimate);
3450         }
3451         FLAC__bitwriter_delete(frame);
3452 }
3453 #endif
3454
3455 unsigned evaluate_constant_subframe_(
3456         FLAC__StreamEncoder *encoder,
3457         const FLAC__int32 signal,
3458         unsigned blocksize,
3459         unsigned subframe_bps,
3460         FLAC__Subframe *subframe
3461 )
3462 {
3463         unsigned estimate;
3464         subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3465         subframe->data.constant.value = signal;
3466
3467         estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
3468
3469 #if SPOTCHECK_ESTIMATE
3470         spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3471 #else
3472         (void)encoder, (void)blocksize;
3473 #endif
3474
3475         return estimate;
3476 }
3477
3478 unsigned evaluate_fixed_subframe_(
3479         FLAC__StreamEncoder *encoder,
3480         const FLAC__int32 signal[],
3481         FLAC__int32 residual[],
3482         FLAC__uint64 abs_residual_partition_sums[],
3483         unsigned raw_bits_per_partition[],
3484         unsigned blocksize,
3485         unsigned subframe_bps,
3486         unsigned order,
3487         unsigned rice_parameter,
3488         unsigned rice_parameter_limit,
3489         unsigned min_partition_order,
3490         unsigned max_partition_order,
3491         FLAC__bool do_escape_coding,
3492         unsigned rice_parameter_search_dist,
3493         FLAC__Subframe *subframe,
3494         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3495 )
3496 {
3497         unsigned i, residual_bits, estimate;
3498         const unsigned residual_samples = blocksize - order;
3499
3500         FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3501
3502         subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3503
3504         subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3505         subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3506         subframe->data.fixed.residual = residual;
3507
3508         residual_bits =
3509                 find_best_partition_order_(
3510                         encoder->private_,
3511                         residual,
3512                         abs_residual_partition_sums,
3513                         raw_bits_per_partition,
3514                         residual_samples,
3515                         order,
3516                         rice_parameter,
3517                         rice_parameter_limit,
3518                         min_partition_order,
3519                         max_partition_order,
3520                         subframe_bps,
3521                         do_escape_coding,
3522                         rice_parameter_search_dist,
3523                         &subframe->data.fixed.entropy_coding_method
3524                 );
3525
3526         subframe->data.fixed.order = order;
3527         for(i = 0; i < order; i++)
3528                 subframe->data.fixed.warmup[i] = signal[i];
3529
3530         estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
3531
3532 #if SPOTCHECK_ESTIMATE
3533         spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3534 #endif
3535
3536         return estimate;
3537 }
3538
3539 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3540 unsigned evaluate_lpc_subframe_(
3541         FLAC__StreamEncoder *encoder,
3542         const FLAC__int32 signal[],
3543         FLAC__int32 residual[],
3544         FLAC__uint64 abs_residual_partition_sums[],
3545         unsigned raw_bits_per_partition[],
3546         const FLAC__real lp_coeff[],
3547         unsigned blocksize,
3548         unsigned subframe_bps,
3549         unsigned order,
3550         unsigned qlp_coeff_precision,
3551         unsigned rice_parameter,
3552         unsigned rice_parameter_limit,
3553         unsigned min_partition_order,
3554         unsigned max_partition_order,
3555         FLAC__bool do_escape_coding,
3556         unsigned rice_parameter_search_dist,
3557         FLAC__Subframe *subframe,
3558         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3559 )
3560 {
3561         FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
3562         unsigned i, residual_bits, estimate;
3563         int quantization, ret;
3564         const unsigned residual_samples = blocksize - order;
3565
3566         /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3567         if(subframe_bps <= 16) {
3568                 FLAC__ASSERT(order > 0);
3569                 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3570                 qlp_coeff_precision = flac_min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3571         }
3572
3573         ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3574         if(ret != 0)
3575                 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3576
3577         if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3578                 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3579                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3580                 else
3581                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3582         else
3583                 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3584
3585         subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3586
3587         subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3588         subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3589         subframe->data.lpc.residual = residual;
3590
3591         residual_bits =
3592                 find_best_partition_order_(
3593                         encoder->private_,
3594                         residual,
3595                         abs_residual_partition_sums,
3596                         raw_bits_per_partition,
3597                         residual_samples,
3598                         order,
3599                         rice_parameter,
3600                         rice_parameter_limit,
3601                         min_partition_order,
3602                         max_partition_order,
3603                         subframe_bps,
3604                         do_escape_coding,
3605                         rice_parameter_search_dist,
3606                         &subframe->data.lpc.entropy_coding_method
3607                 );
3608
3609         subframe->data.lpc.order = order;
3610         subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3611         subframe->data.lpc.quantization_level = quantization;
3612         memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3613         for(i = 0; i < order; i++)
3614                 subframe->data.lpc.warmup[i] = signal[i];
3615
3616         estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits;
3617
3618 #if SPOTCHECK_ESTIMATE
3619         spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3620 #endif
3621
3622         return estimate;
3623 }
3624 #endif
3625
3626 unsigned evaluate_verbatim_subframe_(
3627         FLAC__StreamEncoder *encoder,
3628         const FLAC__int32 signal[],
3629         unsigned blocksize,
3630         unsigned subframe_bps,
3631         FLAC__Subframe *subframe
3632 )
3633 {
3634         unsigned estimate;
3635
3636         subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3637
3638         subframe->data.verbatim.data = signal;
3639
3640         estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
3641
3642 #if SPOTCHECK_ESTIMATE
3643         spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3644 #else
3645         (void)encoder;
3646 #endif
3647
3648         return estimate;
3649 }
3650
3651 unsigned find_best_partition_order_(
3652         FLAC__StreamEncoderPrivate *private_,
3653         const FLAC__int32 residual[],
3654         FLAC__uint64 abs_residual_partition_sums[],
3655         unsigned raw_bits_per_partition[],
3656         unsigned residual_samples,
3657         unsigned predictor_order,
3658         unsigned rice_parameter,
3659         unsigned rice_parameter_limit,
3660         unsigned min_partition_order,
3661         unsigned max_partition_order,
3662         unsigned bps,
3663         FLAC__bool do_escape_coding,
3664         unsigned rice_parameter_search_dist,
3665         FLAC__EntropyCodingMethod *best_ecm
3666 )
3667 {
3668         unsigned residual_bits, best_residual_bits = 0;
3669         unsigned best_parameters_index = 0;
3670         unsigned best_partition_order = 0;
3671         const unsigned blocksize = residual_samples + predictor_order;
3672
3673         max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3674         min_partition_order = flac_min(min_partition_order, max_partition_order);
3675
3676         precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
3677
3678         if(do_escape_coding)
3679                 precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3680
3681         {
3682                 int partition_order;
3683                 unsigned sum;
3684
3685                 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3686                         if(!
3687                                 set_partitioned_rice_(
3688 #ifdef EXACT_RICE_BITS_CALCULATION
3689                                         residual,
3690 #endif
3691                                         abs_residual_partition_sums+sum,
3692                                         raw_bits_per_partition+sum,
3693                                         residual_samples,
3694                                         predictor_order,
3695                                         rice_parameter,
3696                                         rice_parameter_limit,
3697                                         rice_parameter_search_dist,
3698                                         (unsigned)partition_order,
3699                                         do_escape_coding,
3700                                         &private_->partitioned_rice_contents_extra[!best_parameters_index],
3701                                         &residual_bits
3702                                 )
3703                         )
3704                         {
3705                                 FLAC__ASSERT(best_residual_bits != 0);
3706                                 break;
3707                         }
3708                         sum += 1u << partition_order;
3709                         if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3710                                 best_residual_bits = residual_bits;
3711                                 best_parameters_index = !best_parameters_index;
3712                                 best_partition_order = partition_order;
3713                         }
3714                 }
3715         }
3716
3717         best_ecm->data.partitioned_rice.order = best_partition_order;
3718
3719         {
3720                 /*
3721                  * We are allowed to de-const the pointer based on our special
3722                  * knowledge; it is const to the outside world.
3723                  */
3724                 FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
3725                 unsigned partition;
3726
3727                 /* save best parameters and raw_bits */
3728                 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, flac_max(6u, best_partition_order));
3729                 memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
3730                 if(do_escape_coding)
3731                         memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
3732                 /*
3733                  * Now need to check if the type should be changed to
3734                  * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
3735                  * size of the rice parameters.
3736                  */
3737                 for(partition = 0; partition < (1u<<best_partition_order); partition++) {
3738                         if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3739                                 best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
3740                                 break;
3741                         }
3742                 }
3743         }
3744
3745         return best_residual_bits;
3746 }
3747
3748 #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
3749 extern void precompute_partition_info_sums_32bit_asm_ia32_(
3750         const FLAC__int32 residual[],
3751         FLAC__uint64 abs_residual_partition_sums[],
3752         unsigned blocksize,
3753         unsigned predictor_order,
3754         unsigned min_partition_order,
3755         unsigned max_partition_order
3756 );
3757 #endif
3758
3759 void precompute_partition_info_sums_(
3760         const FLAC__int32 residual[],
3761         FLAC__uint64 abs_residual_partition_sums[],
3762         unsigned residual_samples,
3763         unsigned predictor_order,
3764         unsigned min_partition_order,
3765         unsigned max_partition_order,
3766         unsigned bps
3767 )
3768 {
3769         const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
3770         unsigned partitions = 1u << max_partition_order;
3771
3772         FLAC__ASSERT(default_partition_samples > predictor_order);
3773
3774 #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
3775         /* slightly pessimistic but still catches all common cases */
3776         /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
3777         if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
3778                 precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
3779                 return;
3780         }
3781 #endif
3782
3783         /* first do max_partition_order */
3784         {
3785                 unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
3786                 /* slightly pessimistic but still catches all common cases */
3787                 /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
3788                 if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
3789                         FLAC__uint32 abs_residual_partition_sum;
3790
3791                         for(partition = residual_sample = 0; partition < partitions; partition++) {
3792                                 end += default_partition_samples;
3793                                 abs_residual_partition_sum = 0;
3794                                 for( ; residual_sample < end; residual_sample++)
3795                                         abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3796                                 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3797                         }
3798                 }
3799                 else { /* have to pessimistically use 64 bits for accumulator */
3800                         FLAC__uint64 abs_residual_partition_sum;
3801
3802                         for(partition = residual_sample = 0; partition < partitions; partition++) {
3803                                 end += default_partition_samples;
3804                                 abs_residual_partition_sum = 0;
3805                                 for( ; residual_sample < end; residual_sample++)
3806                                         abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3807                                 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3808                         }
3809                 }
3810         }
3811
3812         /* now merge partitions for lower orders */
3813         {
3814                 unsigned from_partition = 0, to_partition = partitions;
3815                 int partition_order;
3816                 for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
3817                         unsigned i;
3818                         partitions >>= 1;
3819                         for(i = 0; i < partitions; i++) {
3820                                 abs_residual_partition_sums[to_partition++] =
3821                                         abs_residual_partition_sums[from_partition  ] +
3822                                         abs_residual_partition_sums[from_partition+1];
3823                                 from_partition += 2;
3824                         }
3825                 }
3826         }
3827 }
3828
3829 void precompute_partition_info_escapes_(
3830         const FLAC__int32 residual[],
3831         unsigned raw_bits_per_partition[],
3832         unsigned residual_samples,
3833         unsigned predictor_order,
3834         unsigned min_partition_order,
3835         unsigned max_partition_order
3836 )
3837 {
3838         int partition_order;
3839         unsigned from_partition, to_partition = 0;
3840         const unsigned blocksize = residual_samples + predictor_order;
3841
3842         /* first do max_partition_order */
3843         for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3844                 FLAC__int32 r;
3845                 FLAC__uint32 rmax;
3846                 unsigned partition, partition_sample, partition_samples, residual_sample;
3847                 const unsigned partitions = 1u << partition_order;
3848                 const unsigned default_partition_samples = blocksize >> partition_order;
3849
3850                 FLAC__ASSERT(default_partition_samples > predictor_order);
3851
3852                 for(partition = residual_sample = 0; partition < partitions; partition++) {
3853                         partition_samples = default_partition_samples;
3854                         if(partition == 0)
3855                                 partition_samples -= predictor_order;
3856                         rmax = 0;
3857                         for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
3858                                 r = residual[residual_sample++];
3859                                 /* OPT: maybe faster: rmax |= r ^ (r>>31) */
3860                                 if(r < 0)
3861                                         rmax |= ~r;
3862                                 else
3863                                         rmax |= r;
3864                         }
3865                         /* now we know all residual values are in the range [-rmax-1,rmax] */
3866                         raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
3867                 }
3868                 to_partition = partitions;
3869                 break; /*@@@ yuck, should remove the 'for' loop instead */
3870         }
3871
3872         /* now merge partitions for lower orders */
3873         for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
3874                 unsigned m;
3875                 unsigned i;
3876                 const unsigned partitions = 1u << partition_order;
3877                 for(i = 0; i < partitions; i++) {
3878                         m = raw_bits_per_partition[from_partition];
3879                         from_partition++;
3880                         raw_bits_per_partition[to_partition] = flac_max(m, raw_bits_per_partition[from_partition]);
3881                         from_partition++;
3882                         to_partition++;
3883                 }
3884         }
3885 }
3886
3887 #ifdef EXACT_RICE_BITS_CALCULATION
3888 static inline unsigned count_rice_bits_in_partition_(
3889         const unsigned rice_parameter,
3890         const unsigned partition_samples,
3891         const FLAC__int32 *residual
3892 )
3893 {
3894         unsigned i, partition_bits =
3895                 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
3896                 (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
3897         ;
3898         for(i = 0; i < partition_samples; i++)
3899                 partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
3900         return partition_bits;
3901 }
3902 #else
3903 static inline unsigned count_rice_bits_in_partition_(
3904         const unsigned rice_parameter,
3905         const unsigned partition_samples,
3906         const FLAC__uint64 abs_residual_partition_sum
3907 )
3908 {
3909         return
3910                 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
3911                 (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
3912                 (
3913                         rice_parameter?
3914                                 (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
3915                                 : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
3916                 )
3917                 - (partition_samples >> 1)
3918                 /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
3919                  * The actual number of bits used is closer to the sum(for all i in the partition) of  abs(residual[i])>>(rice_parameter-1)
3920                  * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
3921                  * So the subtraction term tries to guess how many extra bits were contributed.
3922                  * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
3923                  */
3924         ;
3925 }
3926 #endif
3927
3928 FLAC__bool set_partitioned_rice_(
3929 #ifdef EXACT_RICE_BITS_CALCULATION
3930         const FLAC__int32 residual[],
3931 #endif
3932         const FLAC__uint64 abs_residual_partition_sums[],
3933         const unsigned raw_bits_per_partition[],
3934         const unsigned residual_samples,
3935         const unsigned predictor_order,
3936         const unsigned suggested_rice_parameter,
3937         const unsigned rice_parameter_limit,
3938         const unsigned rice_parameter_search_dist,
3939         const unsigned partition_order,
3940         const FLAC__bool search_for_escapes,
3941         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3942         unsigned *bits
3943 )
3944 {
3945         unsigned rice_parameter, partition_bits;
3946         unsigned best_partition_bits, best_rice_parameter = 0;
3947         unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
3948         unsigned *parameters, *raw_bits;
3949 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3950         unsigned min_rice_parameter, max_rice_parameter;
3951 #else
3952         (void)rice_parameter_search_dist;
3953 #endif
3954
3955         FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
3956         FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
3957
3958         FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, flac_max(6u, partition_order));
3959         parameters = partitioned_rice_contents->parameters;
3960         raw_bits = partitioned_rice_contents->raw_bits;
3961
3962         if(partition_order == 0) {
3963                 best_partition_bits = (unsigned)(-1);
3964 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3965                 if(rice_parameter_search_dist) {
3966                         if(suggested_rice_parameter < rice_parameter_search_dist)
3967                                 min_rice_parameter = 0;
3968                         else
3969                                 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
3970                         max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
3971                         if(max_rice_parameter >= rice_parameter_limit) {
3972 #ifdef DEBUG_VERBOSE
3973                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
3974 #endif
3975                                 max_rice_parameter = rice_parameter_limit - 1;
3976                         }
3977                 }
3978                 else
3979                         min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
3980
3981                 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3982 #else
3983                         rice_parameter = suggested_rice_parameter;
3984 #endif
3985 #ifdef EXACT_RICE_BITS_CALCULATION
3986                         partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
3987 #else
3988                         partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
3989 #endif
3990                         if(partition_bits < best_partition_bits) {
3991                                 best_rice_parameter = rice_parameter;
3992                                 best_partition_bits = partition_bits;
3993                         }
3994 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3995                 }
3996 #endif
3997                 if(search_for_escapes) {
3998                         partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[0] * residual_samples;
3999                         if(partition_bits <= best_partition_bits) {
4000                                 raw_bits[0] = raw_bits_per_partition[0];
4001                                 best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4002                                 best_partition_bits = partition_bits;
4003                         }
4004                         else
4005                                 raw_bits[0] = 0;
4006                 }
4007                 parameters[0] = best_rice_parameter;
4008                 bits_ += best_partition_bits;
4009         }
4010         else {
4011                 unsigned partition, residual_sample;
4012                 unsigned partition_samples;
4013                 FLAC__uint64 mean, k;
4014                 const unsigned partitions = 1u << partition_order;
4015                 for(partition = residual_sample = 0; partition < partitions; partition++) {
4016                         partition_samples = (residual_samples+predictor_order) >> partition_order;
4017                         if(partition == 0) {
4018                                 if(partition_samples <= predictor_order)
4019                                         return false;
4020                                 else
4021                                         partition_samples -= predictor_order;
4022                         }
4023                         mean = abs_residual_partition_sums[partition];
4024                         /* we are basically calculating the size in bits of the
4025                          * average residual magnitude in the partition:
4026                          *   rice_parameter = floor(log2(mean/partition_samples))
4027                          * 'mean' is not a good name for the variable, it is
4028                          * actually the sum of magnitudes of all residual values
4029                          * in the partition, so the actual mean is
4030                          * mean/partition_samples
4031                          */
4032                         for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
4033                                 ;
4034                         if(rice_parameter >= rice_parameter_limit) {
4035 #ifdef DEBUG_VERBOSE
4036                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
4037 #endif
4038                                 rice_parameter = rice_parameter_limit - 1;
4039                         }
4040
4041                         best_partition_bits = (unsigned)(-1);
4042 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4043                         if(rice_parameter_search_dist) {
4044                                 if(rice_parameter < rice_parameter_search_dist)
4045                                         min_rice_parameter = 0;
4046                                 else
4047                                         min_rice_parameter = rice_parameter - rice_parameter_search_dist;
4048                                 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
4049                                 if(max_rice_parameter >= rice_parameter_limit) {
4050 #ifdef DEBUG_VERBOSE
4051                                         fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
4052 #endif
4053                                         max_rice_parameter = rice_parameter_limit - 1;
4054                                 }
4055                         }
4056                         else
4057                                 min_rice_parameter = max_rice_parameter = rice_parameter;
4058
4059                         for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4060 #endif
4061 #ifdef EXACT_RICE_BITS_CALCULATION
4062                                 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
4063 #else
4064                                 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
4065 #endif
4066                                 if(partition_bits < best_partition_bits) {
4067                                         best_rice_parameter = rice_parameter;
4068                                         best_partition_bits = partition_bits;
4069                                 }
4070 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4071                         }
4072 #endif
4073                         if(search_for_escapes) {
4074                                 partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[partition] * partition_samples;
4075                                 if(partition_bits <= best_partition_bits) {
4076                                         raw_bits[partition] = raw_bits_per_partition[partition];
4077                                         best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4078                                         best_partition_bits = partition_bits;
4079                                 }
4080                                 else
4081                                         raw_bits[partition] = 0;
4082                         }
4083                         parameters[partition] = best_rice_parameter;
4084                         bits_ += best_partition_bits;
4085                         residual_sample += partition_samples;
4086                 }
4087         }
4088
4089         *bits = bits_;
4090         return true;
4091 }
4092
4093 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
4094 {
4095         unsigned i, shift;
4096         FLAC__int32 x = 0;
4097
4098         for(i = 0; i < samples && !(x&1); i++)
4099                 x |= signal[i];
4100
4101         if(x == 0) {
4102                 shift = 0;
4103         }
4104         else {
4105                 for(shift = 0; !(x&1); shift++)
4106                         x >>= 1;
4107         }
4108
4109         if(shift > 0) {
4110                 for(i = 0; i < samples; i++)
4111                          signal[i] >>= shift;
4112         }
4113
4114         return shift;
4115 }
4116
4117 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4118 {
4119         unsigned channel;
4120
4121         for(channel = 0; channel < channels; channel++)
4122                 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
4123
4124         fifo->tail += wide_samples;
4125
4126         FLAC__ASSERT(fifo->tail <= fifo->size);
4127 }
4128
4129 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4130 {
4131         unsigned channel;
4132         unsigned sample, wide_sample;
4133         unsigned tail = fifo->tail;
4134
4135         sample = input_offset * channels;
4136         for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
4137                 for(channel = 0; channel < channels; channel++)
4138                         fifo->data[channel][tail] = input[sample++];
4139                 tail++;
4140         }
4141         fifo->tail = tail;
4142
4143         FLAC__ASSERT(fifo->tail <= fifo->size);
4144 }
4145
4146 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4147 {
4148         FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4149         const size_t encoded_bytes = encoder->private_->verify.output.bytes;
4150         (void)decoder;
4151
4152         if(encoder->private_->verify.needs_magic_hack) {
4153                 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
4154                 *bytes = FLAC__STREAM_SYNC_LENGTH;
4155                 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
4156                 encoder->private_->verify.needs_magic_hack = false;
4157         }
4158         else {
4159                 if(encoded_bytes == 0) {
4160                         /*
4161                          * If we get here, a FIFO underflow has occurred,
4162                          * which means there is a bug somewhere.
4163                          */
4164                         FLAC__ASSERT(0);
4165                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
4166                 }
4167                 else if(encoded_bytes < *bytes)
4168                         *bytes = encoded_bytes;
4169                 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
4170                 encoder->private_->verify.output.data += *bytes;
4171                 encoder->private_->verify.output.bytes -= *bytes;
4172         }
4173
4174         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
4175 }
4176
4177 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
4178 {
4179         FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
4180         unsigned channel;
4181         const unsigned channels = frame->header.channels;
4182         const unsigned blocksize = frame->header.blocksize;
4183         const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
4184
4185         (void)decoder;
4186
4187         for(channel = 0; channel < channels; channel++) {
4188                 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
4189                         unsigned i, sample = 0;
4190                         FLAC__int32 expect = 0, got = 0;
4191
4192                         for(i = 0; i < blocksize; i++) {
4193                                 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
4194                                         sample = i;
4195                                         expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
4196                                         got = (FLAC__int32)buffer[channel][i];
4197                                         break;
4198                                 }
4199                         }
4200                         FLAC__ASSERT(i < blocksize);
4201                         FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
4202                         encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
4203                         encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
4204                         encoder->private_->verify.error_stats.channel = channel;
4205                         encoder->private_->verify.error_stats.sample = sample;
4206                         encoder->private_->verify.error_stats.expected = expect;
4207                         encoder->private_->verify.error_stats.got = got;
4208                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
4209                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
4210                 }
4211         }
4212         /* dequeue the frame from the fifo */
4213         encoder->private_->verify.input_fifo.tail -= blocksize;
4214         FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
4215         for(channel = 0; channel < channels; channel++)
4216                 memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail * sizeof(encoder->private_->verify.input_fifo.data[0][0]));
4217         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4218 }
4219
4220 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4221 {
4222         (void)decoder, (void)metadata, (void)client_data;
4223 }
4224
4225 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4226 {
4227         FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4228         (void)decoder, (void)status;
4229         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4230 }
4231
4232 FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4233 {
4234         (void)client_data;
4235
4236         *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
4237         if (*bytes == 0) {
4238                 if (feof(encoder->private_->file))
4239                         return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
4240                 else if (ferror(encoder->private_->file))
4241                         return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
4242         }
4243         return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
4244 }
4245
4246 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4247 {
4248         (void)client_data;
4249
4250         if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
4251                 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4252         else
4253                 return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4254 }
4255
4256 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4257 {
4258         off_t offset;
4259
4260         (void)client_data;
4261
4262         offset = ftello(encoder->private_->file);
4263
4264         if(offset < 0) {
4265                 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4266         }
4267         else {
4268                 *absolute_byte_offset = (FLAC__uint64)offset;
4269                 return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4270         }
4271 }
4272
4273 #ifdef FLAC__VALGRIND_TESTING
4274 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4275 {
4276         size_t ret = fwrite(ptr, size, nmemb, stream);
4277         if(!ferror(stream))
4278                 fflush(stream);
4279         return ret;
4280 }
4281 #else
4282 #define local__fwrite fwrite
4283 #endif
4284
4285 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
4286 {
4287         (void)client_data, (void)current_frame;
4288
4289         if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4290                 FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
4291 #if FLAC__HAS_OGG
4292                         /* We would like to be able to use 'samples > 0' in the
4293                          * clause here but currently because of the nature of our
4294                          * Ogg writing implementation, 'samples' is always 0 (see
4295                          * ogg_encoder_aspect.c).  The downside is extra progress
4296                          * callbacks.
4297                          */
4298                         encoder->private_->is_ogg? true :
4299 #endif
4300                         samples > 0
4301                 );
4302                 if(call_it) {
4303                         /* NOTE: We have to add +bytes, +samples, and +1 to the stats
4304                          * because at this point in the callback chain, the stats
4305                          * have not been updated.  Only after we return and control
4306                          * gets back to write_frame_() are the stats updated
4307                          */
4308                         encoder->private_->progress_callback(encoder, encoder->private_->bytes_written+bytes, encoder->private_->samples_written+samples, encoder->private_->frames_written+(samples?1:0), encoder->private_->total_frames_estimate, encoder->private_->client_data);
4309                 }
4310                 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4311         }
4312         else
4313                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4314 }
4315
4316 /*
4317  * This will forcibly set stdout to binary mode (for OSes that require it)
4318  */
4319 FILE *get_binary_stdout_(void)
4320 {
4321         /* if something breaks here it is probably due to the presence or
4322          * absence of an underscore before the identifiers 'setmode',
4323          * 'fileno', and/or 'O_BINARY'; check your system header files.
4324          */
4325 #if defined _MSC_VER || defined __MINGW32__
4326         _setmode(_fileno(stdout), _O_BINARY);
4327 #elif defined __CYGWIN__
4328         /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4329         setmode(_fileno(stdout), _O_BINARY);
4330 #elif defined __EMX__
4331         setmode(fileno(stdout), O_BINARY);
4332 #endif
4333
4334         return stdout;
4335 }