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