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