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