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