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