remove more redundant logic in process calls
[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         FLAC__MD5Init(&encoder->private_->md5context);
1062         if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1063                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1064                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1065         }
1066         if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1067                 /* the above function sets the state for us in case of an error */
1068                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1069         }
1070
1071         /*
1072          * Now that the STREAMINFO block is written, we can init this to an
1073          * absurdly-high value...
1074          */
1075         encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1076         /* ... and clear this to 0 */
1077         encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1078
1079         /*
1080          * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1081          * if not, we will write an empty one (FLAC__add_metadata_block()
1082          * automatically supplies the vendor string).
1083          *
1084          * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1085          * the STREAMINFO.  (In the case that metadata_has_vorbis_comment is
1086          * true it will have already insured that the metadata list is properly
1087          * ordered.)
1088          */
1089         if(!metadata_has_vorbis_comment) {
1090                 FLAC__StreamMetadata vorbis_comment;
1091                 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1092                 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1093                 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1094                 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1095                 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1096                 vorbis_comment.data.vorbis_comment.num_comments = 0;
1097                 vorbis_comment.data.vorbis_comment.comments = 0;
1098                 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1099                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1100                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1101                 }
1102                 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1103                         /* the above function sets the state for us in case of an error */
1104                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1105                 }
1106         }
1107
1108         /*
1109          * write the user's metadata blocks
1110          */
1111         for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1112                 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1113                 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1114                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1115                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1116                 }
1117                 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1118                         /* the above function sets the state for us in case of an error */
1119                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1120                 }
1121         }
1122
1123         /* now that all the metadata is written, we save the stream offset */
1124         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 */
1125                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1126                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1127         }
1128
1129         if(encoder->protected_->verify)
1130                 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1131
1132         return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1133 }
1134
1135 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1136         FLAC__StreamEncoder *encoder,
1137         FLAC__StreamEncoderWriteCallback write_callback,
1138         FLAC__StreamEncoderSeekCallback seek_callback,
1139         FLAC__StreamEncoderTellCallback tell_callback,
1140         FLAC__StreamEncoderMetadataCallback metadata_callback,
1141         void *client_data
1142 )
1143 {
1144         return init_stream_internal_(
1145                 encoder,
1146                 /*read_callback=*/0,
1147                 write_callback,
1148                 seek_callback,
1149                 tell_callback,
1150                 metadata_callback,
1151                 client_data,
1152                 /*is_ogg=*/false
1153         );
1154 }
1155
1156 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1157         FLAC__StreamEncoder *encoder,
1158         FLAC__StreamEncoderReadCallback read_callback,
1159         FLAC__StreamEncoderWriteCallback write_callback,
1160         FLAC__StreamEncoderSeekCallback seek_callback,
1161         FLAC__StreamEncoderTellCallback tell_callback,
1162         FLAC__StreamEncoderMetadataCallback metadata_callback,
1163         void *client_data
1164 )
1165 {
1166         return init_stream_internal_(
1167                 encoder,
1168                 read_callback,
1169                 write_callback,
1170                 seek_callback,
1171                 tell_callback,
1172                 metadata_callback,
1173                 client_data,
1174                 /*is_ogg=*/true
1175         );
1176 }
1177  
1178 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1179         FLAC__StreamEncoder *encoder,
1180         FILE *file,
1181         FLAC__StreamEncoderProgressCallback progress_callback,
1182         void *client_data,
1183         FLAC__bool is_ogg
1184 )
1185 {
1186         FLAC__StreamEncoderInitStatus init_status;
1187
1188         FLAC__ASSERT(0 != encoder);
1189         FLAC__ASSERT(0 != file);
1190
1191         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1192                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1193
1194         /* double protection */
1195         if(file == 0) {
1196                 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1197                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1198         }
1199
1200         /*
1201          * To make sure that our file does not go unclosed after an error, we
1202          * must assign the FILE pointer before any further error can occur in
1203          * this routine.
1204          */
1205         if(file == stdout)
1206                 file = get_binary_stdout_(); /* just to be safe */
1207
1208         encoder->private_->file = file;
1209
1210         encoder->private_->progress_callback = progress_callback;
1211         encoder->private_->bytes_written = 0;
1212         encoder->private_->samples_written = 0;
1213         encoder->private_->frames_written = 0;
1214
1215         init_status = init_stream_internal_(
1216                 encoder,
1217                 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1218                 file_write_callback_,
1219                 encoder->private_->file == stdout? 0 : file_seek_callback_,
1220                 encoder->private_->file == stdout? 0 : file_tell_callback_,
1221                 /*metadata_callback=*/0,
1222                 client_data,
1223                 is_ogg
1224         );
1225         if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1226                 /* the above function sets the state for us in case of an error */
1227                 return init_status;
1228         }
1229
1230         {
1231                 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1232
1233                 FLAC__ASSERT(blocksize != 0);
1234                 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1235         }
1236
1237         return init_status;
1238 }
1239  
1240 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1241         FLAC__StreamEncoder *encoder,
1242         FILE *file,
1243         FLAC__StreamEncoderProgressCallback progress_callback,
1244         void *client_data
1245 )
1246 {
1247         return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1248 }
1249  
1250 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1251         FLAC__StreamEncoder *encoder,
1252         FILE *file,
1253         FLAC__StreamEncoderProgressCallback progress_callback,
1254         void *client_data
1255 )
1256 {
1257         return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1258 }
1259
1260 static FLAC__StreamEncoderInitStatus init_file_internal_(
1261         FLAC__StreamEncoder *encoder,
1262         const char *filename,
1263         FLAC__StreamEncoderProgressCallback progress_callback,
1264         void *client_data,
1265         FLAC__bool is_ogg
1266 )
1267 {
1268         FILE *file;
1269
1270         FLAC__ASSERT(0 != encoder);
1271
1272         /*
1273          * To make sure that our file does not go unclosed after an error, we
1274          * have to do the same entrance checks here that are later performed
1275          * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1276          */
1277         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1278                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1279
1280         file = filename? fopen(filename, "w+b") : stdout;
1281
1282         if(file == 0) {
1283                 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1284                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1285         }
1286
1287         return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1288 }
1289
1290 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1291         FLAC__StreamEncoder *encoder,
1292         const char *filename,
1293         FLAC__StreamEncoderProgressCallback progress_callback,
1294         void *client_data
1295 )
1296 {
1297         return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1298 }
1299
1300 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1301         FLAC__StreamEncoder *encoder,
1302         const char *filename,
1303         FLAC__StreamEncoderProgressCallback progress_callback,
1304         void *client_data
1305 )
1306 {
1307         return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1308 }
1309
1310 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1311 {
1312         FLAC__bool error = false;
1313
1314         FLAC__ASSERT(0 != encoder);
1315         FLAC__ASSERT(0 != encoder->private_);
1316         FLAC__ASSERT(0 != encoder->protected_);
1317
1318         if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1319                 return true;
1320
1321         if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1322                 if(encoder->private_->current_sample_number != 0) {
1323                         const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1324                         encoder->protected_->blocksize = encoder->private_->current_sample_number;
1325                         if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1326                                 error = true;
1327                 }
1328         }
1329
1330         FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1331
1332         if(!encoder->private_->is_being_deleted) {
1333                 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1334                         if(encoder->private_->seek_callback) {
1335 #if FLAC__HAS_OGG
1336                                 if(encoder->private_->is_ogg)
1337                                         update_ogg_metadata_(encoder);
1338                                 else
1339 #endif
1340                                 update_metadata_(encoder);
1341
1342                                 /* check if an error occurred while updating metadata */
1343                                 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1344                                         error = true;
1345                         }
1346                         if(encoder->private_->metadata_callback)
1347                                 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1348                 }
1349
1350                 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1351                         if(!error)
1352                                 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1353                         error = true;
1354                 }
1355         }
1356
1357         if(0 != encoder->private_->file) {
1358                 if(encoder->private_->file != stdout)
1359                         fclose(encoder->private_->file);
1360                 encoder->private_->file = 0;
1361         }
1362
1363 #if FLAC__HAS_OGG
1364         if(encoder->private_->is_ogg)
1365                 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1366 #endif
1367
1368         free_(encoder);
1369         set_defaults_(encoder);
1370
1371         if(!error)
1372                 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1373
1374         return !error;
1375 }
1376
1377 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1378 {
1379         FLAC__ASSERT(0 != encoder);
1380         FLAC__ASSERT(0 != encoder->private_);
1381         FLAC__ASSERT(0 != encoder->protected_);
1382         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1383                 return false;
1384 #if FLAC__HAS_OGG
1385         /* can't check encoder->private_->is_ogg since that's not set until init time */
1386         FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1387         return true;
1388 #else
1389         (void)value;
1390         return false;
1391 #endif
1392 }
1393
1394 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1395 {
1396         FLAC__ASSERT(0 != encoder);
1397         FLAC__ASSERT(0 != encoder->private_);
1398         FLAC__ASSERT(0 != encoder->protected_);
1399         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1400                 return false;
1401 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1402         encoder->protected_->verify = value;
1403 #endif
1404         return true;
1405 }
1406
1407 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1408 {
1409         FLAC__ASSERT(0 != encoder);
1410         FLAC__ASSERT(0 != encoder->private_);
1411         FLAC__ASSERT(0 != encoder->protected_);
1412         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1413                 return false;
1414         encoder->protected_->streamable_subset = value;
1415         return true;
1416 }
1417
1418 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1419 {
1420         FLAC__ASSERT(0 != encoder);
1421         FLAC__ASSERT(0 != encoder->private_);
1422         FLAC__ASSERT(0 != encoder->protected_);
1423         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1424                 return false;
1425         encoder->protected_->channels = value;
1426         return true;
1427 }
1428
1429 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1430 {
1431         FLAC__ASSERT(0 != encoder);
1432         FLAC__ASSERT(0 != encoder->private_);
1433         FLAC__ASSERT(0 != encoder->protected_);
1434         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1435                 return false;
1436         encoder->protected_->bits_per_sample = value;
1437         return true;
1438 }
1439
1440 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1441 {
1442         FLAC__ASSERT(0 != encoder);
1443         FLAC__ASSERT(0 != encoder->private_);
1444         FLAC__ASSERT(0 != encoder->protected_);
1445         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1446                 return false;
1447         encoder->protected_->sample_rate = value;
1448         return true;
1449 }
1450
1451 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1452 {
1453         FLAC__bool ok = true;
1454         FLAC__ASSERT(0 != encoder);
1455         FLAC__ASSERT(0 != encoder->private_);
1456         FLAC__ASSERT(0 != encoder->protected_);
1457         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1458                 return false;
1459         if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1460                 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1461         ok &= FLAC__stream_encoder_set_do_mid_side_stereo          (encoder, compression_levels_[value].do_mid_side_stereo);
1462         ok &= FLAC__stream_encoder_set_loose_mid_side_stereo       (encoder, compression_levels_[value].loose_mid_side_stereo);
1463 #if 0
1464         /* was: */
1465         ok &= FLAC__stream_encoder_set_apodization                 (encoder, compression_levels_[value].apodization);
1466         /* but it's too hard to specify the string in a locale-specific way */
1467 #else
1468         encoder->protected_->num_apodizations = 1;
1469         encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1470         encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1471 #endif
1472         ok &= FLAC__stream_encoder_set_max_lpc_order               (encoder, compression_levels_[value].max_lpc_order);
1473         ok &= FLAC__stream_encoder_set_qlp_coeff_precision         (encoder, compression_levels_[value].qlp_coeff_precision);
1474         ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search    (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1475         ok &= FLAC__stream_encoder_set_do_escape_coding            (encoder, compression_levels_[value].do_escape_coding);
1476         ok &= FLAC__stream_encoder_set_do_exhaustive_model_search  (encoder, compression_levels_[value].do_exhaustive_model_search);
1477         ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1478         ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1479         ok &= FLAC__stream_encoder_set_rice_parameter_search_dist  (encoder, compression_levels_[value].rice_parameter_search_dist);
1480         return ok;
1481 }
1482
1483 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1484 {
1485         FLAC__ASSERT(0 != encoder);
1486         FLAC__ASSERT(0 != encoder->private_);
1487         FLAC__ASSERT(0 != encoder->protected_);
1488         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1489                 return false;
1490         encoder->protected_->blocksize = value;
1491         return true;
1492 }
1493
1494 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1495 {
1496         FLAC__ASSERT(0 != encoder);
1497         FLAC__ASSERT(0 != encoder->private_);
1498         FLAC__ASSERT(0 != encoder->protected_);
1499         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1500                 return false;
1501         encoder->protected_->do_mid_side_stereo = value;
1502         return true;
1503 }
1504
1505 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1506 {
1507         FLAC__ASSERT(0 != encoder);
1508         FLAC__ASSERT(0 != encoder->private_);
1509         FLAC__ASSERT(0 != encoder->protected_);
1510         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1511                 return false;
1512         encoder->protected_->loose_mid_side_stereo = value;
1513         return true;
1514 }
1515
1516 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1517 {
1518         FLAC__ASSERT(0 != encoder);
1519         FLAC__ASSERT(0 != encoder->private_);
1520         FLAC__ASSERT(0 != encoder->protected_);
1521         FLAC__ASSERT(0 != specification);
1522         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1523                 return false;
1524 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1525         (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1526 #else
1527         encoder->protected_->num_apodizations = 0;
1528         while(1) {
1529                 const char *s = strchr(specification, ';');
1530                 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1531                 if     (n==8  && 0 == strncmp("bartlett"     , specification, n))
1532                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1533                 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1534                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1535                 else if(n==8  && 0 == strncmp("blackman"     , specification, n))
1536                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1537                 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1538                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1539                 else if(n==6  && 0 == strncmp("connes"       , specification, n))
1540                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1541                 else if(n==7  && 0 == strncmp("flattop"      , specification, n))
1542                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1543                 else if(n>7   && 0 == strncmp("gauss("       , specification, 6)) {
1544                         FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1545                         if (stddev > 0.0 && stddev <= 0.5) {
1546                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1547                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1548                         }
1549                 }
1550                 else if(n==7  && 0 == strncmp("hamming"      , specification, n))
1551                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1552                 else if(n==4  && 0 == strncmp("hann"         , specification, n))
1553                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1554                 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1555                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1556                 else if(n==7  && 0 == strncmp("nuttall"      , specification, n))
1557                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1558                 else if(n==9  && 0 == strncmp("rectangle"    , specification, n))
1559                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1560                 else if(n==8  && 0 == strncmp("triangle"     , specification, n))
1561                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1562                 else if(n>7   && 0 == strncmp("tukey("       , specification, 6)) {
1563                         FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1564                         if (p >= 0.0 && p <= 1.0) {
1565                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1566                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1567                         }
1568                 }
1569                 else if(n==5  && 0 == strncmp("welch"        , specification, n))
1570                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1571                 if (encoder->protected_->num_apodizations == 32)
1572                         break;
1573                 if (s)
1574                         specification = s+1;
1575                 else
1576                         break;
1577         }
1578         if(encoder->protected_->num_apodizations == 0) {
1579                 encoder->protected_->num_apodizations = 1;
1580                 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1581                 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1582         }
1583 #endif
1584         return true;
1585 }
1586
1587 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1588 {
1589         FLAC__ASSERT(0 != encoder);
1590         FLAC__ASSERT(0 != encoder->private_);
1591         FLAC__ASSERT(0 != encoder->protected_);
1592         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1593                 return false;
1594         encoder->protected_->max_lpc_order = value;
1595         return true;
1596 }
1597
1598 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1599 {
1600         FLAC__ASSERT(0 != encoder);
1601         FLAC__ASSERT(0 != encoder->private_);
1602         FLAC__ASSERT(0 != encoder->protected_);
1603         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1604                 return false;
1605         encoder->protected_->qlp_coeff_precision = value;
1606         return true;
1607 }
1608
1609 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1610 {
1611         FLAC__ASSERT(0 != encoder);
1612         FLAC__ASSERT(0 != encoder->private_);
1613         FLAC__ASSERT(0 != encoder->protected_);
1614         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1615                 return false;
1616         encoder->protected_->do_qlp_coeff_prec_search = value;
1617         return true;
1618 }
1619
1620 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1621 {
1622         FLAC__ASSERT(0 != encoder);
1623         FLAC__ASSERT(0 != encoder->private_);
1624         FLAC__ASSERT(0 != encoder->protected_);
1625         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1626                 return false;
1627 #if 0
1628         /*@@@ deprecated: */
1629         encoder->protected_->do_escape_coding = value;
1630 #else
1631         (void)value;
1632 #endif
1633         return true;
1634 }
1635
1636 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1637 {
1638         FLAC__ASSERT(0 != encoder);
1639         FLAC__ASSERT(0 != encoder->private_);
1640         FLAC__ASSERT(0 != encoder->protected_);
1641         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1642                 return false;
1643         encoder->protected_->do_exhaustive_model_search = value;
1644         return true;
1645 }
1646
1647 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1648 {
1649         FLAC__ASSERT(0 != encoder);
1650         FLAC__ASSERT(0 != encoder->private_);
1651         FLAC__ASSERT(0 != encoder->protected_);
1652         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1653                 return false;
1654         encoder->protected_->min_residual_partition_order = value;
1655         return true;
1656 }
1657
1658 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1659 {
1660         FLAC__ASSERT(0 != encoder);
1661         FLAC__ASSERT(0 != encoder->private_);
1662         FLAC__ASSERT(0 != encoder->protected_);
1663         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1664                 return false;
1665         encoder->protected_->max_residual_partition_order = value;
1666         return true;
1667 }
1668
1669 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1670 {
1671         FLAC__ASSERT(0 != encoder);
1672         FLAC__ASSERT(0 != encoder->private_);
1673         FLAC__ASSERT(0 != encoder->protected_);
1674         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1675                 return false;
1676 #if 0
1677         /*@@@ deprecated: */
1678         encoder->protected_->rice_parameter_search_dist = value;
1679 #else
1680         (void)value;
1681 #endif
1682         return true;
1683 }
1684
1685 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1686 {
1687         FLAC__ASSERT(0 != encoder);
1688         FLAC__ASSERT(0 != encoder->private_);
1689         FLAC__ASSERT(0 != encoder->protected_);
1690         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1691                 return false;
1692         encoder->protected_->total_samples_estimate = value;
1693         return true;
1694 }
1695
1696 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1697 {
1698         FLAC__ASSERT(0 != encoder);
1699         FLAC__ASSERT(0 != encoder->private_);
1700         FLAC__ASSERT(0 != encoder->protected_);
1701         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1702                 return false;
1703         if(0 == metadata)
1704                 num_blocks = 0;
1705         if(0 == num_blocks)
1706                 metadata = 0;
1707         /* realloc() does not do exactly what we want so... */
1708         if(encoder->protected_->metadata) {
1709                 free(encoder->protected_->metadata);
1710                 encoder->protected_->metadata = 0;
1711                 encoder->protected_->num_metadata_blocks = 0;
1712         }
1713         if(num_blocks) {
1714                 FLAC__StreamMetadata **m;
1715                 if(0 == (m = (FLAC__StreamMetadata**)malloc(sizeof(m[0]) * num_blocks)))
1716                         return false;
1717                 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1718                 encoder->protected_->metadata = m;
1719                 encoder->protected_->num_metadata_blocks = num_blocks;
1720         }
1721 #if FLAC__HAS_OGG
1722         if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1723                 return false;
1724 #endif
1725         return true;
1726 }
1727
1728 /*
1729  * These three functions are not static, but not publically exposed in
1730  * include/FLAC/ either.  They are used by the test suite.
1731  */
1732 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1733 {
1734         FLAC__ASSERT(0 != encoder);
1735         FLAC__ASSERT(0 != encoder->private_);
1736         FLAC__ASSERT(0 != encoder->protected_);
1737         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1738                 return false;
1739         encoder->private_->disable_constant_subframes = value;
1740         return true;
1741 }
1742
1743 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1744 {
1745         FLAC__ASSERT(0 != encoder);
1746         FLAC__ASSERT(0 != encoder->private_);
1747         FLAC__ASSERT(0 != encoder->protected_);
1748         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1749                 return false;
1750         encoder->private_->disable_fixed_subframes = value;
1751         return true;
1752 }
1753
1754 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1755 {
1756         FLAC__ASSERT(0 != encoder);
1757         FLAC__ASSERT(0 != encoder->private_);
1758         FLAC__ASSERT(0 != encoder->protected_);
1759         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1760                 return false;
1761         encoder->private_->disable_verbatim_subframes = value;
1762         return true;
1763 }
1764
1765 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1766 {
1767         FLAC__ASSERT(0 != encoder);
1768         FLAC__ASSERT(0 != encoder->private_);
1769         FLAC__ASSERT(0 != encoder->protected_);
1770         return encoder->protected_->state;
1771 }
1772
1773 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1774 {
1775         FLAC__ASSERT(0 != encoder);
1776         FLAC__ASSERT(0 != encoder->private_);
1777         FLAC__ASSERT(0 != encoder->protected_);
1778         if(encoder->protected_->verify)
1779                 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1780         else
1781                 return FLAC__STREAM_DECODER_UNINITIALIZED;
1782 }
1783
1784 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1785 {
1786         FLAC__ASSERT(0 != encoder);
1787         FLAC__ASSERT(0 != encoder->private_);
1788         FLAC__ASSERT(0 != encoder->protected_);
1789         if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1790                 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1791         else
1792                 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1793 }
1794
1795 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)
1796 {
1797         FLAC__ASSERT(0 != encoder);
1798         FLAC__ASSERT(0 != encoder->private_);
1799         FLAC__ASSERT(0 != encoder->protected_);
1800         if(0 != absolute_sample)
1801                 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1802         if(0 != frame_number)
1803                 *frame_number = encoder->private_->verify.error_stats.frame_number;
1804         if(0 != channel)
1805                 *channel = encoder->private_->verify.error_stats.channel;
1806         if(0 != sample)
1807                 *sample = encoder->private_->verify.error_stats.sample;
1808         if(0 != expected)
1809                 *expected = encoder->private_->verify.error_stats.expected;
1810         if(0 != got)
1811                 *got = encoder->private_->verify.error_stats.got;
1812 }
1813
1814 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1815 {
1816         FLAC__ASSERT(0 != encoder);
1817         FLAC__ASSERT(0 != encoder->private_);
1818         FLAC__ASSERT(0 != encoder->protected_);
1819         return encoder->protected_->verify;
1820 }
1821
1822 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1823 {
1824         FLAC__ASSERT(0 != encoder);
1825         FLAC__ASSERT(0 != encoder->private_);
1826         FLAC__ASSERT(0 != encoder->protected_);
1827         return encoder->protected_->streamable_subset;
1828 }
1829
1830 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1831 {
1832         FLAC__ASSERT(0 != encoder);
1833         FLAC__ASSERT(0 != encoder->private_);
1834         FLAC__ASSERT(0 != encoder->protected_);
1835         return encoder->protected_->channels;
1836 }
1837
1838 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1839 {
1840         FLAC__ASSERT(0 != encoder);
1841         FLAC__ASSERT(0 != encoder->private_);
1842         FLAC__ASSERT(0 != encoder->protected_);
1843         return encoder->protected_->bits_per_sample;
1844 }
1845
1846 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1847 {
1848         FLAC__ASSERT(0 != encoder);
1849         FLAC__ASSERT(0 != encoder->private_);
1850         FLAC__ASSERT(0 != encoder->protected_);
1851         return encoder->protected_->sample_rate;
1852 }
1853
1854 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1855 {
1856         FLAC__ASSERT(0 != encoder);
1857         FLAC__ASSERT(0 != encoder->private_);
1858         FLAC__ASSERT(0 != encoder->protected_);
1859         return encoder->protected_->blocksize;
1860 }
1861
1862 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1863 {
1864         FLAC__ASSERT(0 != encoder);
1865         FLAC__ASSERT(0 != encoder->private_);
1866         FLAC__ASSERT(0 != encoder->protected_);
1867         return encoder->protected_->do_mid_side_stereo;
1868 }
1869
1870 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1871 {
1872         FLAC__ASSERT(0 != encoder);
1873         FLAC__ASSERT(0 != encoder->private_);
1874         FLAC__ASSERT(0 != encoder->protected_);
1875         return encoder->protected_->loose_mid_side_stereo;
1876 }
1877
1878 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1879 {
1880         FLAC__ASSERT(0 != encoder);
1881         FLAC__ASSERT(0 != encoder->private_);
1882         FLAC__ASSERT(0 != encoder->protected_);
1883         return encoder->protected_->max_lpc_order;
1884 }
1885
1886 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1887 {
1888         FLAC__ASSERT(0 != encoder);
1889         FLAC__ASSERT(0 != encoder->private_);
1890         FLAC__ASSERT(0 != encoder->protected_);
1891         return encoder->protected_->qlp_coeff_precision;
1892 }
1893
1894 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1895 {
1896         FLAC__ASSERT(0 != encoder);
1897         FLAC__ASSERT(0 != encoder->private_);
1898         FLAC__ASSERT(0 != encoder->protected_);
1899         return encoder->protected_->do_qlp_coeff_prec_search;
1900 }
1901
1902 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1903 {
1904         FLAC__ASSERT(0 != encoder);
1905         FLAC__ASSERT(0 != encoder->private_);
1906         FLAC__ASSERT(0 != encoder->protected_);
1907         return encoder->protected_->do_escape_coding;
1908 }
1909
1910 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1911 {
1912         FLAC__ASSERT(0 != encoder);
1913         FLAC__ASSERT(0 != encoder->private_);
1914         FLAC__ASSERT(0 != encoder->protected_);
1915         return encoder->protected_->do_exhaustive_model_search;
1916 }
1917
1918 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1919 {
1920         FLAC__ASSERT(0 != encoder);
1921         FLAC__ASSERT(0 != encoder->private_);
1922         FLAC__ASSERT(0 != encoder->protected_);
1923         return encoder->protected_->min_residual_partition_order;
1924 }
1925
1926 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1927 {
1928         FLAC__ASSERT(0 != encoder);
1929         FLAC__ASSERT(0 != encoder->private_);
1930         FLAC__ASSERT(0 != encoder->protected_);
1931         return encoder->protected_->max_residual_partition_order;
1932 }
1933
1934 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1935 {
1936         FLAC__ASSERT(0 != encoder);
1937         FLAC__ASSERT(0 != encoder->private_);
1938         FLAC__ASSERT(0 != encoder->protected_);
1939         return encoder->protected_->rice_parameter_search_dist;
1940 }
1941
1942 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1943 {
1944         FLAC__ASSERT(0 != encoder);
1945         FLAC__ASSERT(0 != encoder->private_);
1946         FLAC__ASSERT(0 != encoder->protected_);
1947         return encoder->protected_->total_samples_estimate;
1948 }
1949
1950 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1951 {
1952         unsigned i, j = 0, channel;
1953         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1954
1955         FLAC__ASSERT(0 != encoder);
1956         FLAC__ASSERT(0 != encoder->private_);
1957         FLAC__ASSERT(0 != encoder->protected_);
1958         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1959
1960         do {
1961                 const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
1962
1963                 if(encoder->protected_->verify)
1964                         append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
1965
1966                 for(channel = 0; channel < channels; channel++)
1967                         memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
1968
1969                 if(encoder->protected_->do_mid_side_stereo) {
1970 #ifdef _MSC_VER
1971                         FLAC__int32 x, mid, side;
1972 #endif
1973                         FLAC__ASSERT(channels == 2);
1974                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
1975                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1976 #ifdef _MSC_VER /* OPT: @@@@@@ make sure this is really faster on MSVC6, else drop it, make appropriate change in ..._interleaved() too */
1977                                 mid = side = buffer[0][j];
1978                                 x = buffer[1][j];
1979                                 mid += x;
1980                                 side -= x;
1981                                 encoder->private_->integer_signal_mid_side[1][i] = side;
1982                                 encoder->private_->integer_signal_mid_side[0][i] = mid >> 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
1983 #else
1984                                 encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
1985                                 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' ! */
1986 #endif
1987                         }
1988                 }
1989                 else
1990                         j += n;
1991
1992                 encoder->private_->current_sample_number += n;
1993
1994                 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
1995                 if(encoder->private_->current_sample_number > blocksize) {
1996                         if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
1997                                 return false;
1998                         /* move unprocessed overread samples to beginnings of arrays */
1999                         FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
2000                         FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2001                         for(channel = 0; channel < channels; channel++)
2002                                 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2003                         if(encoder->protected_->do_mid_side_stereo) {
2004                                 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2005                                 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2006                         }
2007                         encoder->private_->current_sample_number = 1;
2008                 }
2009         } while(j < samples);
2010
2011         return true;
2012 }
2013
2014 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2015 {
2016         unsigned i, j, k, channel;
2017         FLAC__int32 x, mid, side;
2018         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2019
2020         FLAC__ASSERT(0 != encoder);
2021         FLAC__ASSERT(0 != encoder->private_);
2022         FLAC__ASSERT(0 != encoder->protected_);
2023         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2024
2025         j = k = 0;
2026         /*
2027          * we have several flavors of the same basic loop, optimized for
2028          * different conditions:
2029          */
2030         if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2031                 /*
2032                  * stereo coding: unroll channel loop
2033                  */
2034                 do {
2035                         if(encoder->protected_->verify)
2036                                 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2037
2038                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2039                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2040                                 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2041                                 x = buffer[k++];
2042                                 encoder->private_->integer_signal[1][i] = x;
2043                                 mid += x;
2044                                 side -= x;
2045                                 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2046                                 encoder->private_->integer_signal_mid_side[1][i] = side;
2047                                 encoder->private_->integer_signal_mid_side[0][i] = mid;
2048                         }
2049                         encoder->private_->current_sample_number = i;
2050                         /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2051                         if(i > blocksize) {
2052                                 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2053                                         return false;
2054                                 /* move unprocessed overread samples to beginnings of arrays */
2055                                 FLAC__ASSERT(i == blocksize+OVERREAD_);
2056                                 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2057                                 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
2058                                 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
2059                                 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2060                                 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2061                                 encoder->private_->current_sample_number = 1;
2062                         }
2063                 } while(j < samples);
2064         }
2065         else {
2066                 /*
2067                  * independent channel coding: buffer each channel in inner loop
2068                  */
2069                 do {
2070                         if(encoder->protected_->verify)
2071                                 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2072
2073                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2074                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2075                                 for(channel = 0; channel < channels; channel++)
2076                                         encoder->private_->integer_signal[channel][i] = buffer[k++];
2077                         }
2078                         encoder->private_->current_sample_number = i;
2079                         /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2080                         if(i > blocksize) {
2081                                 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2082                                         return false;
2083                                 /* move unprocessed overread samples to beginnings of arrays */
2084                                 FLAC__ASSERT(i == blocksize+OVERREAD_);
2085                                 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2086                                 for(channel = 0; channel < channels; channel++)
2087                                         encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2088                                 encoder->private_->current_sample_number = 1;
2089                         }
2090                 } while(j < samples);
2091         }
2092
2093         return true;
2094 }
2095
2096 /***********************************************************************
2097  *
2098  * Private class methods
2099  *
2100  ***********************************************************************/
2101
2102 void set_defaults_(FLAC__StreamEncoder *encoder)
2103 {
2104         FLAC__ASSERT(0 != encoder);
2105
2106 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2107         encoder->protected_->verify = true;
2108 #else
2109         encoder->protected_->verify = false;
2110 #endif
2111         encoder->protected_->streamable_subset = true;
2112         encoder->protected_->do_mid_side_stereo = false;
2113         encoder->protected_->loose_mid_side_stereo = false;
2114         encoder->protected_->channels = 2;
2115         encoder->protected_->bits_per_sample = 16;
2116         encoder->protected_->sample_rate = 44100;
2117         encoder->protected_->blocksize = 0;
2118 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2119         encoder->protected_->num_apodizations = 1;
2120         encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2121         encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2122 #endif
2123         encoder->protected_->max_lpc_order = 0;
2124         encoder->protected_->qlp_coeff_precision = 0;
2125         encoder->protected_->do_qlp_coeff_prec_search = false;
2126         encoder->protected_->do_exhaustive_model_search = false;
2127         encoder->protected_->do_escape_coding = false;
2128         encoder->protected_->min_residual_partition_order = 0;
2129         encoder->protected_->max_residual_partition_order = 0;
2130         encoder->protected_->rice_parameter_search_dist = 0;
2131         encoder->protected_->total_samples_estimate = 0;
2132         encoder->protected_->metadata = 0;
2133         encoder->protected_->num_metadata_blocks = 0;
2134
2135         encoder->private_->seek_table = 0;
2136         encoder->private_->disable_constant_subframes = false;
2137         encoder->private_->disable_fixed_subframes = false;
2138         encoder->private_->disable_verbatim_subframes = false;
2139 #if FLAC__HAS_OGG
2140         encoder->private_->is_ogg = false;
2141 #endif
2142         encoder->private_->read_callback = 0;
2143         encoder->private_->write_callback = 0;
2144         encoder->private_->seek_callback = 0;
2145         encoder->private_->tell_callback = 0;
2146         encoder->private_->metadata_callback = 0;
2147         encoder->private_->progress_callback = 0;
2148         encoder->private_->client_data = 0;
2149
2150 #if FLAC__HAS_OGG
2151         FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2152 #endif
2153 }
2154
2155 void free_(FLAC__StreamEncoder *encoder)
2156 {
2157         unsigned i, channel;
2158
2159         FLAC__ASSERT(0 != encoder);
2160         if(encoder->protected_->metadata) {
2161                 free(encoder->protected_->metadata);
2162                 encoder->protected_->metadata = 0;
2163                 encoder->protected_->num_metadata_blocks = 0;
2164         }
2165         for(i = 0; i < encoder->protected_->channels; i++) {
2166                 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2167                         free(encoder->private_->integer_signal_unaligned[i]);
2168                         encoder->private_->integer_signal_unaligned[i] = 0;
2169                 }
2170 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2171                 if(0 != encoder->private_->real_signal_unaligned[i]) {
2172                         free(encoder->private_->real_signal_unaligned[i]);
2173                         encoder->private_->real_signal_unaligned[i] = 0;
2174                 }
2175 #endif
2176         }
2177         for(i = 0; i < 2; i++) {
2178                 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2179                         free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2180                         encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2181                 }
2182 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2183                 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2184                         free(encoder->private_->real_signal_mid_side_unaligned[i]);
2185                         encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2186                 }
2187 #endif
2188         }
2189 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2190         for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2191                 if(0 != encoder->private_->window_unaligned[i]) {
2192                         free(encoder->private_->window_unaligned[i]);
2193                         encoder->private_->window_unaligned[i] = 0;
2194                 }
2195         }
2196         if(0 != encoder->private_->windowed_signal_unaligned) {
2197                 free(encoder->private_->windowed_signal_unaligned);
2198                 encoder->private_->windowed_signal_unaligned = 0;
2199         }
2200 #endif
2201         for(channel = 0; channel < encoder->protected_->channels; channel++) {
2202                 for(i = 0; i < 2; i++) {
2203                         if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2204                                 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2205                                 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2206                         }
2207                 }
2208         }
2209         for(channel = 0; channel < 2; channel++) {
2210                 for(i = 0; i < 2; i++) {
2211                         if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2212                                 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2213                                 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2214                         }
2215                 }
2216         }
2217         if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2218                 free(encoder->private_->abs_residual_partition_sums_unaligned);
2219                 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2220         }
2221         if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2222                 free(encoder->private_->raw_bits_per_partition_unaligned);
2223                 encoder->private_->raw_bits_per_partition_unaligned = 0;
2224         }
2225         if(encoder->protected_->verify) {
2226                 for(i = 0; i < encoder->protected_->channels; i++) {
2227                         if(0 != encoder->private_->verify.input_fifo.data[i]) {
2228                                 free(encoder->private_->verify.input_fifo.data[i]);
2229                                 encoder->private_->verify.input_fifo.data[i] = 0;
2230                         }
2231                 }
2232         }
2233         FLAC__bitwriter_free(encoder->private_->frame);
2234 }
2235
2236 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2237 {
2238         FLAC__bool ok;
2239         unsigned i, channel;
2240
2241         FLAC__ASSERT(new_blocksize > 0);
2242         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2243         FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2244
2245         /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2246         if(new_blocksize <= encoder->private_->input_capacity)
2247                 return true;
2248
2249         ok = true;
2250
2251         /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
2252          * requires that the input arrays (in our case the integer signals)
2253          * have a buffer of up to 3 zeroes in front (at negative indices) for
2254          * alignment purposes; we use 4 in front to keep the data well-aligned.
2255          */
2256
2257         for(i = 0; ok && i < encoder->protected_->channels; i++) {
2258                 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2259                 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2260                 encoder->private_->integer_signal[i] += 4;
2261 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2262 #if 0 /* @@@ currently unused */
2263                 if(encoder->protected_->max_lpc_order > 0)
2264                         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2265 #endif
2266 #endif
2267         }
2268         for(i = 0; ok && i < 2; i++) {
2269                 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]);
2270                 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2271                 encoder->private_->integer_signal_mid_side[i] += 4;
2272 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2273 #if 0 /* @@@ currently unused */
2274                 if(encoder->protected_->max_lpc_order > 0)
2275                         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]);
2276 #endif
2277 #endif
2278         }
2279 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2280         if(ok && encoder->protected_->max_lpc_order > 0) {
2281                 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2282                         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2283                 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2284         }
2285 #endif
2286         for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2287                 for(i = 0; ok && i < 2; i++) {
2288                         ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2289                 }
2290         }
2291         for(channel = 0; ok && channel < 2; channel++) {
2292                 for(i = 0; ok && i < 2; i++) {
2293                         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]);
2294                 }
2295         }
2296         /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2297         /*@@@ 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) */
2298         ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2299         if(encoder->protected_->do_escape_coding)
2300                 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2301
2302         /* now adjust the windows if the blocksize has changed */
2303 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2304         if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2305                 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2306                         switch(encoder->protected_->apodizations[i].type) {
2307                                 case FLAC__APODIZATION_BARTLETT:
2308                                         FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2309                                         break;
2310                                 case FLAC__APODIZATION_BARTLETT_HANN:
2311                                         FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2312                                         break;
2313                                 case FLAC__APODIZATION_BLACKMAN:
2314                                         FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2315                                         break;
2316                                 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2317                                         FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2318                                         break;
2319                                 case FLAC__APODIZATION_CONNES:
2320                                         FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2321                                         break;
2322                                 case FLAC__APODIZATION_FLATTOP:
2323                                         FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2324                                         break;
2325                                 case FLAC__APODIZATION_GAUSS:
2326                                         FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2327                                         break;
2328                                 case FLAC__APODIZATION_HAMMING:
2329                                         FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2330                                         break;
2331                                 case FLAC__APODIZATION_HANN:
2332                                         FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2333                                         break;
2334                                 case FLAC__APODIZATION_KAISER_BESSEL:
2335                                         FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2336                                         break;
2337                                 case FLAC__APODIZATION_NUTTALL:
2338                                         FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2339                                         break;
2340                                 case FLAC__APODIZATION_RECTANGLE:
2341                                         FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2342                                         break;
2343                                 case FLAC__APODIZATION_TRIANGLE:
2344                                         FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2345                                         break;
2346                                 case FLAC__APODIZATION_TUKEY:
2347                                         FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2348                                         break;
2349                                 case FLAC__APODIZATION_WELCH:
2350                                         FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2351                                         break;
2352                                 default:
2353                                         FLAC__ASSERT(0);
2354                                         /* double protection */
2355                                         FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2356                                         break;
2357                         }
2358                 }
2359         }
2360 #endif
2361
2362         if(ok)
2363                 encoder->private_->input_capacity = new_blocksize;
2364         else
2365                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2366
2367         return ok;
2368 }
2369
2370 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2371 {
2372         const FLAC__byte *buffer;
2373         size_t bytes;
2374
2375         FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2376
2377         if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2378                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2379                 return false;
2380         }
2381
2382         if(encoder->protected_->verify) {
2383                 encoder->private_->verify.output.data = buffer;
2384                 encoder->private_->verify.output.bytes = bytes;
2385                 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2386                         encoder->private_->verify.needs_magic_hack = true;
2387                 }
2388                 else {
2389                         if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2390                                 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2391                                 FLAC__bitwriter_clear(encoder->private_->frame);
2392                                 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2393                                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2394                                 return false;
2395                         }
2396                 }
2397         }
2398
2399         if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2400                 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2401                 FLAC__bitwriter_clear(encoder->private_->frame);
2402                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2403                 return false;
2404         }
2405
2406         FLAC__bitwriter_release_buffer(encoder->private_->frame);
2407         FLAC__bitwriter_clear(encoder->private_->frame);
2408
2409         if(samples > 0) {
2410                 encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2411                 encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2412         }
2413
2414         return true;
2415 }
2416
2417 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2418 {
2419         FLAC__StreamEncoderWriteStatus status;
2420         FLAC__uint64 output_position = 0;
2421
2422         /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2423         if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2424                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2425                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2426         }
2427
2428         /*
2429          * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2430          */
2431         if(samples == 0) {
2432                 FLAC__MetadataType type = (buffer[0] & 0x7f);
2433                 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2434                         encoder->protected_->streaminfo_offset = output_position;
2435                 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2436                         encoder->protected_->seektable_offset = output_position;
2437         }
2438
2439         /*
2440          * Mark the current seek point if hit (if audio_offset == 0 that
2441          * means we're still writing metadata and haven't hit the first
2442          * frame yet)
2443          */
2444         if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2445                 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2446                 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2447                 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2448                 FLAC__uint64 test_sample;
2449                 unsigned i;
2450                 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2451                         test_sample = encoder->private_->seek_table->points[i].sample_number;
2452                         if(test_sample > frame_last_sample) {
2453                                 break;
2454                         }
2455                         else if(test_sample >= frame_first_sample) {
2456                                 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2457                                 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2458                                 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2459                                 encoder->private_->first_seekpoint_to_check++;
2460                                 /* DO NOT: "break;" and here's why:
2461                                  * The seektable template may contain more than one target
2462                                  * sample for any given frame; we will keep looping, generating
2463                                  * duplicate seekpoints for them, and we'll clean it up later,
2464                                  * just before writing the seektable back to the metadata.
2465                                  */
2466                         }
2467                         else {
2468                                 encoder->private_->first_seekpoint_to_check++;
2469                         }
2470                 }
2471         }
2472
2473 #if FLAC__HAS_OGG
2474         if(encoder->private_->is_ogg) {
2475                 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2476                         &encoder->protected_->ogg_encoder_aspect,
2477                         buffer,
2478                         bytes,
2479                         samples,
2480                         encoder->private_->current_frame_number,
2481                         is_last_block,
2482                         (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2483                         encoder,
2484                         encoder->private_->client_data
2485                 );
2486         }
2487         else
2488 #endif
2489         status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2490
2491         if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2492                 encoder->private_->bytes_written += bytes;
2493                 encoder->private_->samples_written += samples;
2494                 /* we keep a high watermark on the number of frames written because
2495                  * when the encoder goes back to write metadata, 'current_frame'
2496                  * will drop back to 0.
2497                  */
2498                 encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2499         }
2500         else
2501                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2502
2503         return status;
2504 }
2505
2506 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2507 void update_metadata_(const FLAC__StreamEncoder *encoder)
2508 {
2509         FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2510         const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2511         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2512         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2513         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2514         const unsigned bps = metadata->data.stream_info.bits_per_sample;
2515         FLAC__StreamEncoderSeekStatus seek_status;
2516
2517         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2518
2519         /* All this is based on intimate knowledge of the stream header
2520          * layout, but a change to the header format that would break this
2521          * would also break all streams encoded in the previous format.
2522          */
2523
2524         /*
2525          * Write MD5 signature
2526          */
2527         {
2528                 const unsigned md5_offset =
2529                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2530                         (
2531                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2532                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2533                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2534                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2535                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2536                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2537                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2538                                 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2539                         ) / 8;
2540
2541                 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2542                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2543                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2544                         return;
2545                 }
2546                 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2547                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2548                         return;
2549                 }
2550         }
2551
2552         /*
2553          * Write total samples
2554          */
2555         {
2556                 const unsigned total_samples_byte_offset =
2557                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2558                         (
2559                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2560                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2561                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2562                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2563                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2564                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2565                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2566                                 - 4
2567                         ) / 8;
2568
2569                 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2570                 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2571                 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2572                 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2573                 b[4] = (FLAC__byte)(samples & 0xFF);
2574                 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) {
2575                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2576                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2577                         return;
2578                 }
2579                 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2580                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2581                         return;
2582                 }
2583         }
2584
2585         /*
2586          * Write min/max framesize
2587          */
2588         {
2589                 const unsigned min_framesize_offset =
2590                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2591                         (
2592                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2593                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2594                         ) / 8;
2595
2596                 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2597                 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2598                 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2599                 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2600                 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2601                 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2602                 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) {
2603                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2604                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2605                         return;
2606                 }
2607                 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2608                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2609                         return;
2610                 }
2611         }
2612
2613         /*
2614          * Write seektable
2615          */
2616         if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2617                 unsigned i;
2618
2619                 FLAC__format_seektable_sort(encoder->private_->seek_table);
2620
2621                 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2622
2623                 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) {
2624                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2625                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2626                         return;
2627                 }
2628
2629                 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2630                         FLAC__uint64 xx;
2631                         unsigned x;
2632                         xx = encoder->private_->seek_table->points[i].sample_number;
2633                         b[7] = (FLAC__byte)xx; xx >>= 8;
2634                         b[6] = (FLAC__byte)xx; xx >>= 8;
2635                         b[5] = (FLAC__byte)xx; xx >>= 8;
2636                         b[4] = (FLAC__byte)xx; xx >>= 8;
2637                         b[3] = (FLAC__byte)xx; xx >>= 8;
2638                         b[2] = (FLAC__byte)xx; xx >>= 8;
2639                         b[1] = (FLAC__byte)xx; xx >>= 8;
2640                         b[0] = (FLAC__byte)xx; xx >>= 8;
2641                         xx = encoder->private_->seek_table->points[i].stream_offset;
2642                         b[15] = (FLAC__byte)xx; xx >>= 8;
2643                         b[14] = (FLAC__byte)xx; xx >>= 8;
2644                         b[13] = (FLAC__byte)xx; xx >>= 8;
2645                         b[12] = (FLAC__byte)xx; xx >>= 8;
2646                         b[11] = (FLAC__byte)xx; xx >>= 8;
2647                         b[10] = (FLAC__byte)xx; xx >>= 8;
2648                         b[9] = (FLAC__byte)xx; xx >>= 8;
2649                         b[8] = (FLAC__byte)xx; xx >>= 8;
2650                         x = encoder->private_->seek_table->points[i].frame_samples;
2651                         b[17] = (FLAC__byte)x; x >>= 8;
2652                         b[16] = (FLAC__byte)x; x >>= 8;
2653                         if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2654                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2655                                 return;
2656                         }
2657                 }
2658         }
2659 }
2660
2661 #if FLAC__HAS_OGG
2662 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2663 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2664 {
2665         /* the # of bytes in the 1st packet that precede the STREAMINFO */
2666         static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2667                 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2668                 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2669                 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2670                 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2671                 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2672                 FLAC__STREAM_SYNC_LENGTH
2673         ;
2674         FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2675         const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2676         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2677         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2678         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2679         ogg_page page;
2680
2681         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2682         FLAC__ASSERT(0 != encoder->private_->seek_callback);
2683
2684         /* Pre-check that client supports seeking, since we don't want the
2685          * ogg_helper code to ever have to deal with this condition.
2686          */
2687         if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2688                 return;
2689
2690         /* All this is based on intimate knowledge of the stream header
2691          * layout, but a change to the header format that would break this
2692          * would also break all streams encoded in the previous format.
2693          */
2694
2695         /**
2696          ** Write STREAMINFO stats
2697          **/
2698         simple_ogg_page__init(&page);
2699         if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2700                 simple_ogg_page__clear(&page);
2701                 return; /* state already set */
2702         }
2703
2704         /*
2705          * Write MD5 signature
2706          */
2707         {
2708                 const unsigned md5_offset =
2709                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2710                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2711                         (
2712                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2713                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2714                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2715                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2716                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2717                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2718                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2719                                 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2720                         ) / 8;
2721
2722                 if(md5_offset + 16 > (unsigned)page.body_len) {
2723                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2724                         simple_ogg_page__clear(&page);
2725                         return;
2726                 }
2727                 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2728         }
2729
2730         /*
2731          * Write total samples
2732          */
2733         {
2734                 const unsigned total_samples_byte_offset =
2735                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2736                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2737                         (
2738                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2739                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2740                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2741                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2742                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2743                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2744                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2745                                 - 4
2746                         ) / 8;
2747
2748                 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2749                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2750                         simple_ogg_page__clear(&page);
2751                         return;
2752                 }
2753                 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2754                 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2755                 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2756                 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2757                 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2758                 b[4] = (FLAC__byte)(samples & 0xFF);
2759                 memcpy(page.body + total_samples_byte_offset, b, 5);
2760         }
2761
2762         /*
2763          * Write min/max framesize
2764          */
2765         {
2766                 const unsigned min_framesize_offset =
2767                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2768                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2769                         (
2770                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2771                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2772                         ) / 8;
2773
2774                 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2775                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2776                         simple_ogg_page__clear(&page);
2777                         return;
2778                 }
2779                 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2780                 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2781                 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2782                 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2783                 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2784                 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2785                 memcpy(page.body + min_framesize_offset, b, 6);
2786         }
2787         if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2788                 simple_ogg_page__clear(&page);
2789                 return; /* state already set */
2790         }
2791         simple_ogg_page__clear(&page);
2792
2793         /*
2794          * Write seektable
2795          */
2796         if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2797                 unsigned i;
2798                 FLAC__byte *p;
2799
2800                 FLAC__format_seektable_sort(encoder->private_->seek_table);
2801
2802                 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2803
2804                 simple_ogg_page__init(&page);
2805                 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2806                         simple_ogg_page__clear(&page);
2807                         return; /* state already set */
2808                 }
2809
2810                 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
2811                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2812                         simple_ogg_page__clear(&page);
2813                         return;
2814                 }
2815
2816                 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
2817                         FLAC__uint64 xx;
2818                         unsigned x;
2819                         xx = encoder->private_->seek_table->points[i].sample_number;
2820                         b[7] = (FLAC__byte)xx; xx >>= 8;
2821                         b[6] = (FLAC__byte)xx; xx >>= 8;
2822                         b[5] = (FLAC__byte)xx; xx >>= 8;
2823                         b[4] = (FLAC__byte)xx; xx >>= 8;
2824                         b[3] = (FLAC__byte)xx; xx >>= 8;
2825                         b[2] = (FLAC__byte)xx; xx >>= 8;
2826                         b[1] = (FLAC__byte)xx; xx >>= 8;
2827                         b[0] = (FLAC__byte)xx; xx >>= 8;
2828                         xx = encoder->private_->seek_table->points[i].stream_offset;
2829                         b[15] = (FLAC__byte)xx; xx >>= 8;
2830                         b[14] = (FLAC__byte)xx; xx >>= 8;
2831                         b[13] = (FLAC__byte)xx; xx >>= 8;
2832                         b[12] = (FLAC__byte)xx; xx >>= 8;
2833                         b[11] = (FLAC__byte)xx; xx >>= 8;
2834                         b[10] = (FLAC__byte)xx; xx >>= 8;
2835                         b[9] = (FLAC__byte)xx; xx >>= 8;
2836                         b[8] = (FLAC__byte)xx; xx >>= 8;
2837                         x = encoder->private_->seek_table->points[i].frame_samples;
2838                         b[17] = (FLAC__byte)x; x >>= 8;
2839                         b[16] = (FLAC__byte)x; x >>= 8;
2840                         memcpy(p, b, 18);
2841                 }
2842
2843                 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2844                         simple_ogg_page__clear(&page);
2845                         return; /* state already set */
2846                 }
2847                 simple_ogg_page__clear(&page);
2848         }
2849 }
2850 #endif
2851
2852 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
2853 {
2854         FLAC__uint16 crc;
2855         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2856
2857         /*
2858          * Accumulate raw signal to the MD5 signature
2859          */
2860         if(!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)) {
2861                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2862                 return false;
2863         }
2864
2865         /*
2866          * Process the frame header and subframes into the frame bitbuffer
2867          */
2868         if(!process_subframes_(encoder, is_fractional_block)) {
2869                 /* the above function sets the state for us in case of an error */
2870                 return false;
2871         }
2872
2873         /*
2874          * Zero-pad the frame to a byte_boundary
2875          */
2876         if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
2877                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2878                 return false;
2879         }
2880
2881         /*
2882          * CRC-16 the whole thing
2883          */
2884         FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2885         if(
2886                 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
2887                 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
2888         ) {
2889                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2890                 return false;
2891         }
2892
2893         /*
2894          * Write it
2895          */
2896         if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
2897                 /* the above function sets the state for us in case of an error */
2898                 return false;
2899         }
2900
2901         /*
2902          * Get ready for the next frame
2903          */
2904         encoder->private_->current_sample_number = 0;
2905         encoder->private_->current_frame_number++;
2906         encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
2907
2908         return true;
2909 }
2910
2911 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
2912 {
2913         FLAC__FrameHeader frame_header;
2914         unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
2915         FLAC__bool do_independent, do_mid_side;
2916
2917         /*
2918          * Calculate the min,max Rice partition orders
2919          */
2920         if(is_fractional_block) {
2921                 max_partition_order = 0;
2922         }
2923         else {
2924                 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
2925                 max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
2926         }
2927         min_partition_order = min(min_partition_order, max_partition_order);
2928
2929         /*
2930          * Setup the frame
2931          */
2932         frame_header.blocksize = encoder->protected_->blocksize;
2933         frame_header.sample_rate = encoder->protected_->sample_rate;
2934         frame_header.channels = encoder->protected_->channels;
2935         frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
2936         frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
2937         frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2938         frame_header.number.frame_number = encoder->private_->current_frame_number;
2939
2940         /*
2941          * Figure out what channel assignments to try
2942          */
2943         if(encoder->protected_->do_mid_side_stereo) {
2944                 if(encoder->protected_->loose_mid_side_stereo) {
2945                         if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
2946                                 do_independent = true;
2947                                 do_mid_side = true;
2948                         }
2949                         else {
2950                                 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
2951                                 do_mid_side = !do_independent;
2952                         }
2953                 }
2954                 else {
2955                         do_independent = true;
2956                         do_mid_side = true;
2957                 }
2958         }
2959         else {
2960                 do_independent = true;
2961                 do_mid_side = false;
2962         }
2963
2964         FLAC__ASSERT(do_independent || do_mid_side);
2965
2966         /*
2967          * Check for wasted bits; set effective bps for each subframe
2968          */
2969         if(do_independent) {
2970                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2971                         const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
2972                         encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
2973                         encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
2974                 }
2975         }
2976         if(do_mid_side) {
2977                 FLAC__ASSERT(encoder->protected_->channels == 2);
2978                 for(channel = 0; channel < 2; channel++) {
2979                         const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
2980                         encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
2981                         encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
2982                 }
2983         }
2984
2985         /*
2986          * First do a normal encoding pass of each independent channel
2987          */
2988         if(do_independent) {
2989                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2990                         if(!
2991                                 process_subframe_(
2992                                         encoder,
2993                                         min_partition_order,
2994                                         max_partition_order,
2995                                         &frame_header,
2996                                         encoder->private_->subframe_bps[channel],
2997                                         encoder->private_->integer_signal[channel],
2998                                         encoder->private_->subframe_workspace_ptr[channel],
2999                                         encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3000                                         encoder->private_->residual_workspace[channel],
3001                                         encoder->private_->best_subframe+channel,
3002                                         encoder->private_->best_subframe_bits+channel
3003                                 )
3004                         )
3005                                 return false;
3006                 }
3007         }
3008
3009         /*
3010          * Now do mid and side channels if requested
3011          */
3012         if(do_mid_side) {
3013                 FLAC__ASSERT(encoder->protected_->channels == 2);
3014
3015                 for(channel = 0; channel < 2; channel++) {
3016                         if(!
3017                                 process_subframe_(
3018                                         encoder,
3019                                         min_partition_order,
3020                                         max_partition_order,
3021                                         &frame_header,
3022                                         encoder->private_->subframe_bps_mid_side[channel],
3023                                         encoder->private_->integer_signal_mid_side[channel],
3024                                         encoder->private_->subframe_workspace_ptr_mid_side[channel],
3025                                         encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3026                                         encoder->private_->residual_workspace_mid_side[channel],
3027                                         encoder->private_->best_subframe_mid_side+channel,
3028                                         encoder->private_->best_subframe_bits_mid_side+channel
3029                                 )
3030                         )
3031                                 return false;
3032                 }
3033         }
3034
3035         /*
3036          * Compose the frame bitbuffer
3037          */
3038         if(do_mid_side) {
3039                 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3040                 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3041                 FLAC__ChannelAssignment channel_assignment;
3042
3043                 FLAC__ASSERT(encoder->protected_->channels == 2);
3044
3045                 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3046                         channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3047                 }
3048                 else {
3049                         unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3050                         unsigned min_bits;
3051                         int ca;
3052
3053                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3054                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE   == 1);
3055                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE  == 2);
3056                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE    == 3);
3057                         FLAC__ASSERT(do_independent && do_mid_side);
3058
3059                         /* We have to figure out which channel assignent results in the smallest frame */
3060                         bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits         [1];
3061                         bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE  ] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits_mid_side[1];
3062                         bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits         [1] + encoder->private_->best_subframe_bits_mid_side[1];
3063                         bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE   ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3064
3065                         channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3066                         min_bits = bits[channel_assignment];
3067                         for(ca = 1; ca <= 3; ca++) {
3068                                 if(bits[ca] < min_bits) {
3069                                         min_bits = bits[ca];
3070                                         channel_assignment = (FLAC__ChannelAssignment)ca;
3071                                 }
3072                         }
3073                 }
3074
3075                 frame_header.channel_assignment = channel_assignment;
3076
3077                 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3078                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3079                         return false;
3080                 }
3081
3082                 switch(channel_assignment) {
3083                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3084                                 left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3085                                 right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
3086                                 break;
3087                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3088                                 left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3089                                 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3090                                 break;
3091                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3092                                 left_subframe  = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3093                                 right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
3094                                 break;
3095                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3096                                 left_subframe  = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3097                                 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3098                                 break;
3099                         default:
3100                                 FLAC__ASSERT(0);
3101                 }
3102
3103                 switch(channel_assignment) {
3104                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3105                                 left_bps  = encoder->private_->subframe_bps         [0];
3106                                 right_bps = encoder->private_->subframe_bps         [1];
3107                                 break;
3108                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3109                                 left_bps  = encoder->private_->subframe_bps         [0];
3110                                 right_bps = encoder->private_->subframe_bps_mid_side[1];
3111                                 break;
3112                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3113                                 left_bps  = encoder->private_->subframe_bps_mid_side[1];
3114                                 right_bps = encoder->private_->subframe_bps         [1];
3115                                 break;
3116                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3117                                 left_bps  = encoder->private_->subframe_bps_mid_side[0];
3118                                 right_bps = encoder->private_->subframe_bps_mid_side[1];
3119                                 break;
3120                         default:
3121                                 FLAC__ASSERT(0);
3122                 }
3123
3124                 /* note that encoder_add_subframe_ sets the state for us in case of an error */
3125                 if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3126                         return false;
3127                 if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3128                         return false;
3129         }
3130         else {
3131                 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3132                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3133                         return false;
3134                 }
3135
3136                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3137                         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)) {
3138                                 /* the above function sets the state for us in case of an error */
3139                                 return false;
3140                         }
3141                 }
3142         }
3143
3144         if(encoder->protected_->loose_mid_side_stereo) {
3145                 encoder->private_->loose_mid_side_stereo_frame_count++;
3146                 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3147                         encoder->private_->loose_mid_side_stereo_frame_count = 0;
3148         }
3149
3150         encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3151
3152         return true;
3153 }
3154
3155 FLAC__bool process_subframe_(
3156         FLAC__StreamEncoder *encoder,
3157         unsigned min_partition_order,
3158         unsigned max_partition_order,
3159         const FLAC__FrameHeader *frame_header,
3160         unsigned subframe_bps,
3161         const FLAC__int32 integer_signal[],
3162         FLAC__Subframe *subframe[2],
3163         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3164         FLAC__int32 *residual[2],
3165         unsigned *best_subframe,
3166         unsigned *best_bits
3167 )
3168 {
3169 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3170         FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3171 #else
3172         FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3173 #endif
3174 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3175         FLAC__double lpc_residual_bits_per_sample;
3176         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 */
3177         FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3178         unsigned min_lpc_order, max_lpc_order, lpc_order;
3179         unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3180 #endif
3181         unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3182         unsigned rice_parameter;
3183         unsigned _candidate_bits, _best_bits;
3184         unsigned _best_subframe;
3185
3186         FLAC__ASSERT(frame_header->blocksize > 0);
3187
3188         /* verbatim subframe is the baseline against which we measure other compressed subframes */
3189         _best_subframe = 0;
3190         if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3191                 _best_bits = UINT_MAX;
3192         else
3193                 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3194
3195         if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3196                 unsigned signal_is_constant = false;
3197                 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);
3198                 /* check for constant subframe */
3199                 if(
3200                         !encoder->private_->disable_constant_subframes &&
3201 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3202                         fixed_residual_bits_per_sample[1] == 0.0
3203 #else
3204                         fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3205 #endif
3206                 ) {
3207                         /* the above means it's possible all samples are the same value; now double-check it: */
3208                         unsigned i;
3209                         signal_is_constant = true;
3210                         for(i = 1; i < frame_header->blocksize; i++) {
3211                                 if(integer_signal[0] != integer_signal[i]) {
3212                                         signal_is_constant = false;
3213                                         break;
3214                                 }
3215                         }
3216                 }
3217                 if(signal_is_constant) {
3218                         _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3219                         if(_candidate_bits < _best_bits) {
3220                                 _best_subframe = !_best_subframe;
3221                                 _best_bits = _candidate_bits;
3222                         }
3223                 }
3224                 else {
3225                         if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3226                                 /* encode fixed */
3227                                 if(encoder->protected_->do_exhaustive_model_search) {
3228                                         min_fixed_order = 0;
3229                                         max_fixed_order = FLAC__MAX_FIXED_ORDER;
3230                                 }
3231                                 else {
3232                                         min_fixed_order = max_fixed_order = guess_fixed_order;
3233                                 }
3234                                 if(max_fixed_order >= frame_header->blocksize)
3235                                         max_fixed_order = frame_header->blocksize - 1;
3236                                 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3237 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3238                                         if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3239                                                 continue; /* don't even try */
3240                                         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 */
3241 #else
3242                                         if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3243                                                 continue; /* don't even try */
3244                                         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 */
3245 #endif
3246                                         rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3247                                         if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3248 #ifdef DEBUG_VERBOSE
3249                                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3250 #endif
3251                                                 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3252                                         }
3253                                         _candidate_bits =
3254                                                 evaluate_fixed_subframe_(
3255                                                         encoder,
3256                                                         integer_signal,
3257                                                         residual[!_best_subframe],
3258                                                         encoder->private_->abs_residual_partition_sums,
3259                                                         encoder->private_->raw_bits_per_partition,
3260                                                         frame_header->blocksize,
3261                                                         subframe_bps,
3262                                                         fixed_order,
3263                                                         rice_parameter,
3264                                                         min_partition_order,
3265                                                         max_partition_order,
3266                                                         encoder->protected_->do_escape_coding,
3267                                                         encoder->protected_->rice_parameter_search_dist,
3268                                                         subframe[!_best_subframe],
3269                                                         partitioned_rice_contents[!_best_subframe]
3270                                                 );
3271                                         if(_candidate_bits < _best_bits) {
3272                                                 _best_subframe = !_best_subframe;
3273                                                 _best_bits = _candidate_bits;
3274                                         }
3275                                 }
3276                         }
3277
3278 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3279                         /* encode lpc */
3280                         if(encoder->protected_->max_lpc_order > 0) {
3281                                 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3282                                         max_lpc_order = frame_header->blocksize-1;
3283                                 else
3284                                         max_lpc_order = encoder->protected_->max_lpc_order;
3285                                 if(max_lpc_order > 0) {
3286                                         unsigned a;
3287                                         for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3288                                                 FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3289                                                 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3290                                                 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3291                                                 if(autoc[0] != 0.0) {
3292                                                         FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3293                                                         if(encoder->protected_->do_exhaustive_model_search) {
3294                                                                 min_lpc_order = 1;
3295                                                         }
3296                                                         else {
3297                                                                 const unsigned guess_lpc_order =
3298                                                                         FLAC__lpc_compute_best_order(
3299                                                                                 lpc_error,
3300                                                                                 max_lpc_order,
3301                                                                                 frame_header->blocksize,
3302                                                                                 subframe_bps + (
3303                                                                                         encoder->protected_->do_qlp_coeff_prec_search?
3304                                                                                                 FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
3305                                                                                                 encoder->protected_->qlp_coeff_precision
3306                                                                                 )
3307                                                                         );
3308                                                                 min_lpc_order = max_lpc_order = guess_lpc_order;
3309                                                         }
3310                                                         if(max_lpc_order >= frame_header->blocksize)
3311                                                                 max_lpc_order = frame_header->blocksize - 1;
3312                                                         for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
3313                                                                 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
3314                                                                 if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
3315                                                                         continue; /* don't even try */
3316                                                                 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
3317                                                                 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3318                                                                 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3319 #ifdef DEBUG_VERBOSE
3320                                                                         fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3321 #endif
3322                                                                         rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3323                                                                 }
3324                                                                 if(encoder->protected_->do_qlp_coeff_prec_search) {
3325                                                                         min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
3326                                                                         /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
3327                                                                         if(subframe_bps <= 17) {
3328                                                                                 max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
3329                                                                                 max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
3330                                                                         }
3331                                                                         else
3332                                                                                 max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
3333                                                                 }
3334                                                                 else {
3335                                                                         min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
3336                                                                 }
3337                                                                 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
3338                                                                         _candidate_bits =
3339                                                                                 evaluate_lpc_subframe_(
3340                                                                                         encoder,
3341                                                                                         integer_signal,
3342                                                                                         residual[!_best_subframe],
3343                                                                                         encoder->private_->abs_residual_partition_sums,
3344                                                                                         encoder->private_->raw_bits_per_partition,
3345                                                                                         encoder->private_->lp_coeff[lpc_order-1],
3346                                                                                         frame_header->blocksize,
3347                                                                                         subframe_bps,
3348                                                                                         lpc_order,
3349                                                                                         qlp_coeff_precision,
3350                                                                                         rice_parameter,
3351                                                                                         min_partition_order,
3352                                                                                         max_partition_order,
3353                                                                                         encoder->protected_->do_escape_coding,
3354                                                                                         encoder->protected_->rice_parameter_search_dist,
3355                                                                                         subframe[!_best_subframe],
3356                                                                                         partitioned_rice_contents[!_best_subframe]
3357                                                                                 );
3358                                                                         if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
3359                                                                                 if(_candidate_bits < _best_bits) {
3360                                                                                         _best_subframe = !_best_subframe;
3361                                                                                         _best_bits = _candidate_bits;
3362                                                                                 }
3363                                                                         }
3364                                                                 }
3365                                                         }
3366                                                 }
3367                                         }
3368                                 }
3369                         }
3370 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3371                 }
3372         }
3373
3374         /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3375         if(_best_bits == UINT_MAX) {
3376                 FLAC__ASSERT(_best_subframe == 0);
3377                 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3378         }
3379
3380         *best_subframe = _best_subframe;
3381         *best_bits = _best_bits;
3382
3383         return true;
3384 }
3385
3386 FLAC__bool add_subframe_(
3387         FLAC__StreamEncoder *encoder,
3388         unsigned blocksize,
3389         unsigned subframe_bps,
3390         const FLAC__Subframe *subframe,
3391         FLAC__BitWriter *frame
3392 )
3393 {
3394         switch(subframe->type) {
3395                 case FLAC__SUBFRAME_TYPE_CONSTANT:
3396                         if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3397                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3398                                 return false;
3399                         }
3400                         break;
3401                 case FLAC__SUBFRAME_TYPE_FIXED:
3402                         if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3403                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3404                                 return false;
3405                         }
3406                         break;
3407                 case FLAC__SUBFRAME_TYPE_LPC:
3408                         if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, 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_VERBATIM:
3414                         if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3415                                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3416                                 return false;
3417                         }
3418                         break;
3419                 default:
3420                         FLAC__ASSERT(0);
3421         }
3422
3423         return true;
3424 }
3425
3426 #define SPOTCHECK_ESTIMATE 0
3427 #if SPOTCHECK_ESTIMATE
3428 static void spotcheck_subframe_estimate_(
3429         FLAC__StreamEncoder *encoder,
3430         unsigned blocksize,
3431         unsigned subframe_bps,
3432         const FLAC__Subframe *subframe,
3433         unsigned estimate
3434 )
3435 {
3436         FLAC__bool ret;
3437         FLAC__BitWriter *frame = FLAC__bitwriter_new();
3438         if(frame == 0) {
3439                 fprintf(stderr, "EST: can't allocate frame\n");
3440                 return;
3441         }
3442         if(!FLAC__bitwriter_init(frame)) {
3443                 fprintf(stderr, "EST: can't init frame\n");
3444                 return;
3445         }
3446         ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
3447         FLAC__ASSERT(ret);
3448         {
3449                 const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
3450                 if(estimate != actual)
3451                         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);
3452         }
3453         FLAC__bitwriter_delete(frame);
3454 }
3455 #endif
3456
3457 unsigned evaluate_constant_subframe_(
3458         FLAC__StreamEncoder *encoder,
3459         const FLAC__int32 signal,
3460         unsigned blocksize,
3461         unsigned subframe_bps,
3462         FLAC__Subframe *subframe
3463 )
3464 {
3465         unsigned estimate;
3466         subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3467         subframe->data.constant.value = signal;
3468
3469         estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
3470
3471 #if SPOTCHECK_ESTIMATE
3472         spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3473 #else
3474         (void)encoder, (void)blocksize;
3475 #endif
3476
3477         return estimate;
3478 }
3479
3480 unsigned evaluate_fixed_subframe_(
3481         FLAC__StreamEncoder *encoder,
3482         const FLAC__int32 signal[],
3483         FLAC__int32 residual[],
3484         FLAC__uint64 abs_residual_partition_sums[],
3485         unsigned raw_bits_per_partition[],
3486         unsigned blocksize,
3487         unsigned subframe_bps,
3488         unsigned order,
3489         unsigned rice_parameter,
3490         unsigned min_partition_order,
3491         unsigned max_partition_order,
3492         FLAC__bool do_escape_coding,
3493         unsigned rice_parameter_search_dist,
3494         FLAC__Subframe *subframe,
3495         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3496 )
3497 {
3498         unsigned i, residual_bits, estimate;
3499         const unsigned residual_samples = blocksize - order;
3500
3501         FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3502
3503         subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3504
3505         subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3506         subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3507         subframe->data.fixed.residual = residual;
3508
3509         residual_bits =
3510                 find_best_partition_order_(
3511                         encoder->private_,
3512                         residual,
3513                         abs_residual_partition_sums,
3514                         raw_bits_per_partition,
3515                         residual_samples,
3516                         order,
3517                         rice_parameter,
3518                         min_partition_order,
3519                         max_partition_order,
3520                         subframe_bps,
3521                         do_escape_coding,
3522                         rice_parameter_search_dist,
3523                         &subframe->data.fixed.entropy_coding_method.data.partitioned_rice
3524                 );
3525
3526         subframe->data.fixed.order = order;
3527         for(i = 0; i < order; i++)
3528                 subframe->data.fixed.warmup[i] = signal[i];
3529
3530         estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
3531
3532 #if SPOTCHECK_ESTIMATE
3533         spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3534 #endif
3535
3536         return estimate;
3537 }
3538
3539 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3540 unsigned evaluate_lpc_subframe_(
3541         FLAC__StreamEncoder *encoder,
3542         const FLAC__int32 signal[],
3543         FLAC__int32 residual[],
3544         FLAC__uint64 abs_residual_partition_sums[],
3545         unsigned raw_bits_per_partition[],
3546         const FLAC__real lp_coeff[],
3547         unsigned blocksize,
3548         unsigned subframe_bps,
3549         unsigned order,
3550         unsigned qlp_coeff_precision,
3551         unsigned rice_parameter,
3552         unsigned min_partition_order,
3553         unsigned max_partition_order,
3554         FLAC__bool do_escape_coding,
3555         unsigned rice_parameter_search_dist,
3556         FLAC__Subframe *subframe,
3557         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3558 )
3559 {
3560         FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
3561         unsigned i, residual_bits, estimate;
3562         int quantization, ret;
3563         const unsigned residual_samples = blocksize - order;
3564
3565         /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3566         if(subframe_bps <= 16) {
3567                 FLAC__ASSERT(order > 0);
3568                 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3569                 qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3570         }
3571
3572         ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3573         if(ret != 0)
3574                 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3575
3576         if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3577                 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3578                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3579                 else
3580                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3581         else
3582                 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3583
3584         subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3585
3586         subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3587         subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3588         subframe->data.lpc.residual = residual;
3589
3590         residual_bits =
3591                 find_best_partition_order_(
3592                         encoder->private_,
3593                         residual,
3594                         abs_residual_partition_sums,
3595                         raw_bits_per_partition,
3596                         residual_samples,
3597                         order,
3598                         rice_parameter,
3599                         min_partition_order,
3600                         max_partition_order,
3601                         subframe_bps,
3602                         do_escape_coding,
3603                         rice_parameter_search_dist,
3604                         &subframe->data.lpc.entropy_coding_method.data.partitioned_rice
3605                 );
3606
3607         subframe->data.lpc.order = order;
3608         subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3609         subframe->data.lpc.quantization_level = quantization;
3610         memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3611         for(i = 0; i < order; i++)
3612                 subframe->data.lpc.warmup[i] = signal[i];
3613
3614         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;
3615
3616 #if SPOTCHECK_ESTIMATE
3617         spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3618 #endif
3619
3620         return estimate;
3621 }
3622 #endif
3623
3624 unsigned evaluate_verbatim_subframe_(
3625         FLAC__StreamEncoder *encoder,
3626         const FLAC__int32 signal[],
3627         unsigned blocksize,
3628         unsigned subframe_bps,
3629         FLAC__Subframe *subframe
3630 )
3631 {
3632         unsigned estimate;
3633
3634         subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3635
3636         subframe->data.verbatim.data = signal;
3637
3638         estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
3639
3640 #if SPOTCHECK_ESTIMATE
3641         spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3642 #else
3643         (void)encoder;
3644 #endif
3645
3646         return estimate;
3647 }
3648
3649 unsigned find_best_partition_order_(
3650         FLAC__StreamEncoderPrivate *private_,
3651         const FLAC__int32 residual[],
3652         FLAC__uint64 abs_residual_partition_sums[],
3653         unsigned raw_bits_per_partition[],
3654         unsigned residual_samples,
3655         unsigned predictor_order,
3656         unsigned rice_parameter,
3657         unsigned min_partition_order,
3658         unsigned max_partition_order,
3659         unsigned bps,
3660         FLAC__bool do_escape_coding,
3661         unsigned rice_parameter_search_dist,
3662         FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
3663 )
3664 {
3665         unsigned residual_bits, best_residual_bits = 0;
3666         unsigned best_parameters_index = 0;
3667         const unsigned blocksize = residual_samples + predictor_order;
3668
3669         max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3670         min_partition_order = min(min_partition_order, max_partition_order);
3671
3672         precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
3673
3674         if(do_escape_coding)
3675                 precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3676
3677         {
3678                 int partition_order;
3679                 unsigned sum;
3680
3681                 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3682                         if(!
3683                                 set_partitioned_rice_(
3684 #ifdef EXACT_RICE_BITS_CALCULATION
3685                                         residual,
3686 #endif
3687                                         abs_residual_partition_sums+sum,
3688                                         raw_bits_per_partition+sum,
3689                                         residual_samples,
3690                                         predictor_order,
3691                                         rice_parameter,
3692                                         rice_parameter_search_dist,
3693                                         (unsigned)partition_order,
3694                                         do_escape_coding,
3695                                         &private_->partitioned_rice_contents_extra[!best_parameters_index],
3696                                         &residual_bits
3697                                 )
3698                         )
3699                         {
3700                                 FLAC__ASSERT(best_residual_bits != 0);
3701                                 break;
3702                         }
3703                         sum += 1u << partition_order;
3704                         if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3705                                 best_residual_bits = residual_bits;
3706                                 best_parameters_index = !best_parameters_index;
3707                                 best_partitioned_rice->order = partition_order;
3708                         }
3709                 }
3710         }
3711
3712         /*
3713          * We are allowed to de-const the pointer based on our special knowledge;
3714          * it is const to the outside world.
3715          */
3716         {
3717                 FLAC__EntropyCodingMethod_PartitionedRiceContents* best_partitioned_rice_contents = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_partitioned_rice->contents;
3718                 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(best_partitioned_rice_contents, max(6, best_partitioned_rice->order));
3719                 memcpy(best_partitioned_rice_contents->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
3720                 memcpy(best_partitioned_rice_contents->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
3721         }
3722
3723         return best_residual_bits;
3724 }
3725
3726 void precompute_partition_info_sums_(
3727         const FLAC__int32 residual[],
3728         FLAC__uint64 abs_residual_partition_sums[],
3729         unsigned residual_samples,
3730         unsigned predictor_order,
3731         unsigned min_partition_order,
3732         unsigned max_partition_order,
3733         unsigned bps
3734 )
3735 {
3736         int partition_order;
3737         unsigned from_partition, to_partition = 0;
3738         const unsigned blocksize = residual_samples + predictor_order;
3739         const unsigned partitions = 1u << max_partition_order;
3740         const unsigned default_partition_samples = blocksize >> max_partition_order;
3741         unsigned partition, end, residual_sample;
3742
3743         FLAC__ASSERT(default_partition_samples > predictor_order);
3744
3745         /* first do max_partition_order */
3746         if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) { /* very slightly pessimistic but still catches all common cases */
3747                 FLAC__uint32 abs_residual_partition_sum;
3748
3749                 end = (unsigned)(-(int)predictor_order);
3750                 for(partition = residual_sample = 0; partition < partitions; partition++) {
3751                         end += default_partition_samples;
3752                         abs_residual_partition_sum = 0;
3753                         for( ; residual_sample < end; residual_sample++)
3754                                 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3755                         abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3756                 }
3757         }
3758         else { /* have to pessimistically use 64 bits for accumulator */
3759                 FLAC__uint64 abs_residual_partition_sum;
3760
3761                 end = (unsigned)(-(int)predictor_order);
3762                 for(partition = residual_sample = 0; partition < partitions; partition++) {
3763                         end += default_partition_samples;
3764                         abs_residual_partition_sum = 0;
3765                         for( ; residual_sample < end; residual_sample++)
3766                                 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3767                         abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3768                 }
3769         }
3770
3771         /* now merge partitions for lower orders */
3772         for(from_partition = 0, to_partition = partitions, partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
3773                 unsigned i;
3774                 const unsigned partitions = 1u << partition_order;
3775                 for(i = 0; i < partitions; i++) {
3776                         abs_residual_partition_sums[to_partition++] =
3777                                 abs_residual_partition_sums[from_partition  ] +
3778                                 abs_residual_partition_sums[from_partition+1];
3779                         from_partition += 2;
3780                 }
3781         }
3782 }
3783
3784 void precompute_partition_info_escapes_(
3785         const FLAC__int32 residual[],
3786         unsigned raw_bits_per_partition[],
3787         unsigned residual_samples,
3788         unsigned predictor_order,
3789         unsigned min_partition_order,
3790         unsigned max_partition_order
3791 )
3792 {
3793         int partition_order;
3794         unsigned from_partition, to_partition = 0;
3795         const unsigned blocksize = residual_samples + predictor_order;
3796
3797         /* first do max_partition_order */
3798         for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3799                 FLAC__int32 r;
3800                 FLAC__uint32 rmax;
3801                 unsigned partition, partition_sample, partition_samples, residual_sample;
3802                 const unsigned partitions = 1u << partition_order;
3803                 const unsigned default_partition_samples = blocksize >> partition_order;
3804
3805                 FLAC__ASSERT(default_partition_samples > predictor_order);
3806
3807                 for(partition = residual_sample = 0; partition < partitions; partition++) {
3808                         partition_samples = default_partition_samples;
3809                         if(partition == 0)
3810                                 partition_samples -= predictor_order;
3811                         rmax = 0;
3812                         for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
3813                                 r = residual[residual_sample++];
3814                                 /* OPT: maybe faster: rmax |= r ^ (r>>31) */
3815                                 if(r < 0)
3816                                         rmax |= ~r;
3817                                 else
3818                                         rmax |= r;
3819                         }
3820                         /* now we know all residual values are in the range [-rmax-1,rmax] */
3821                         raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
3822                 }
3823                 to_partition = partitions;
3824                 break; /*@@@ yuck, should remove the 'for' loop instead */
3825         }
3826
3827         /* now merge partitions for lower orders */
3828         for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
3829                 unsigned m;
3830                 unsigned i;
3831                 const unsigned partitions = 1u << partition_order;
3832                 for(i = 0; i < partitions; i++) {
3833                         m = raw_bits_per_partition[from_partition];
3834                         from_partition++;
3835                         raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
3836                         from_partition++;
3837                         to_partition++;
3838                 }
3839         }
3840 }
3841
3842 #ifdef EXACT_RICE_BITS_CALCULATION
3843 static FLaC__INLINE unsigned count_rice_bits_in_partition_(
3844         const unsigned rice_parameter,
3845         const unsigned partition_samples,
3846         const FLAC__int32 *residual
3847 )
3848 {
3849         unsigned i, partition_bits =
3850                 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN +
3851                 (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
3852         ;
3853         for(i = 0; i < partition_samples; i++)
3854                 partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
3855         return partition_bits;
3856 }
3857 #else
3858 static FLaC__INLINE unsigned count_rice_bits_in_partition_(
3859         const unsigned rice_parameter,
3860         const unsigned partition_samples,
3861         const FLAC__uint64 abs_residual_partition_sum
3862 )
3863 {
3864         return
3865                 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN +
3866                 (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
3867                 (
3868                         rice_parameter?
3869                                 (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
3870                                 : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
3871                 )
3872                 - (partition_samples >> 1)
3873                 /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
3874                  * The actual number of bits used is closer to the sum(for all i in the partition) of  abs(residual[i])>>(rice_parameter-1)
3875                  * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
3876                  * So the subtraction term tries to guess how many extra bits were contributed.
3877                  * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
3878                  */
3879         ;
3880 }
3881 #endif
3882
3883 FLAC__bool set_partitioned_rice_(
3884 #ifdef EXACT_RICE_BITS_CALCULATION
3885         const FLAC__int32 residual[],
3886 #endif
3887         const FLAC__uint64 abs_residual_partition_sums[],
3888         const unsigned raw_bits_per_partition[],
3889         const unsigned residual_samples,
3890         const unsigned predictor_order,
3891         const unsigned suggested_rice_parameter,
3892         const unsigned rice_parameter_search_dist,
3893         const unsigned partition_order,
3894         const FLAC__bool search_for_escapes,
3895         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3896         unsigned *bits
3897 )
3898 {
3899         unsigned rice_parameter, partition_bits;
3900         unsigned best_partition_bits, best_rice_parameter = 0;
3901         unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
3902         unsigned *parameters, *raw_bits;
3903 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3904         unsigned min_rice_parameter, max_rice_parameter;
3905 #else
3906         (void)rice_parameter_search_dist;
3907 #endif
3908
3909         FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
3910
3911         FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
3912         parameters = partitioned_rice_contents->parameters;
3913         raw_bits = partitioned_rice_contents->raw_bits;
3914
3915         if(partition_order == 0) {
3916                 best_partition_bits = 0xffffffff;
3917 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3918                 if(rice_parameter_search_dist) {
3919                         if(suggested_rice_parameter < rice_parameter_search_dist)
3920                                 min_rice_parameter = 0;
3921                         else
3922                                 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
3923                         max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
3924                         if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3925 #ifdef DEBUG_VERBOSE
3926                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3927 #endif
3928                                 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3929                         }
3930                 }
3931                 else
3932                         min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
3933
3934                 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3935 #else
3936                         rice_parameter = suggested_rice_parameter;
3937 #endif
3938 #ifdef EXACT_RICE_BITS_CALCULATION
3939                         partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
3940 #else
3941                         partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
3942 #endif
3943                         if(partition_bits < best_partition_bits) {
3944                                 best_rice_parameter = rice_parameter;
3945                                 best_partition_bits = partition_bits;
3946                         }
3947 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3948                 }
3949 #endif
3950                 if(search_for_escapes) {
3951                         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;
3952                         if(partition_bits <= best_partition_bits) {
3953                                 raw_bits[0] = raw_bits_per_partition[0];
3954                                 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
3955                                 best_partition_bits = partition_bits;
3956                         }
3957                 }
3958                 parameters[0] = best_rice_parameter;
3959                 bits_ += best_partition_bits;
3960         }
3961         else {
3962                 unsigned partition, residual_sample;
3963                 unsigned partition_samples;
3964                 FLAC__uint64 mean, k;
3965                 const unsigned partitions = 1u << partition_order;
3966                 for(partition = residual_sample = 0; partition < partitions; partition++) {
3967                         partition_samples = (residual_samples+predictor_order) >> partition_order;
3968                         if(partition == 0) {
3969                                 if(partition_samples <= predictor_order)
3970                                         return false;
3971                                 else
3972                                         partition_samples -= predictor_order;
3973                         }
3974                         mean = abs_residual_partition_sums[partition];
3975                         /* we are basically calculating the size in bits of the
3976                          * average residual magnitude in the partition:
3977                          *   rice_parameter = floor(log2(mean/partition_samples))
3978                          * 'mean' is not a good name for the variable, it is
3979                          * actually the sum of magnitudes of all residual values
3980                          * in the partition, so the actual mean is
3981                          * mean/partition_samples
3982                          */
3983                         for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
3984                                 ;
3985                         if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3986 #ifdef DEBUG_VERBOSE
3987                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3988 #endif
3989                                 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3990                         }
3991
3992                         best_partition_bits = 0xffffffff;
3993 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3994                         if(rice_parameter_search_dist) {
3995                                 if(rice_parameter < rice_parameter_search_dist)
3996                                         min_rice_parameter = 0;
3997                                 else
3998                                         min_rice_parameter = rice_parameter - rice_parameter_search_dist;
3999                                 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
4000                                 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
4001 #ifdef DEBUG_VERBOSE
4002                                         fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
4003 #endif
4004                                         max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
4005                                 }
4006                         }
4007                         else
4008                                 min_rice_parameter = max_rice_parameter = rice_parameter;
4009
4010                         for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4011 #endif
4012 #ifdef EXACT_RICE_BITS_CALCULATION
4013                                 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
4014 #else
4015                                 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
4016 #endif
4017                                 if(partition_bits < best_partition_bits) {
4018                                         best_rice_parameter = rice_parameter;
4019                                         best_partition_bits = partition_bits;
4020                                 }
4021 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4022                         }
4023 #endif
4024                         if(search_for_escapes) {
4025                                 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;
4026                                 if(partition_bits <= best_partition_bits) {
4027                                         raw_bits[partition] = raw_bits_per_partition[partition];
4028                                         best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
4029                                         best_partition_bits = partition_bits;
4030                                 }
4031                         }
4032                         parameters[partition] = best_rice_parameter;
4033                         bits_ += best_partition_bits;
4034                         residual_sample += partition_samples;
4035                 }
4036         }
4037
4038         *bits = bits_;
4039         return true;
4040 }
4041
4042 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
4043 {
4044         unsigned i, shift;
4045         FLAC__int32 x = 0;
4046
4047         for(i = 0; i < samples && !(x&1); i++)
4048                 x |= signal[i];
4049
4050         if(x == 0) {
4051                 shift = 0;
4052         }
4053         else {
4054                 for(shift = 0; !(x&1); shift++)
4055                         x >>= 1;
4056         }
4057
4058         if(shift > 0) {
4059                 for(i = 0; i < samples; i++)
4060                          signal[i] >>= shift;
4061         }
4062
4063         return shift;
4064 }
4065
4066 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4067 {
4068         unsigned channel;
4069
4070         for(channel = 0; channel < channels; channel++)
4071                 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
4072
4073         fifo->tail += wide_samples;
4074
4075         FLAC__ASSERT(fifo->tail <= fifo->size);
4076 }
4077
4078 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4079 {
4080         unsigned channel;
4081         unsigned sample, wide_sample;
4082         unsigned tail = fifo->tail;
4083
4084         sample = input_offset * channels;
4085         for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
4086                 for(channel = 0; channel < channels; channel++)
4087                         fifo->data[channel][tail] = input[sample++];
4088                 tail++;
4089         }
4090         fifo->tail = tail;
4091
4092         FLAC__ASSERT(fifo->tail <= fifo->size);
4093 }
4094
4095 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4096 {
4097         FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4098         const size_t encoded_bytes = encoder->private_->verify.output.bytes;
4099         (void)decoder;
4100
4101         if(encoder->private_->verify.needs_magic_hack) {
4102                 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
4103                 *bytes = FLAC__STREAM_SYNC_LENGTH;
4104                 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
4105                 encoder->private_->verify.needs_magic_hack = false;
4106         }
4107         else {
4108                 if(encoded_bytes == 0) {
4109                         /*
4110                          * If we get here, a FIFO underflow has occurred,
4111                          * which means there is a bug somewhere.
4112                          */
4113                         FLAC__ASSERT(0);
4114                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
4115                 }
4116                 else if(encoded_bytes < *bytes)
4117                         *bytes = encoded_bytes;
4118                 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
4119                 encoder->private_->verify.output.data += *bytes;
4120                 encoder->private_->verify.output.bytes -= *bytes;
4121         }
4122
4123         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
4124 }
4125
4126 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
4127 {
4128         FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
4129         unsigned channel;
4130         const unsigned channels = frame->header.channels;
4131         const unsigned blocksize = frame->header.blocksize;
4132         const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
4133
4134         (void)decoder;
4135
4136         for(channel = 0; channel < channels; channel++) {
4137                 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
4138                         unsigned i, sample = 0;
4139                         FLAC__int32 expect = 0, got = 0;
4140
4141                         for(i = 0; i < blocksize; i++) {
4142                                 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
4143                                         sample = i;
4144                                         expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
4145                                         got = (FLAC__int32)buffer[channel][i];
4146                                         break;
4147                                 }
4148                         }
4149                         FLAC__ASSERT(i < blocksize);
4150                         FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
4151                         encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
4152                         encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
4153                         encoder->private_->verify.error_stats.channel = channel;
4154                         encoder->private_->verify.error_stats.sample = sample;
4155                         encoder->private_->verify.error_stats.expected = expect;
4156                         encoder->private_->verify.error_stats.got = got;
4157                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
4158                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
4159                 }
4160         }
4161         /* dequeue the frame from the fifo */
4162         encoder->private_->verify.input_fifo.tail -= blocksize;
4163         FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
4164         for(channel = 0; channel < channels; channel++)
4165                 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]));
4166         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4167 }
4168
4169 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4170 {
4171         (void)decoder, (void)metadata, (void)client_data;
4172 }
4173
4174 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4175 {
4176         FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4177         (void)decoder, (void)status;
4178         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4179 }
4180
4181 FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4182 {
4183         (void)client_data;
4184
4185         *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
4186         if (*bytes == 0) {
4187                 if (feof(encoder->private_->file))
4188                         return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
4189                 else if (ferror(encoder->private_->file))
4190                         return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
4191         }
4192         return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
4193 }
4194
4195 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4196 {
4197         (void)client_data;
4198
4199         if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
4200                 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4201         else
4202                 return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4203 }
4204
4205 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4206 {
4207         off_t offset;
4208
4209         (void)client_data;
4210
4211         offset = ftello(encoder->private_->file);
4212
4213         if(offset < 0) {
4214                 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4215         }
4216         else {
4217                 *absolute_byte_offset = (FLAC__uint64)offset;
4218                 return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4219         }
4220 }
4221
4222 #ifdef FLAC__VALGRIND_TESTING
4223 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4224 {
4225         size_t ret = fwrite(ptr, size, nmemb, stream);
4226         if(!ferror(stream))
4227                 fflush(stream);
4228         return ret;
4229 }
4230 #else
4231 #define local__fwrite fwrite
4232 #endif
4233
4234 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
4235 {
4236         (void)client_data, (void)current_frame;
4237
4238         if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4239                 FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
4240 #if FLAC__HAS_OGG
4241                         /* We would like to be able to use 'samples > 0' in the
4242                          * clause here but currently because of the nature of our
4243                          * Ogg writing implementation, 'samples' is always 0 (see
4244                          * ogg_encoder_aspect.c).  The downside is extra progress
4245                          * callbacks.
4246                          */
4247                         encoder->private_->is_ogg? true :
4248 #endif
4249                         samples > 0
4250                 );
4251                 if(call_it) {
4252                         /* NOTE: We have to add +bytes, +samples, and +1 to the stats
4253                          * because at this point in the callback chain, the stats
4254                          * have not been updated.  Only after we return and control
4255                          * gets back to write_frame_() are the stats updated
4256                          */
4257                         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);
4258                 }
4259                 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4260         }
4261         else
4262                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4263 }
4264
4265 /*
4266  * This will forcibly set stdout to binary mode (for OSes that require it)
4267  */
4268 FILE *get_binary_stdout_(void)
4269 {
4270         /* if something breaks here it is probably due to the presence or
4271          * absence of an underscore before the identifiers 'setmode',
4272          * 'fileno', and/or 'O_BINARY'; check your system header files.
4273          */
4274 #if defined _MSC_VER || defined __MINGW32__
4275         _setmode(_fileno(stdout), _O_BINARY);
4276 #elif defined __CYGWIN__
4277         /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4278         setmode(_fileno(stdout), _O_BINARY);
4279 #elif defined __EMX__
4280         setmode(fileno(stdout), O_BINARY);
4281 #endif
4282
4283         return stdout;
4284 }