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