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