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