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