a7e1191066ec8e76e29d7c0a23cb2da57f3f767e
[flac.git] / src / libFLAC / stream_encoder.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000-2009  Josh Coalson
3  * Copyright (C) 2011-2014  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 #include "share/compat.h"
43 #include "FLAC/assert.h"
44 #include "FLAC/stream_decoder.h"
45 #include "protected/stream_encoder.h"
46 #include "private/bitwriter.h"
47 #include "private/bitmath.h"
48 #include "private/crc.h"
49 #include "private/cpu.h"
50 #include "private/fixed.h"
51 #include "private/format.h"
52 #include "private/lpc.h"
53 #include "private/md5.h"
54 #include "private/memory.h"
55 #include "private/macros.h"
56 #if FLAC__HAS_OGG
57 #include "private/ogg_helper.h"
58 #include "private/ogg_mapping.h"
59 #endif
60 #include "private/stream_encoder.h"
61 #include "private/stream_encoder_framing.h"
62 #include "private/window.h"
63 #include "share/alloc.h"
64 #include "share/private.h"
65
66
67 /* Exact Rice codeword length calculation is off by default.  The simple
68  * (and fast) estimation (of how many bits a residual value will be
69  * encoded with) in this encoder is very good, almost always yielding
70  * compression within 0.1% of exact calculation.
71  */
72 #undef EXACT_RICE_BITS_CALCULATION
73 /* Rice parameter searching is off by default.  The simple (and fast)
74  * parameter estimation in this encoder is very good, almost always
75  * yielding compression within 0.1% of the optimal parameters.
76  */
77 #undef ENABLE_RICE_PARAMETER_SEARCH
78
79
80 typedef struct {
81         FLAC__int32 *data[FLAC__MAX_CHANNELS];
82         unsigned size; /* of each data[] in samples */
83         unsigned tail;
84 } verify_input_fifo;
85
86 typedef struct {
87         const FLAC__byte *data;
88         unsigned capacity;
89         unsigned bytes;
90 } verify_output;
91
92 typedef enum {
93         ENCODER_IN_MAGIC = 0,
94         ENCODER_IN_METADATA = 1,
95         ENCODER_IN_AUDIO = 2
96 } EncoderStateHint;
97
98 static struct CompressionLevels {
99         FLAC__bool do_mid_side_stereo;
100         FLAC__bool loose_mid_side_stereo;
101         unsigned max_lpc_order;
102         unsigned qlp_coeff_precision;
103         FLAC__bool do_qlp_coeff_prec_search;
104         FLAC__bool do_escape_coding;
105         FLAC__bool do_exhaustive_model_search;
106         unsigned min_residual_partition_order;
107         unsigned max_residual_partition_order;
108         unsigned rice_parameter_search_dist;
109         const char *apodization;
110 } compression_levels_[] = {
111         { false, false,  0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
112         { true , true ,  0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
113         { true , false,  0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
114         { false, false,  6, 0, false, false, false, 0, 4, 0, "tukey(5e-1)" },
115         { true , true ,  8, 0, false, false, false, 0, 4, 0, "tukey(5e-1)" },
116         { true , false,  8, 0, false, false, false, 0, 5, 0, "tukey(5e-1)" },
117         { true , false,  8, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2)" },
118         { true , false, 12, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2)" },
119         { true , false, 12, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2);punchout_tukey(3)" }
120         /* here we use locale-independent 5e-1 instead of 0.5 or 0,5 */
121 };
122
123
124 /***********************************************************************
125  *
126  * Private class method prototypes
127  *
128  ***********************************************************************/
129
130 static void set_defaults_(FLAC__StreamEncoder *encoder);
131 static void free_(FLAC__StreamEncoder *encoder);
132 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
133 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
134 static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
135 static void update_metadata_(const FLAC__StreamEncoder *encoder);
136 #if FLAC__HAS_OGG
137 static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
138 #endif
139 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
140 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
141
142 static FLAC__bool process_subframe_(
143         FLAC__StreamEncoder *encoder,
144         unsigned min_partition_order,
145         unsigned max_partition_order,
146         const FLAC__FrameHeader *frame_header,
147         unsigned subframe_bps,
148         const FLAC__int32 integer_signal[],
149         FLAC__Subframe *subframe[2],
150         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
151         FLAC__int32 *residual[2],
152         unsigned *best_subframe,
153         unsigned *best_bits
154 );
155
156 static FLAC__bool add_subframe_(
157         FLAC__StreamEncoder *encoder,
158         unsigned blocksize,
159         unsigned subframe_bps,
160         const FLAC__Subframe *subframe,
161         FLAC__BitWriter *frame
162 );
163
164 static unsigned evaluate_constant_subframe_(
165         FLAC__StreamEncoder *encoder,
166         const FLAC__int32 signal,
167         unsigned blocksize,
168         unsigned subframe_bps,
169         FLAC__Subframe *subframe
170 );
171
172 static unsigned evaluate_fixed_subframe_(
173         FLAC__StreamEncoder *encoder,
174         const FLAC__int32 signal[],
175         FLAC__int32 residual[],
176         FLAC__uint64 abs_residual_partition_sums[],
177         unsigned raw_bits_per_partition[],
178         unsigned blocksize,
179         unsigned subframe_bps,
180         unsigned order,
181         unsigned rice_parameter,
182         unsigned rice_parameter_limit,
183         unsigned min_partition_order,
184         unsigned max_partition_order,
185         FLAC__bool do_escape_coding,
186         unsigned rice_parameter_search_dist,
187         FLAC__Subframe *subframe,
188         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
189 );
190
191 #ifndef FLAC__INTEGER_ONLY_LIBRARY
192 static unsigned evaluate_lpc_subframe_(
193         FLAC__StreamEncoder *encoder,
194         const FLAC__int32 signal[],
195         FLAC__int32 residual[],
196         FLAC__uint64 abs_residual_partition_sums[],
197         unsigned raw_bits_per_partition[],
198         const FLAC__real lp_coeff[],
199         unsigned blocksize,
200         unsigned subframe_bps,
201         unsigned order,
202         unsigned qlp_coeff_precision,
203         unsigned rice_parameter,
204         unsigned rice_parameter_limit,
205         unsigned min_partition_order,
206         unsigned max_partition_order,
207         FLAC__bool do_escape_coding,
208         unsigned rice_parameter_search_dist,
209         FLAC__Subframe *subframe,
210         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
211 );
212 #endif
213
214 static unsigned evaluate_verbatim_subframe_(
215         FLAC__StreamEncoder *encoder,
216         const FLAC__int32 signal[],
217         unsigned blocksize,
218         unsigned subframe_bps,
219         FLAC__Subframe *subframe
220 );
221
222 static unsigned find_best_partition_order_(
223         struct FLAC__StreamEncoderPrivate *private_,
224         const FLAC__int32 residual[],
225         FLAC__uint64 abs_residual_partition_sums[],
226         unsigned raw_bits_per_partition[],
227         unsigned residual_samples,
228         unsigned predictor_order,
229         unsigned rice_parameter,
230         unsigned rice_parameter_limit,
231         unsigned min_partition_order,
232         unsigned max_partition_order,
233         unsigned bps,
234         FLAC__bool do_escape_coding,
235         unsigned rice_parameter_search_dist,
236         FLAC__EntropyCodingMethod *best_ecm
237 );
238
239 static void precompute_partition_info_sums_(
240         const FLAC__int32 residual[],
241         FLAC__uint64 abs_residual_partition_sums[],
242         unsigned residual_samples,
243         unsigned predictor_order,
244         unsigned min_partition_order,
245         unsigned max_partition_order,
246         unsigned bps
247 );
248
249 static void precompute_partition_info_escapes_(
250         const FLAC__int32 residual[],
251         unsigned raw_bits_per_partition[],
252         unsigned residual_samples,
253         unsigned predictor_order,
254         unsigned min_partition_order,
255         unsigned max_partition_order
256 );
257
258 static FLAC__bool set_partitioned_rice_(
259 #ifdef EXACT_RICE_BITS_CALCULATION
260         const FLAC__int32 residual[],
261 #endif
262         const FLAC__uint64 abs_residual_partition_sums[],
263         const unsigned raw_bits_per_partition[],
264         const unsigned residual_samples,
265         const unsigned predictor_order,
266         const unsigned suggested_rice_parameter,
267         const unsigned rice_parameter_limit,
268         const unsigned rice_parameter_search_dist,
269         const unsigned partition_order,
270         const FLAC__bool search_for_escapes,
271         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
272         unsigned *bits
273 );
274
275 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
276
277 /* verify-related routines: */
278 static void append_to_verify_fifo_(
279         verify_input_fifo *fifo,
280         const FLAC__int32 * const input[],
281         unsigned input_offset,
282         unsigned channels,
283         unsigned wide_samples
284 );
285
286 static void append_to_verify_fifo_interleaved_(
287         verify_input_fifo *fifo,
288         const FLAC__int32 input[],
289         unsigned input_offset,
290         unsigned channels,
291         unsigned wide_samples
292 );
293
294 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
295 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
296 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
297 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
298
299 static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
300 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
301 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
302 static FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
303 static FILE *get_binary_stdout_(void);
304
305
306 /***********************************************************************
307  *
308  * Private class data
309  *
310  ***********************************************************************/
311
312 typedef struct FLAC__StreamEncoderPrivate {
313         unsigned input_capacity;                          /* current size (in samples) of the signal and residual buffers */
314         FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS];  /* the integer version of the input signal */
315         FLAC__int32 *integer_signal_mid_side[2];          /* the integer version of the mid-side input signal (stereo only) */
316 #ifndef FLAC__INTEGER_ONLY_LIBRARY
317         FLAC__real *real_signal[FLAC__MAX_CHANNELS];      /* (@@@ currently unused) the floating-point version of the input signal */
318         FLAC__real *real_signal_mid_side[2];              /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
319         FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
320         FLAC__real *windowed_signal;                      /* the integer_signal[] * current window[] */
321 #endif
322         unsigned subframe_bps[FLAC__MAX_CHANNELS];        /* the effective bits per sample of the input signal (stream bps - wasted bits) */
323         unsigned subframe_bps_mid_side[2];                /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
324         FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
325         FLAC__int32 *residual_workspace_mid_side[2][2];
326         FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
327         FLAC__Subframe subframe_workspace_mid_side[2][2];
328         FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
329         FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
330         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
331         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
332         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
333         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
334         unsigned best_subframe[FLAC__MAX_CHANNELS];       /* index (0 or 1) into 2nd dimension of the above workspaces */
335         unsigned best_subframe_mid_side[2];
336         unsigned best_subframe_bits[FLAC__MAX_CHANNELS];  /* size in bits of the best subframe for each channel */
337         unsigned best_subframe_bits_mid_side[2];
338         FLAC__uint64 *abs_residual_partition_sums;        /* workspace where the sum of abs(candidate residual) for each partition is stored */
339         unsigned *raw_bits_per_partition;                 /* workspace where the sum of silog2(candidate residual) for each partition is stored */
340         FLAC__BitWriter *frame;                           /* the current frame being worked on */
341         unsigned loose_mid_side_stereo_frames;            /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
342         unsigned loose_mid_side_stereo_frame_count;       /* number of frames using the current channel assignment */
343         FLAC__ChannelAssignment last_channel_assignment;
344         FLAC__StreamMetadata streaminfo;                  /* scratchpad for STREAMINFO as it is built */
345         FLAC__StreamMetadata_SeekTable *seek_table;       /* pointer into encoder->protected_->metadata_ where the seek table is */
346         unsigned current_sample_number;
347         unsigned current_frame_number;
348         FLAC__MD5Context md5context;
349         FLAC__CPUInfo cpuinfo;
350         void (*local_precompute_partition_info_sums)(const FLAC__int32 residual[], FLAC__uint64 abs_residual_partition_sums[], unsigned residual_samples, unsigned predictor_order, unsigned min_partition_order, unsigned max_partition_order, unsigned bps);
351 #ifndef FLAC__INTEGER_ONLY_LIBRARY
352         unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
353         unsigned (*local_fixed_compute_best_predictor_wide)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
354 #else
355         unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
356         unsigned (*local_fixed_compute_best_predictor_wide)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
357 #endif
358 #ifndef FLAC__INTEGER_ONLY_LIBRARY
359         void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
360         void (*local_lpc_compute_residual_from_qlp_coefficients)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
361         void (*local_lpc_compute_residual_from_qlp_coefficients_64bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
362         void (*local_lpc_compute_residual_from_qlp_coefficients_16bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
363 #endif
364         FLAC__bool use_wide_by_block;          /* use slow 64-bit versions of some functions because of the block size */
365         FLAC__bool use_wide_by_partition;      /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
366         FLAC__bool use_wide_by_order;          /* use slow 64-bit versions of some functions because of the lpc order */
367         FLAC__bool disable_constant_subframes;
368         FLAC__bool disable_fixed_subframes;
369         FLAC__bool disable_verbatim_subframes;
370 #if FLAC__HAS_OGG
371         FLAC__bool is_ogg;
372 #endif
373         FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
374         FLAC__StreamEncoderSeekCallback seek_callback;
375         FLAC__StreamEncoderTellCallback tell_callback;
376         FLAC__StreamEncoderWriteCallback write_callback;
377         FLAC__StreamEncoderMetadataCallback metadata_callback;
378         FLAC__StreamEncoderProgressCallback progress_callback;
379         void *client_data;
380         unsigned first_seekpoint_to_check;
381         FILE *file;                            /* only used when encoding to a file */
382         FLAC__uint64 bytes_written;
383         FLAC__uint64 samples_written;
384         unsigned frames_written;
385         unsigned total_frames_estimate;
386         /* unaligned (original) pointers to allocated data */
387         FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
388         FLAC__int32 *integer_signal_mid_side_unaligned[2];
389 #ifndef FLAC__INTEGER_ONLY_LIBRARY
390         FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
391         FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
392         FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
393         FLAC__real *windowed_signal_unaligned;
394 #endif
395         FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
396         FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
397         FLAC__uint64 *abs_residual_partition_sums_unaligned;
398         unsigned *raw_bits_per_partition_unaligned;
399         /*
400          * These fields have been moved here from private function local
401          * declarations merely to save stack space during encoding.
402          */
403 #ifndef FLAC__INTEGER_ONLY_LIBRARY
404         FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
405 #endif
406         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
407         /*
408          * The data for the verify section
409          */
410         struct {
411                 FLAC__StreamDecoder *decoder;
412                 EncoderStateHint state_hint;
413                 FLAC__bool needs_magic_hack;
414                 verify_input_fifo input_fifo;
415                 verify_output output;
416                 struct {
417                         FLAC__uint64 absolute_sample;
418                         unsigned frame_number;
419                         unsigned channel;
420                         unsigned sample;
421                         FLAC__int32 expected;
422                         FLAC__int32 got;
423                 } error_stats;
424         } verify;
425         FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
426 } FLAC__StreamEncoderPrivate;
427
428 /***********************************************************************
429  *
430  * Public static class data
431  *
432  ***********************************************************************/
433
434 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
435         "FLAC__STREAM_ENCODER_OK",
436         "FLAC__STREAM_ENCODER_UNINITIALIZED",
437         "FLAC__STREAM_ENCODER_OGG_ERROR",
438         "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
439         "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
440         "FLAC__STREAM_ENCODER_CLIENT_ERROR",
441         "FLAC__STREAM_ENCODER_IO_ERROR",
442         "FLAC__STREAM_ENCODER_FRAMING_ERROR",
443         "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
444 };
445
446 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
447         "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
448         "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
449         "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
450         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
451         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
452         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
453         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
454         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
455         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
456         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
457         "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
458         "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
459         "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
460         "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
461 };
462
463 FLAC_API const char * const FLAC__StreamEncoderReadStatusString[] = {
464         "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
465         "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
466         "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
467         "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
468 };
469
470 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
471         "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
472         "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
473 };
474
475 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
476         "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
477         "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
478         "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
479 };
480
481 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
482         "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
483         "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
484         "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
485 };
486
487 /* Number of samples that will be overread to watch for end of stream.  By
488  * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
489  * always try to read blocksize+1 samples before encoding a block, so that
490  * even if the stream has a total sample count that is an integral multiple
491  * of the blocksize, we will still notice when we are encoding the last
492  * block.  This is needed, for example, to correctly set the end-of-stream
493  * marker in Ogg FLAC.
494  *
495  * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
496  * not really any reason to change it.
497  */
498 static const unsigned OVERREAD_ = 1;
499
500 /***********************************************************************
501  *
502  * Class constructor/destructor
503  *
504  */
505 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
506 {
507         FLAC__StreamEncoder *encoder;
508         unsigned i;
509
510         FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
511
512         encoder = calloc(1, sizeof(FLAC__StreamEncoder));
513         if(encoder == 0) {
514                 return 0;
515         }
516
517         encoder->protected_ = calloc(1, sizeof(FLAC__StreamEncoderProtected));
518         if(encoder->protected_ == 0) {
519                 free(encoder);
520                 return 0;
521         }
522
523         encoder->private_ = calloc(1, sizeof(FLAC__StreamEncoderPrivate));
524         if(encoder->private_ == 0) {
525                 free(encoder->protected_);
526                 free(encoder);
527                 return 0;
528         }
529
530         encoder->private_->frame = FLAC__bitwriter_new();
531         if(encoder->private_->frame == 0) {
532                 free(encoder->private_);
533                 free(encoder->protected_);
534                 free(encoder);
535                 return 0;
536         }
537
538         encoder->private_->file = 0;
539
540         set_defaults_(encoder);
541
542         encoder->private_->is_being_deleted = false;
543
544         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
545                 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
546                 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
547         }
548         for(i = 0; i < 2; i++) {
549                 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
550                 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
551         }
552         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
553                 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
554                 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
555         }
556         for(i = 0; i < 2; i++) {
557                 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
558                 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
559         }
560
561         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
562                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
563                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
564         }
565         for(i = 0; i < 2; i++) {
566                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
567                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
568         }
569         for(i = 0; i < 2; i++)
570                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
571
572         encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
573
574         return encoder;
575 }
576
577 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
578 {
579         unsigned i;
580
581         if (encoder == NULL)
582                 return ;
583
584         FLAC__ASSERT(0 != encoder->protected_);
585         FLAC__ASSERT(0 != encoder->private_);
586         FLAC__ASSERT(0 != encoder->private_->frame);
587
588         encoder->private_->is_being_deleted = true;
589
590         (void)FLAC__stream_encoder_finish(encoder);
591
592         if(0 != encoder->private_->verify.decoder)
593                 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
594
595         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
596                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
597                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
598         }
599         for(i = 0; i < 2; i++) {
600                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
601                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
602         }
603         for(i = 0; i < 2; i++)
604                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
605
606         FLAC__bitwriter_delete(encoder->private_->frame);
607         free(encoder->private_);
608         free(encoder->protected_);
609         free(encoder);
610 }
611
612 /***********************************************************************
613  *
614  * Public class methods
615  *
616  ***********************************************************************/
617
618 static FLAC__StreamEncoderInitStatus init_stream_internal_(
619         FLAC__StreamEncoder *encoder,
620         FLAC__StreamEncoderReadCallback read_callback,
621         FLAC__StreamEncoderWriteCallback write_callback,
622         FLAC__StreamEncoderSeekCallback seek_callback,
623         FLAC__StreamEncoderTellCallback tell_callback,
624         FLAC__StreamEncoderMetadataCallback metadata_callback,
625         void *client_data,
626         FLAC__bool is_ogg
627 )
628 {
629         unsigned i;
630         FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
631
632         FLAC__ASSERT(0 != encoder);
633
634         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
635                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
636
637 #if !FLAC__HAS_OGG
638         if(is_ogg)
639                 return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
640 #endif
641
642         if(0 == write_callback || (seek_callback && 0 == tell_callback))
643                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
644
645         if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
646                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
647
648         if(encoder->protected_->channels != 2) {
649                 encoder->protected_->do_mid_side_stereo = false;
650                 encoder->protected_->loose_mid_side_stereo = false;
651         }
652         else if(!encoder->protected_->do_mid_side_stereo)
653                 encoder->protected_->loose_mid_side_stereo = false;
654
655         if(encoder->protected_->bits_per_sample >= 32)
656                 encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
657
658         if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
659                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
660
661         if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
662                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
663
664         if(encoder->protected_->blocksize == 0) {
665                 if(encoder->protected_->max_lpc_order == 0)
666                         encoder->protected_->blocksize = 1152;
667                 else
668                         encoder->protected_->blocksize = 4096;
669         }
670
671         if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
672                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
673
674         if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
675                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
676
677         if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
678                 return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
679
680         if(encoder->protected_->qlp_coeff_precision == 0) {
681                 if(encoder->protected_->bits_per_sample < 16) {
682                         /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
683                         /* @@@ until then we'll make a guess */
684                         encoder->protected_->qlp_coeff_precision = flac_max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
685                 }
686                 else if(encoder->protected_->bits_per_sample == 16) {
687                         if(encoder->protected_->blocksize <= 192)
688                                 encoder->protected_->qlp_coeff_precision = 7;
689                         else if(encoder->protected_->blocksize <= 384)
690                                 encoder->protected_->qlp_coeff_precision = 8;
691                         else if(encoder->protected_->blocksize <= 576)
692                                 encoder->protected_->qlp_coeff_precision = 9;
693                         else if(encoder->protected_->blocksize <= 1152)
694                                 encoder->protected_->qlp_coeff_precision = 10;
695                         else if(encoder->protected_->blocksize <= 2304)
696                                 encoder->protected_->qlp_coeff_precision = 11;
697                         else if(encoder->protected_->blocksize <= 4608)
698                                 encoder->protected_->qlp_coeff_precision = 12;
699                         else
700                                 encoder->protected_->qlp_coeff_precision = 13;
701                 }
702                 else {
703                         if(encoder->protected_->blocksize <= 384)
704                                 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
705                         else if(encoder->protected_->blocksize <= 1152)
706                                 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
707                         else
708                                 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
709                 }
710                 FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
711         }
712         else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
713                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
714
715         if(encoder->protected_->streamable_subset) {
716                 if(!FLAC__format_blocksize_is_subset(encoder->protected_->blocksize, encoder->protected_->sample_rate))
717                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
718                 if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
719                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
720                 if(
721                         encoder->protected_->bits_per_sample != 8 &&
722                         encoder->protected_->bits_per_sample != 12 &&
723                         encoder->protected_->bits_per_sample != 16 &&
724                         encoder->protected_->bits_per_sample != 20 &&
725                         encoder->protected_->bits_per_sample != 24
726                 )
727                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
728                 if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
729                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
730                 if(
731                         encoder->protected_->sample_rate <= 48000 &&
732                         (
733                                 encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
734                                 encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
735                         )
736                 ) {
737                         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
738                 }
739         }
740
741         if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
742                 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
743         if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
744                 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
745
746 #if FLAC__HAS_OGG
747         /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
748         if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
749                 unsigned i1;
750                 for(i1 = 1; i1 < encoder->protected_->num_metadata_blocks; i1++) {
751                         if(0 != encoder->protected_->metadata[i1] && encoder->protected_->metadata[i1]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
752                                 FLAC__StreamMetadata *vc = encoder->protected_->metadata[i1];
753                                 for( ; i1 > 0; i1--)
754                                         encoder->protected_->metadata[i1] = encoder->protected_->metadata[i1-1];
755                                 encoder->protected_->metadata[0] = vc;
756                                 break;
757                         }
758                 }
759         }
760 #endif
761         /* keep track of any SEEKTABLE block */
762         if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
763                 unsigned i2;
764                 for(i2 = 0; i2 < encoder->protected_->num_metadata_blocks; i2++) {
765                         if(0 != encoder->protected_->metadata[i2] && encoder->protected_->metadata[i2]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
766                                 encoder->private_->seek_table = &encoder->protected_->metadata[i2]->data.seek_table;
767                                 break; /* take only the first one */
768                         }
769                 }
770         }
771
772         /* validate metadata */
773         if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
774                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
775         metadata_has_seektable = false;
776         metadata_has_vorbis_comment = false;
777         metadata_picture_has_type1 = false;
778         metadata_picture_has_type2 = false;
779         for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
780                 const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
781                 if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
782                         return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
783                 else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
784                         if(metadata_has_seektable) /* only one is allowed */
785                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
786                         metadata_has_seektable = true;
787                         if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
788                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
789                 }
790                 else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
791                         if(metadata_has_vorbis_comment) /* only one is allowed */
792                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
793                         metadata_has_vorbis_comment = true;
794                 }
795                 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
796                         if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
797                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
798                 }
799                 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
800                         if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
801                                 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
802                         if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
803                                 if(metadata_picture_has_type1) /* there should only be 1 per stream */
804                                         return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
805                                 metadata_picture_has_type1 = true;
806                                 /* standard icon must be 32x32 pixel PNG */
807                                 if(
808                                         m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
809                                         (
810                                                 (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
811                                                 m->data.picture.width != 32 ||
812                                                 m->data.picture.height != 32
813                                         )
814                                 )
815                                         return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
816                         }
817                         else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
818                                 if(metadata_picture_has_type2) /* there should only be 1 per stream */
819                                         return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
820                                 metadata_picture_has_type2 = true;
821                         }
822                 }
823         }
824
825         encoder->private_->input_capacity = 0;
826         for(i = 0; i < encoder->protected_->channels; i++) {
827                 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
828 #ifndef FLAC__INTEGER_ONLY_LIBRARY
829                 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
830 #endif
831         }
832         for(i = 0; i < 2; i++) {
833                 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
834 #ifndef FLAC__INTEGER_ONLY_LIBRARY
835                 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
836 #endif
837         }
838 #ifndef FLAC__INTEGER_ONLY_LIBRARY
839         for(i = 0; i < encoder->protected_->num_apodizations; i++)
840                 encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
841         encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
842 #endif
843         for(i = 0; i < encoder->protected_->channels; i++) {
844                 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
845                 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
846                 encoder->private_->best_subframe[i] = 0;
847         }
848         for(i = 0; i < 2; i++) {
849                 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
850                 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
851                 encoder->private_->best_subframe_mid_side[i] = 0;
852         }
853         encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
854         encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
855 #ifndef FLAC__INTEGER_ONLY_LIBRARY
856         encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
857 #else
858         /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
859         /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
860         FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
861         FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
862         FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
863         FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
864         encoder->private_->loose_mid_side_stereo_frames = (unsigned)FLAC__fixedpoint_trunc((((FLAC__uint64)(encoder->protected_->sample_rate) * (FLAC__uint64)(26214)) << 16) / (encoder->protected_->blocksize<<16) + FLAC__FP_ONE_HALF);
865 #endif
866         if(encoder->private_->loose_mid_side_stereo_frames == 0)
867                 encoder->private_->loose_mid_side_stereo_frames = 1;
868         encoder->private_->loose_mid_side_stereo_frame_count = 0;
869         encoder->private_->current_sample_number = 0;
870         encoder->private_->current_frame_number = 0;
871
872         encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
873         encoder->private_->use_wide_by_order = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(flac_max(encoder->protected_->max_lpc_order, FLAC__MAX_FIXED_ORDER))+1 > 30); /*@@@ need to use this? */
874         encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
875
876         /*
877          * get the CPU info and set the function pointers
878          */
879         FLAC__cpu_info(&encoder->private_->cpuinfo);
880         /* first default to the non-asm routines */
881 #ifndef FLAC__INTEGER_ONLY_LIBRARY
882         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
883 #endif
884         encoder->private_->local_precompute_partition_info_sums = precompute_partition_info_sums_;
885         encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
886         encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide;
887 #ifndef FLAC__INTEGER_ONLY_LIBRARY
888         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
889         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
890         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
891 #endif
892         /* now override with asm where appropriate */
893 #ifndef FLAC__INTEGER_ONLY_LIBRARY
894 # ifndef FLAC__NO_ASM
895         if(encoder->private_->cpuinfo.use_asm) {
896 #  ifdef FLAC__CPU_IA32
897                 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
898 #   ifdef FLAC__HAS_NASM
899                 if(encoder->private_->cpuinfo.ia32.sse) {
900                         if(encoder->protected_->max_lpc_order < 4)
901                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4_old;
902                         else if(encoder->protected_->max_lpc_order < 8)
903                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8_old;
904                         else if(encoder->protected_->max_lpc_order < 12)
905                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12_old;
906                         else if(encoder->protected_->max_lpc_order < 16)
907                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_16_old;
908                         else
909                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
910                 }
911                 else
912                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
913
914                 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 */
915                 if(encoder->private_->cpuinfo.ia32.mmx) {
916                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
917                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
918                 }
919                 else {
920                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
921                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
922                 }
923
924                 if(encoder->private_->cpuinfo.ia32.mmx && encoder->private_->cpuinfo.ia32.cmov)
925                         encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
926 #   endif /* FLAC__HAS_NASM */
927 #   ifdef FLAC__HAS_X86INTRIN
928 #    if defined FLAC__SSE_SUPPORTED
929                 if(encoder->private_->cpuinfo.ia32.sse) {
930                         if(encoder->private_->cpuinfo.ia32.sse42 || !encoder->private_->cpuinfo.ia32.intel) { /* use new autocorrelation functions */
931                                 if(encoder->protected_->max_lpc_order < 4)
932                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_new;
933                                 else if(encoder->protected_->max_lpc_order < 8)
934                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_new;
935                                 else if(encoder->protected_->max_lpc_order < 12)
936                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_new;
937                                 else if(encoder->protected_->max_lpc_order < 16)
938                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_new;
939                                 else
940                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
941                         }
942                         else { /* use old autocorrelation functions */
943                                 if(encoder->protected_->max_lpc_order < 4)
944                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_old;
945                                 else if(encoder->protected_->max_lpc_order < 8)
946                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_old;
947                                 else if(encoder->protected_->max_lpc_order < 12)
948                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_old;
949                                 else if(encoder->protected_->max_lpc_order < 16)
950                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_old;
951                                 else
952                                         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
953                         }
954                 }
955 #    endif
956
957 #    ifdef FLAC__SSE2_SUPPORTED
958                 if(encoder->private_->cpuinfo.ia32.sse2) {
959                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients       = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse2;
960                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_sse2;
961                 }
962 #    endif
963 #    ifdef FLAC__SSE4_1_SUPPORTED
964                 if(encoder->private_->cpuinfo.ia32.sse41) {
965                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients       = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse41;
966                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_sse41;
967                 }
968 #    endif
969 #    ifdef FLAC__AVX2_SUPPORTED
970                 if(encoder->private_->cpuinfo.ia32.avx2) {
971                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_avx2;
972                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients       = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_avx2;
973                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_avx2;
974                 }
975 #    endif
976
977 #    ifdef FLAC__SSE2_SUPPORTED
978                 if (encoder->private_->cpuinfo.ia32.sse2) {
979                         encoder->private_->local_fixed_compute_best_predictor      = FLAC__fixed_compute_best_predictor_intrin_sse2;
980                         encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_sse2;
981                 }
982 #    endif
983 #    ifdef FLAC__SSSE3_SUPPORTED
984                 if (encoder->private_->cpuinfo.ia32.ssse3) {
985                         encoder->private_->local_fixed_compute_best_predictor      = FLAC__fixed_compute_best_predictor_intrin_ssse3;
986                         encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_ssse3;
987                 }
988 #    endif
989 #   endif /* FLAC__HAS_X86INTRIN */
990 #  elif defined FLAC__CPU_X86_64
991                 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_X86_64);
992 #   ifdef FLAC__HAS_X86INTRIN
993 #    ifdef FLAC__SSE_SUPPORTED
994                 if(encoder->private_->cpuinfo.x86.sse42 || !encoder->private_->cpuinfo.x86.intel) { /* use new autocorrelation functions */
995                         if(encoder->protected_->max_lpc_order < 4)
996                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_new;
997                         else if(encoder->protected_->max_lpc_order < 8)
998                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_new;
999                         else if(encoder->protected_->max_lpc_order < 12)
1000                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_new;
1001                         else if(encoder->protected_->max_lpc_order < 16)
1002                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_new;
1003                 }
1004                 else {
1005                         if(encoder->protected_->max_lpc_order < 4)
1006                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_old;
1007                         else if(encoder->protected_->max_lpc_order < 8)
1008                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_old;
1009                         else if(encoder->protected_->max_lpc_order < 12)
1010                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_old;
1011                         else if(encoder->protected_->max_lpc_order < 16)
1012                                 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_old;
1013                 }
1014 #    endif
1015
1016 #    ifdef FLAC__SSE2_SUPPORTED
1017                 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_sse2;
1018 #    endif
1019 #    ifdef FLAC__SSE4_1_SUPPORTED
1020                 if(encoder->private_->cpuinfo.x86.sse41) {
1021                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse41;
1022                 }
1023 #    endif
1024 #    ifdef FLAC__AVX2_SUPPORTED
1025                 if(encoder->private_->cpuinfo.x86.avx2) {
1026                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_avx2;
1027                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients       = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_avx2;
1028                         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_avx2;
1029                 }
1030 #    endif
1031
1032 #    ifdef FLAC__SSE2_SUPPORTED
1033                 encoder->private_->local_fixed_compute_best_predictor      = FLAC__fixed_compute_best_predictor_intrin_sse2;
1034                 encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_sse2;
1035 #    endif
1036 #    ifdef FLAC__SSSE3_SUPPORTED
1037                 if (encoder->private_->cpuinfo.x86.ssse3) {
1038                         encoder->private_->local_fixed_compute_best_predictor      = FLAC__fixed_compute_best_predictor_intrin_ssse3;
1039                         encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_ssse3;
1040                 }
1041 #    endif
1042 #   endif /* FLAC__HAS_X86INTRIN */
1043 #  endif /* FLAC__CPU_... */
1044         }
1045 # endif /* !FLAC__NO_ASM */
1046 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
1047 #if !defined FLAC__NO_ASM && defined FLAC__HAS_X86INTRIN
1048         if(encoder->private_->cpuinfo.use_asm) {
1049 # if defined FLAC__CPU_IA32
1050 #  ifdef FLAC__SSE2_SUPPORTED
1051                 if(encoder->private_->cpuinfo.ia32.sse2)
1052                         encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_sse2;
1053 #  endif
1054 #  ifdef FLAC__SSSE3_SUPPORTED
1055                 if(encoder->private_->cpuinfo.ia32.ssse3)
1056                         encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_ssse3;
1057 #  endif
1058 #  ifdef FLAC__AVX2_SUPPORTED
1059                 if(encoder->private_->cpuinfo.ia32.avx2)
1060                         encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_avx2;
1061 #  endif
1062 # elif defined FLAC__CPU_X86_64
1063 #  ifdef FLAC__SSE2_SUPPORTED
1064                 encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_sse2;
1065 #  endif
1066 #  ifdef FLAC__SSSE3_SUPPORTED
1067                 if(encoder->private_->cpuinfo.x86.ssse3)
1068                         encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_ssse3;
1069 #  endif
1070 #  ifdef FLAC__AVX2_SUPPORTED
1071                 if(encoder->private_->cpuinfo.x86.avx2)
1072                         encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_avx2;
1073 #  endif
1074 # endif /* FLAC__CPU_... */
1075         }
1076 #endif /* !FLAC__NO_ASM && FLAC__HAS_X86INTRIN */
1077         /* finally override based on wide-ness if necessary */
1078         if(encoder->private_->use_wide_by_block) {
1079                 encoder->private_->local_fixed_compute_best_predictor = encoder->private_->local_fixed_compute_best_predictor_wide;
1080         }
1081
1082         /* set state to OK; from here on, errors are fatal and we'll override the state then */
1083         encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
1084
1085 #if FLAC__HAS_OGG
1086         encoder->private_->is_ogg = is_ogg;
1087         if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
1088                 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
1089                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1090         }
1091 #endif
1092
1093         encoder->private_->read_callback = read_callback;
1094         encoder->private_->write_callback = write_callback;
1095         encoder->private_->seek_callback = seek_callback;
1096         encoder->private_->tell_callback = tell_callback;
1097         encoder->private_->metadata_callback = metadata_callback;
1098         encoder->private_->client_data = client_data;
1099
1100         if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
1101                 /* the above function sets the state for us in case of an error */
1102                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1103         }
1104
1105         if(!FLAC__bitwriter_init(encoder->private_->frame)) {
1106                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1107                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1108         }
1109
1110         /*
1111          * Set up the verify stuff if necessary
1112          */
1113         if(encoder->protected_->verify) {
1114                 /*
1115                  * First, set up the fifo which will hold the
1116                  * original signal to compare against
1117                  */
1118                 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
1119                 for(i = 0; i < encoder->protected_->channels; i++) {
1120                         if(0 == (encoder->private_->verify.input_fifo.data[i] = safe_malloc_mul_2op_p(sizeof(FLAC__int32), /*times*/encoder->private_->verify.input_fifo.size))) {
1121                                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1122                                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1123                         }
1124                 }
1125                 encoder->private_->verify.input_fifo.tail = 0;
1126
1127                 /*
1128                  * Now set up a stream decoder for verification
1129                  */
1130                 if(0 == encoder->private_->verify.decoder) {
1131                         encoder->private_->verify.decoder = FLAC__stream_decoder_new();
1132                         if(0 == encoder->private_->verify.decoder) {
1133                                 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1134                                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1135                         }
1136                 }
1137
1138                 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) {
1139                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1140                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1141                 }
1142         }
1143         encoder->private_->verify.error_stats.absolute_sample = 0;
1144         encoder->private_->verify.error_stats.frame_number = 0;
1145         encoder->private_->verify.error_stats.channel = 0;
1146         encoder->private_->verify.error_stats.sample = 0;
1147         encoder->private_->verify.error_stats.expected = 0;
1148         encoder->private_->verify.error_stats.got = 0;
1149
1150         /*
1151          * These must be done before we write any metadata, because that
1152          * calls the write_callback, which uses these values.
1153          */
1154         encoder->private_->first_seekpoint_to_check = 0;
1155         encoder->private_->samples_written = 0;
1156         encoder->protected_->streaminfo_offset = 0;
1157         encoder->protected_->seektable_offset = 0;
1158         encoder->protected_->audio_offset = 0;
1159
1160         /*
1161          * write the stream header
1162          */
1163         if(encoder->protected_->verify)
1164                 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1165         if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1166                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1167                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1168         }
1169         if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1170                 /* the above function sets the state for us in case of an error */
1171                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1172         }
1173
1174         /*
1175          * write the STREAMINFO metadata block
1176          */
1177         if(encoder->protected_->verify)
1178                 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1179         encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1180         encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1181         encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1182         encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1183         encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1184         encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1185         encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1186         encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1187         encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1188         encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1189         encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1190         memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1191         if(encoder->protected_->do_md5)
1192                 FLAC__MD5Init(&encoder->private_->md5context);
1193         if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1194                 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1195                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1196         }
1197         if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1198                 /* the above function sets the state for us in case of an error */
1199                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1200         }
1201
1202         /*
1203          * Now that the STREAMINFO block is written, we can init this to an
1204          * absurdly-high value...
1205          */
1206         encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1207         /* ... and clear this to 0 */
1208         encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1209
1210         /*
1211          * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1212          * if not, we will write an empty one (FLAC__add_metadata_block()
1213          * automatically supplies the vendor string).
1214          *
1215          * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1216          * the STREAMINFO.  (In the case that metadata_has_vorbis_comment is
1217          * true it will have already insured that the metadata list is properly
1218          * ordered.)
1219          */
1220         if(!metadata_has_vorbis_comment) {
1221                 FLAC__StreamMetadata vorbis_comment;
1222                 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1223                 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1224                 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1225                 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1226                 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1227                 vorbis_comment.data.vorbis_comment.num_comments = 0;
1228                 vorbis_comment.data.vorbis_comment.comments = 0;
1229                 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1230                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1231                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1232                 }
1233                 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1234                         /* the above function sets the state for us in case of an error */
1235                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1236                 }
1237         }
1238
1239         /*
1240          * write the user's metadata blocks
1241          */
1242         for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1243                 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1244                 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1245                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1246                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1247                 }
1248                 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1249                         /* the above function sets the state for us in case of an error */
1250                         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1251                 }
1252         }
1253
1254         /* now that all the metadata is written, we save the stream offset */
1255         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 */
1256                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1257                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1258         }
1259
1260         if(encoder->protected_->verify)
1261                 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1262
1263         return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1264 }
1265
1266 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1267         FLAC__StreamEncoder *encoder,
1268         FLAC__StreamEncoderWriteCallback write_callback,
1269         FLAC__StreamEncoderSeekCallback seek_callback,
1270         FLAC__StreamEncoderTellCallback tell_callback,
1271         FLAC__StreamEncoderMetadataCallback metadata_callback,
1272         void *client_data
1273 )
1274 {
1275         return init_stream_internal_(
1276                 encoder,
1277                 /*read_callback=*/0,
1278                 write_callback,
1279                 seek_callback,
1280                 tell_callback,
1281                 metadata_callback,
1282                 client_data,
1283                 /*is_ogg=*/false
1284         );
1285 }
1286
1287 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1288         FLAC__StreamEncoder *encoder,
1289         FLAC__StreamEncoderReadCallback read_callback,
1290         FLAC__StreamEncoderWriteCallback write_callback,
1291         FLAC__StreamEncoderSeekCallback seek_callback,
1292         FLAC__StreamEncoderTellCallback tell_callback,
1293         FLAC__StreamEncoderMetadataCallback metadata_callback,
1294         void *client_data
1295 )
1296 {
1297         return init_stream_internal_(
1298                 encoder,
1299                 read_callback,
1300                 write_callback,
1301                 seek_callback,
1302                 tell_callback,
1303                 metadata_callback,
1304                 client_data,
1305                 /*is_ogg=*/true
1306         );
1307 }
1308
1309 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1310         FLAC__StreamEncoder *encoder,
1311         FILE *file,
1312         FLAC__StreamEncoderProgressCallback progress_callback,
1313         void *client_data,
1314         FLAC__bool is_ogg
1315 )
1316 {
1317         FLAC__StreamEncoderInitStatus init_status;
1318
1319         FLAC__ASSERT(0 != encoder);
1320         FLAC__ASSERT(0 != file);
1321
1322         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1323                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1324
1325         /* double protection */
1326         if(file == 0) {
1327                 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1328                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1329         }
1330
1331         /*
1332          * To make sure that our file does not go unclosed after an error, we
1333          * must assign the FILE pointer before any further error can occur in
1334          * this routine.
1335          */
1336         if(file == stdout)
1337                 file = get_binary_stdout_(); /* just to be safe */
1338
1339 #ifdef _WIN32
1340         /*
1341          * Windows can suffer quite badly from disk fragmentation. This can be
1342          * reduced significantly by setting the output buffer size to be 10MB.
1343          */
1344         setvbuf(file, NULL, _IOFBF, 10*1024*1024);
1345 #endif
1346         encoder->private_->file = file;
1347
1348         encoder->private_->progress_callback = progress_callback;
1349         encoder->private_->bytes_written = 0;
1350         encoder->private_->samples_written = 0;
1351         encoder->private_->frames_written = 0;
1352
1353         init_status = init_stream_internal_(
1354                 encoder,
1355                 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1356                 file_write_callback_,
1357                 encoder->private_->file == stdout? 0 : file_seek_callback_,
1358                 encoder->private_->file == stdout? 0 : file_tell_callback_,
1359                 /*metadata_callback=*/0,
1360                 client_data,
1361                 is_ogg
1362         );
1363         if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1364                 /* the above function sets the state for us in case of an error */
1365                 return init_status;
1366         }
1367
1368         {
1369                 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1370
1371                 FLAC__ASSERT(blocksize != 0);
1372                 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1373         }
1374
1375         return init_status;
1376 }
1377
1378 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1379         FLAC__StreamEncoder *encoder,
1380         FILE *file,
1381         FLAC__StreamEncoderProgressCallback progress_callback,
1382         void *client_data
1383 )
1384 {
1385         return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1386 }
1387
1388 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1389         FLAC__StreamEncoder *encoder,
1390         FILE *file,
1391         FLAC__StreamEncoderProgressCallback progress_callback,
1392         void *client_data
1393 )
1394 {
1395         return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1396 }
1397
1398 static FLAC__StreamEncoderInitStatus init_file_internal_(
1399         FLAC__StreamEncoder *encoder,
1400         const char *filename,
1401         FLAC__StreamEncoderProgressCallback progress_callback,
1402         void *client_data,
1403         FLAC__bool is_ogg
1404 )
1405 {
1406         FILE *file;
1407
1408         FLAC__ASSERT(0 != encoder);
1409
1410         /*
1411          * To make sure that our file does not go unclosed after an error, we
1412          * have to do the same entrance checks here that are later performed
1413          * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1414          */
1415         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1416                 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1417
1418         file = filename? flac_fopen(filename, "w+b") : stdout;
1419
1420         if(file == 0) {
1421                 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1422                 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1423         }
1424
1425         return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1426 }
1427
1428 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1429         FLAC__StreamEncoder *encoder,
1430         const char *filename,
1431         FLAC__StreamEncoderProgressCallback progress_callback,
1432         void *client_data
1433 )
1434 {
1435         return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1436 }
1437
1438 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1439         FLAC__StreamEncoder *encoder,
1440         const char *filename,
1441         FLAC__StreamEncoderProgressCallback progress_callback,
1442         void *client_data
1443 )
1444 {
1445         return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1446 }
1447
1448 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1449 {
1450         FLAC__bool error = false;
1451
1452         FLAC__ASSERT(0 != encoder);
1453         FLAC__ASSERT(0 != encoder->private_);
1454         FLAC__ASSERT(0 != encoder->protected_);
1455
1456         if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1457                 return true;
1458
1459         if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1460                 if(encoder->private_->current_sample_number != 0) {
1461                         const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1462                         encoder->protected_->blocksize = encoder->private_->current_sample_number;
1463                         if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1464                                 error = true;
1465                 }
1466         }
1467
1468         if(encoder->protected_->do_md5)
1469                 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1470
1471         if(!encoder->private_->is_being_deleted) {
1472                 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1473                         if(encoder->private_->seek_callback) {
1474 #if FLAC__HAS_OGG
1475                                 if(encoder->private_->is_ogg)
1476                                         update_ogg_metadata_(encoder);
1477                                 else
1478 #endif
1479                                 update_metadata_(encoder);
1480
1481                                 /* check if an error occurred while updating metadata */
1482                                 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1483                                         error = true;
1484                         }
1485                         if(encoder->private_->metadata_callback)
1486                                 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1487                 }
1488
1489                 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1490                         if(!error)
1491                                 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1492                         error = true;
1493                 }
1494         }
1495
1496         if(0 != encoder->private_->file) {
1497                 if(encoder->private_->file != stdout)
1498                         fclose(encoder->private_->file);
1499                 encoder->private_->file = 0;
1500         }
1501
1502 #if FLAC__HAS_OGG
1503         if(encoder->private_->is_ogg)
1504                 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1505 #endif
1506
1507         free_(encoder);
1508         set_defaults_(encoder);
1509
1510         if(!error)
1511                 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1512
1513         return !error;
1514 }
1515
1516 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1517 {
1518         FLAC__ASSERT(0 != encoder);
1519         FLAC__ASSERT(0 != encoder->private_);
1520         FLAC__ASSERT(0 != encoder->protected_);
1521         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1522                 return false;
1523 #if FLAC__HAS_OGG
1524         /* can't check encoder->private_->is_ogg since that's not set until init time */
1525         FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1526         return true;
1527 #else
1528         (void)value;
1529         return false;
1530 #endif
1531 }
1532
1533 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1534 {
1535         FLAC__ASSERT(0 != encoder);
1536         FLAC__ASSERT(0 != encoder->private_);
1537         FLAC__ASSERT(0 != encoder->protected_);
1538         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1539                 return false;
1540 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1541         encoder->protected_->verify = value;
1542 #endif
1543         return true;
1544 }
1545
1546 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1547 {
1548         FLAC__ASSERT(0 != encoder);
1549         FLAC__ASSERT(0 != encoder->private_);
1550         FLAC__ASSERT(0 != encoder->protected_);
1551         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1552                 return false;
1553         encoder->protected_->streamable_subset = value;
1554         return true;
1555 }
1556
1557 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
1558 {
1559         FLAC__ASSERT(0 != encoder);
1560         FLAC__ASSERT(0 != encoder->private_);
1561         FLAC__ASSERT(0 != encoder->protected_);
1562         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1563                 return false;
1564         encoder->protected_->do_md5 = value;
1565         return true;
1566 }
1567
1568 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned 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_->channels = value;
1576         return true;
1577 }
1578
1579 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned 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_->bits_per_sample = value;
1587         return true;
1588 }
1589
1590 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned 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_->sample_rate = value;
1598         return true;
1599 }
1600
1601 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1602 {
1603         FLAC__bool ok = true;
1604         FLAC__ASSERT(0 != encoder);
1605         FLAC__ASSERT(0 != encoder->private_);
1606         FLAC__ASSERT(0 != encoder->protected_);
1607         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1608                 return false;
1609         if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1610                 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1611         ok &= FLAC__stream_encoder_set_do_mid_side_stereo          (encoder, compression_levels_[value].do_mid_side_stereo);
1612         ok &= FLAC__stream_encoder_set_loose_mid_side_stereo       (encoder, compression_levels_[value].loose_mid_side_stereo);
1613 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1614 #if 1
1615         ok &= FLAC__stream_encoder_set_apodization                 (encoder, compression_levels_[value].apodization);
1616 #else
1617         /* equivalent to -A tukey(0.5) */
1618         encoder->protected_->num_apodizations = 1;
1619         encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1620         encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1621 #endif
1622 #endif
1623         ok &= FLAC__stream_encoder_set_max_lpc_order               (encoder, compression_levels_[value].max_lpc_order);
1624         ok &= FLAC__stream_encoder_set_qlp_coeff_precision         (encoder, compression_levels_[value].qlp_coeff_precision);
1625         ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search    (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1626         ok &= FLAC__stream_encoder_set_do_escape_coding            (encoder, compression_levels_[value].do_escape_coding);
1627         ok &= FLAC__stream_encoder_set_do_exhaustive_model_search  (encoder, compression_levels_[value].do_exhaustive_model_search);
1628         ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1629         ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1630         ok &= FLAC__stream_encoder_set_rice_parameter_search_dist  (encoder, compression_levels_[value].rice_parameter_search_dist);
1631         return ok;
1632 }
1633
1634 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1635 {
1636         FLAC__ASSERT(0 != encoder);
1637         FLAC__ASSERT(0 != encoder->private_);
1638         FLAC__ASSERT(0 != encoder->protected_);
1639         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1640                 return false;
1641         encoder->protected_->blocksize = value;
1642         return true;
1643 }
1644
1645 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1646 {
1647         FLAC__ASSERT(0 != encoder);
1648         FLAC__ASSERT(0 != encoder->private_);
1649         FLAC__ASSERT(0 != encoder->protected_);
1650         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1651                 return false;
1652         encoder->protected_->do_mid_side_stereo = value;
1653         return true;
1654 }
1655
1656 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool 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_->loose_mid_side_stereo = value;
1664         return true;
1665 }
1666
1667 /*@@@@add to tests*/
1668 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1669 {
1670         FLAC__ASSERT(0 != encoder);
1671         FLAC__ASSERT(0 != encoder->private_);
1672         FLAC__ASSERT(0 != encoder->protected_);
1673         FLAC__ASSERT(0 != specification);
1674         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1675                 return false;
1676 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1677         (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1678 #else
1679         encoder->protected_->num_apodizations = 0;
1680         while(1) {
1681                 const char *s = strchr(specification, ';');
1682                 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1683                 if     (n==8  && 0 == strncmp("bartlett"     , specification, n))
1684                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1685                 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1686                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1687                 else if(n==8  && 0 == strncmp("blackman"     , specification, n))
1688                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1689                 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1690                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1691                 else if(n==6  && 0 == strncmp("connes"       , specification, n))
1692                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1693                 else if(n==7  && 0 == strncmp("flattop"      , specification, n))
1694                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1695                 else if(n>7   && 0 == strncmp("gauss("       , specification, 6)) {
1696                         FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1697                         if (stddev > 0.0 && stddev <= 0.5) {
1698                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1699                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1700                         }
1701                 }
1702                 else if(n==7  && 0 == strncmp("hamming"      , specification, n))
1703                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1704                 else if(n==4  && 0 == strncmp("hann"         , specification, n))
1705                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1706                 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1707                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1708                 else if(n==7  && 0 == strncmp("nuttall"      , specification, n))
1709                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1710                 else if(n==9  && 0 == strncmp("rectangle"    , specification, n))
1711                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1712                 else if(n==8  && 0 == strncmp("triangle"     , specification, n))
1713                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1714                 else if(n>7   && 0 == strncmp("tukey("       , specification, 6)) {
1715                         FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1716                         if (p >= 0.0 && p <= 1.0) {
1717                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1718                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1719                         }
1720                 }
1721                 else if(n>15   && 0 == strncmp("partial_tukey("       , specification, 14)) {
1722                         FLAC__int32 tukey_parts = (FLAC__int32)strtod(specification+14, 0);
1723                         const char *si_1 = strchr(specification, '/');
1724                         FLAC__real overlap = si_1?flac_min((FLAC__real)strtod(si_1+1, 0),0.99f):0.1f;
1725                         FLAC__real overlap_units = 1.0f/(1.0f - overlap) - 1.0f;
1726                         const char *si_2 = strchr((si_1?(si_1+1):specification), '/');
1727                         FLAC__real tukey_p = si_2?(FLAC__real)strtod(si_2+1, 0):0.2f;
1728
1729                         if (tukey_parts <= 1) {
1730                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = tukey_p;
1731                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1732                         }else if (encoder->protected_->num_apodizations + tukey_parts < 32){
1733                                 FLAC__int32 m;
1734                                 for(m = 0; m < tukey_parts; m++){
1735                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.p = tukey_p;
1736                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.start = m/(tukey_parts+overlap_units);
1737                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.end = (m+1+overlap_units)/(tukey_parts+overlap_units);
1738                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_PARTIAL_TUKEY;
1739                                 }
1740                         }
1741                 }
1742                 else if(n>16   && 0 == strncmp("punchout_tukey("       , specification, 15)) {
1743                         FLAC__int32 tukey_parts = (FLAC__int32)strtod(specification+15, 0);
1744                         const char *si_1 = strchr(specification, '/');
1745                         FLAC__real overlap = si_1?flac_min((FLAC__real)strtod(si_1+1, 0),0.99f):0.2f;
1746                         FLAC__real overlap_units = 1.0f/(1.0f - overlap) - 1.0f;
1747                         const char *si_2 = strchr((si_1?(si_1+1):specification), '/');
1748                         FLAC__real tukey_p = si_2?(FLAC__real)strtod(si_2+1, 0):0.2f;
1749
1750                         if (tukey_parts <= 1) {
1751                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = tukey_p;
1752                                 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1753                         }else if (encoder->protected_->num_apodizations + tukey_parts < 32){
1754                                 FLAC__int32 m;
1755                                 for(m = 0; m < tukey_parts; m++){
1756                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.p = tukey_p;
1757                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.start = m/(tukey_parts+overlap_units);
1758                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.end = (m+1+overlap_units)/(tukey_parts+overlap_units);
1759                                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_PUNCHOUT_TUKEY;
1760                                 }
1761                         }
1762                 }
1763                 else if(n==5  && 0 == strncmp("welch"        , specification, n))
1764                         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1765                 if (encoder->protected_->num_apodizations == 32)
1766                         break;
1767                 if (s)
1768                         specification = s+1;
1769                 else
1770                         break;
1771         }
1772         if(encoder->protected_->num_apodizations == 0) {
1773                 encoder->protected_->num_apodizations = 1;
1774                 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1775                 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1776         }
1777 #endif
1778         return true;
1779 }
1780
1781 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1782 {
1783         FLAC__ASSERT(0 != encoder);
1784         FLAC__ASSERT(0 != encoder->private_);
1785         FLAC__ASSERT(0 != encoder->protected_);
1786         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1787                 return false;
1788         encoder->protected_->max_lpc_order = value;
1789         return true;
1790 }
1791
1792 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1793 {
1794         FLAC__ASSERT(0 != encoder);
1795         FLAC__ASSERT(0 != encoder->private_);
1796         FLAC__ASSERT(0 != encoder->protected_);
1797         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1798                 return false;
1799         encoder->protected_->qlp_coeff_precision = value;
1800         return true;
1801 }
1802
1803 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool 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_->do_qlp_coeff_prec_search = value;
1811         return true;
1812 }
1813
1814 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool 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 #if 0
1822         /*@@@ deprecated: */
1823         encoder->protected_->do_escape_coding = value;
1824 #else
1825         (void)value;
1826 #endif
1827         return true;
1828 }
1829
1830 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1831 {
1832         FLAC__ASSERT(0 != encoder);
1833         FLAC__ASSERT(0 != encoder->private_);
1834         FLAC__ASSERT(0 != encoder->protected_);
1835         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1836                 return false;
1837         encoder->protected_->do_exhaustive_model_search = value;
1838         return true;
1839 }
1840
1841 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1842 {
1843         FLAC__ASSERT(0 != encoder);
1844         FLAC__ASSERT(0 != encoder->private_);
1845         FLAC__ASSERT(0 != encoder->protected_);
1846         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1847                 return false;
1848         encoder->protected_->min_residual_partition_order = value;
1849         return true;
1850 }
1851
1852 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned 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_->max_residual_partition_order = value;
1860         return true;
1861 }
1862
1863 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned 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 #if 0
1871         /*@@@ deprecated: */
1872         encoder->protected_->rice_parameter_search_dist = value;
1873 #else
1874         (void)value;
1875 #endif
1876         return true;
1877 }
1878
1879 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1880 {
1881         FLAC__ASSERT(0 != encoder);
1882         FLAC__ASSERT(0 != encoder->private_);
1883         FLAC__ASSERT(0 != encoder->protected_);
1884         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1885                 return false;
1886         encoder->protected_->total_samples_estimate = value;
1887         return true;
1888 }
1889
1890 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1891 {
1892         FLAC__ASSERT(0 != encoder);
1893         FLAC__ASSERT(0 != encoder->private_);
1894         FLAC__ASSERT(0 != encoder->protected_);
1895         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1896                 return false;
1897         if(0 == metadata)
1898                 num_blocks = 0;
1899         if(0 == num_blocks)
1900                 metadata = 0;
1901         /* realloc() does not do exactly what we want so... */
1902         if(encoder->protected_->metadata) {
1903                 free(encoder->protected_->metadata);
1904                 encoder->protected_->metadata = 0;
1905                 encoder->protected_->num_metadata_blocks = 0;
1906         }
1907         if(num_blocks) {
1908                 FLAC__StreamMetadata **m;
1909                 if(0 == (m = safe_malloc_mul_2op_p(sizeof(m[0]), /*times*/num_blocks)))
1910                         return false;
1911                 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1912                 encoder->protected_->metadata = m;
1913                 encoder->protected_->num_metadata_blocks = num_blocks;
1914         }
1915 #if FLAC__HAS_OGG
1916         if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1917                 return false;
1918 #endif
1919         return true;
1920 }
1921
1922 /*
1923  * These three functions are not static, but not publically exposed in
1924  * include/FLAC/ either.  They are used by the test suite.
1925  */
1926 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1927 {
1928         FLAC__ASSERT(0 != encoder);
1929         FLAC__ASSERT(0 != encoder->private_);
1930         FLAC__ASSERT(0 != encoder->protected_);
1931         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1932                 return false;
1933         encoder->private_->disable_constant_subframes = value;
1934         return true;
1935 }
1936
1937 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1938 {
1939         FLAC__ASSERT(0 != encoder);
1940         FLAC__ASSERT(0 != encoder->private_);
1941         FLAC__ASSERT(0 != encoder->protected_);
1942         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1943                 return false;
1944         encoder->private_->disable_fixed_subframes = value;
1945         return true;
1946 }
1947
1948 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1949 {
1950         FLAC__ASSERT(0 != encoder);
1951         FLAC__ASSERT(0 != encoder->private_);
1952         FLAC__ASSERT(0 != encoder->protected_);
1953         if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1954                 return false;
1955         encoder->private_->disable_verbatim_subframes = value;
1956         return true;
1957 }
1958
1959 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1960 {
1961         FLAC__ASSERT(0 != encoder);
1962         FLAC__ASSERT(0 != encoder->private_);
1963         FLAC__ASSERT(0 != encoder->protected_);
1964         return encoder->protected_->state;
1965 }
1966
1967 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1968 {
1969         FLAC__ASSERT(0 != encoder);
1970         FLAC__ASSERT(0 != encoder->private_);
1971         FLAC__ASSERT(0 != encoder->protected_);
1972         if(encoder->protected_->verify)
1973                 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1974         else
1975                 return FLAC__STREAM_DECODER_UNINITIALIZED;
1976 }
1977
1978 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1979 {
1980         FLAC__ASSERT(0 != encoder);
1981         FLAC__ASSERT(0 != encoder->private_);
1982         FLAC__ASSERT(0 != encoder->protected_);
1983         if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1984                 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1985         else
1986                 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1987 }
1988
1989 FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got)
1990 {
1991         FLAC__ASSERT(0 != encoder);
1992         FLAC__ASSERT(0 != encoder->private_);
1993         FLAC__ASSERT(0 != encoder->protected_);
1994         if(0 != absolute_sample)
1995                 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1996         if(0 != frame_number)
1997                 *frame_number = encoder->private_->verify.error_stats.frame_number;
1998         if(0 != channel)
1999                 *channel = encoder->private_->verify.error_stats.channel;
2000         if(0 != sample)
2001                 *sample = encoder->private_->verify.error_stats.sample;
2002         if(0 != expected)
2003                 *expected = encoder->private_->verify.error_stats.expected;
2004         if(0 != got)
2005                 *got = encoder->private_->verify.error_stats.got;
2006 }
2007
2008 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
2009 {
2010         FLAC__ASSERT(0 != encoder);
2011         FLAC__ASSERT(0 != encoder->private_);
2012         FLAC__ASSERT(0 != encoder->protected_);
2013         return encoder->protected_->verify;
2014 }
2015
2016 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
2017 {
2018         FLAC__ASSERT(0 != encoder);
2019         FLAC__ASSERT(0 != encoder->private_);
2020         FLAC__ASSERT(0 != encoder->protected_);
2021         return encoder->protected_->streamable_subset;
2022 }
2023
2024 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
2025 {
2026         FLAC__ASSERT(0 != encoder);
2027         FLAC__ASSERT(0 != encoder->private_);
2028         FLAC__ASSERT(0 != encoder->protected_);
2029         return encoder->protected_->do_md5;
2030 }
2031
2032 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
2033 {
2034         FLAC__ASSERT(0 != encoder);
2035         FLAC__ASSERT(0 != encoder->private_);
2036         FLAC__ASSERT(0 != encoder->protected_);
2037         return encoder->protected_->channels;
2038 }
2039
2040 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
2041 {
2042         FLAC__ASSERT(0 != encoder);
2043         FLAC__ASSERT(0 != encoder->private_);
2044         FLAC__ASSERT(0 != encoder->protected_);
2045         return encoder->protected_->bits_per_sample;
2046 }
2047
2048 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
2049 {
2050         FLAC__ASSERT(0 != encoder);
2051         FLAC__ASSERT(0 != encoder->private_);
2052         FLAC__ASSERT(0 != encoder->protected_);
2053         return encoder->protected_->sample_rate;
2054 }
2055
2056 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
2057 {
2058         FLAC__ASSERT(0 != encoder);
2059         FLAC__ASSERT(0 != encoder->private_);
2060         FLAC__ASSERT(0 != encoder->protected_);
2061         return encoder->protected_->blocksize;
2062 }
2063
2064 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
2065 {
2066         FLAC__ASSERT(0 != encoder);
2067         FLAC__ASSERT(0 != encoder->private_);
2068         FLAC__ASSERT(0 != encoder->protected_);
2069         return encoder->protected_->do_mid_side_stereo;
2070 }
2071
2072 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
2073 {
2074         FLAC__ASSERT(0 != encoder);
2075         FLAC__ASSERT(0 != encoder->private_);
2076         FLAC__ASSERT(0 != encoder->protected_);
2077         return encoder->protected_->loose_mid_side_stereo;
2078 }
2079
2080 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
2081 {
2082         FLAC__ASSERT(0 != encoder);
2083         FLAC__ASSERT(0 != encoder->private_);
2084         FLAC__ASSERT(0 != encoder->protected_);
2085         return encoder->protected_->max_lpc_order;
2086 }
2087
2088 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
2089 {
2090         FLAC__ASSERT(0 != encoder);
2091         FLAC__ASSERT(0 != encoder->private_);
2092         FLAC__ASSERT(0 != encoder->protected_);
2093         return encoder->protected_->qlp_coeff_precision;
2094 }
2095
2096 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
2097 {
2098         FLAC__ASSERT(0 != encoder);
2099         FLAC__ASSERT(0 != encoder->private_);
2100         FLAC__ASSERT(0 != encoder->protected_);
2101         return encoder->protected_->do_qlp_coeff_prec_search;
2102 }
2103
2104 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
2105 {
2106         FLAC__ASSERT(0 != encoder);
2107         FLAC__ASSERT(0 != encoder->private_);
2108         FLAC__ASSERT(0 != encoder->protected_);
2109         return encoder->protected_->do_escape_coding;
2110 }
2111
2112 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
2113 {
2114         FLAC__ASSERT(0 != encoder);
2115         FLAC__ASSERT(0 != encoder->private_);
2116         FLAC__ASSERT(0 != encoder->protected_);
2117         return encoder->protected_->do_exhaustive_model_search;
2118 }
2119
2120 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
2121 {
2122         FLAC__ASSERT(0 != encoder);
2123         FLAC__ASSERT(0 != encoder->private_);
2124         FLAC__ASSERT(0 != encoder->protected_);
2125         return encoder->protected_->min_residual_partition_order;
2126 }
2127
2128 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
2129 {
2130         FLAC__ASSERT(0 != encoder);
2131         FLAC__ASSERT(0 != encoder->private_);
2132         FLAC__ASSERT(0 != encoder->protected_);
2133         return encoder->protected_->max_residual_partition_order;
2134 }
2135
2136 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
2137 {
2138         FLAC__ASSERT(0 != encoder);
2139         FLAC__ASSERT(0 != encoder->private_);
2140         FLAC__ASSERT(0 != encoder->protected_);
2141         return encoder->protected_->rice_parameter_search_dist;
2142 }
2143
2144 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
2145 {
2146         FLAC__ASSERT(0 != encoder);
2147         FLAC__ASSERT(0 != encoder->private_);
2148         FLAC__ASSERT(0 != encoder->protected_);
2149         return encoder->protected_->total_samples_estimate;
2150 }
2151
2152 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
2153 {
2154         unsigned i, j = 0, channel;
2155         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2156
2157         FLAC__ASSERT(0 != encoder);
2158         FLAC__ASSERT(0 != encoder->private_);
2159         FLAC__ASSERT(0 != encoder->protected_);
2160         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2161
2162 //      FLAC__ASSERT(samples <= blocksize);
2163
2164         do {
2165                 const unsigned n = flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
2166
2167                 if(encoder->protected_->verify)
2168                         append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
2169
2170                 for(channel = 0; channel < channels; channel++) {
2171                         if (buffer[channel] == NULL) {
2172                                 encoder->protected_->state = FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2173                                 return false;
2174                         }
2175                         memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
2176                 }
2177
2178                 if(encoder->protected_->do_mid_side_stereo) {
2179                         FLAC__ASSERT(channels == 2);
2180                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2181                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2182                                 encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
2183                                 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' ! */
2184                         }
2185                 }
2186                 else
2187                         j += n;
2188
2189                 encoder->private_->current_sample_number += n;
2190
2191                 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2192                 if(encoder->private_->current_sample_number > blocksize) {
2193                         FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
2194                         FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2195                         if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2196                                 return false;
2197                         /* move unprocessed overread samples to beginnings of arrays */
2198                         for(channel = 0; channel < channels; channel++)
2199                                 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2200                         if(encoder->protected_->do_mid_side_stereo) {
2201                                 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2202                                 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2203                         }
2204                         encoder->private_->current_sample_number = 1;
2205                 }
2206         } while(j < samples);
2207
2208         return true;
2209 }
2210
2211 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2212 {
2213         unsigned i, j, k, channel;
2214         FLAC__int32 x, mid, side;
2215         const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2216
2217         FLAC__ASSERT(0 != encoder);
2218         FLAC__ASSERT(0 != encoder->private_);
2219         FLAC__ASSERT(0 != encoder->protected_);
2220         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2221
2222         j = k = 0;
2223         /*
2224          * we have several flavors of the same basic loop, optimized for
2225          * different conditions:
2226          */
2227         if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2228                 /*
2229                  * stereo coding: unroll channel loop
2230                  */
2231                 do {
2232                         if(encoder->protected_->verify)
2233                                 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2234
2235                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2236                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2237                                 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2238                                 x = buffer[k++];
2239                                 encoder->private_->integer_signal[1][i] = x;
2240                                 mid += x;
2241                                 side -= x;
2242                                 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2243                                 encoder->private_->integer_signal_mid_side[1][i] = side;
2244                                 encoder->private_->integer_signal_mid_side[0][i] = mid;
2245                         }
2246                         encoder->private_->current_sample_number = i;
2247                         /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2248                         if(i > blocksize) {
2249                                 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2250                                         return false;
2251                                 /* move unprocessed overread samples to beginnings of arrays */
2252                                 FLAC__ASSERT(i == blocksize+OVERREAD_);
2253                                 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2254                                 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
2255                                 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
2256                                 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2257                                 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2258                                 encoder->private_->current_sample_number = 1;
2259                         }
2260                 } while(j < samples);
2261         }
2262         else {
2263                 /*
2264                  * independent channel coding: buffer each channel in inner loop
2265                  */
2266                 do {
2267                         if(encoder->protected_->verify)
2268                                 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2269
2270                         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2271                         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2272                                 for(channel = 0; channel < channels; channel++)
2273                                         encoder->private_->integer_signal[channel][i] = buffer[k++];
2274                         }
2275                         encoder->private_->current_sample_number = i;
2276                         /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2277                         if(i > blocksize) {
2278                                 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2279                                         return false;
2280                                 /* move unprocessed overread samples to beginnings of arrays */
2281                                 FLAC__ASSERT(i == blocksize+OVERREAD_);
2282                                 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2283                                 for(channel = 0; channel < channels; channel++)
2284                                         encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2285                                 encoder->private_->current_sample_number = 1;
2286                         }
2287                 } while(j < samples);
2288         }
2289
2290         return true;
2291 }
2292
2293 /***********************************************************************
2294  *
2295  * Private class methods
2296  *
2297  ***********************************************************************/
2298
2299 void set_defaults_(FLAC__StreamEncoder *encoder)
2300 {
2301         FLAC__ASSERT(0 != encoder);
2302
2303 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2304         encoder->protected_->verify = true;
2305 #else
2306         encoder->protected_->verify = false;
2307 #endif
2308         encoder->protected_->streamable_subset = true;
2309         encoder->protected_->do_md5 = true;
2310         encoder->protected_->do_mid_side_stereo = false;
2311         encoder->protected_->loose_mid_side_stereo = false;
2312         encoder->protected_->channels = 2;
2313         encoder->protected_->bits_per_sample = 16;
2314         encoder->protected_->sample_rate = 44100;
2315         encoder->protected_->blocksize = 0;
2316 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2317         encoder->protected_->num_apodizations = 1;
2318         encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2319         encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2320 #endif
2321         encoder->protected_->max_lpc_order = 0;
2322         encoder->protected_->qlp_coeff_precision = 0;
2323         encoder->protected_->do_qlp_coeff_prec_search = false;
2324         encoder->protected_->do_exhaustive_model_search = false;
2325         encoder->protected_->do_escape_coding = false;
2326         encoder->protected_->min_residual_partition_order = 0;
2327         encoder->protected_->max_residual_partition_order = 0;
2328         encoder->protected_->rice_parameter_search_dist = 0;
2329         encoder->protected_->total_samples_estimate = 0;
2330         encoder->protected_->metadata = 0;
2331         encoder->protected_->num_metadata_blocks = 0;
2332
2333         encoder->private_->seek_table = 0;
2334         encoder->private_->disable_constant_subframes = false;
2335         encoder->private_->disable_fixed_subframes = false;
2336         encoder->private_->disable_verbatim_subframes = false;
2337 #if FLAC__HAS_OGG
2338         encoder->private_->is_ogg = false;
2339 #endif
2340         encoder->private_->read_callback = 0;
2341         encoder->private_->write_callback = 0;
2342         encoder->private_->seek_callback = 0;
2343         encoder->private_->tell_callback = 0;
2344         encoder->private_->metadata_callback = 0;
2345         encoder->private_->progress_callback = 0;
2346         encoder->private_->client_data = 0;
2347
2348 #if FLAC__HAS_OGG
2349         FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2350 #endif
2351
2352         FLAC__stream_encoder_set_compression_level(encoder, 5);
2353 }
2354
2355 void free_(FLAC__StreamEncoder *encoder)
2356 {
2357         unsigned i, channel;
2358
2359         FLAC__ASSERT(0 != encoder);
2360         if(encoder->protected_->metadata) {
2361                 free(encoder->protected_->metadata);
2362                 encoder->protected_->metadata = 0;
2363                 encoder->protected_->num_metadata_blocks = 0;
2364         }
2365         for(i = 0; i < encoder->protected_->channels; i++) {
2366                 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2367                         free(encoder->private_->integer_signal_unaligned[i]);
2368                         encoder->private_->integer_signal_unaligned[i] = 0;
2369                 }
2370 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2371                 if(0 != encoder->private_->real_signal_unaligned[i]) {
2372                         free(encoder->private_->real_signal_unaligned[i]);
2373                         encoder->private_->real_signal_unaligned[i] = 0;
2374                 }
2375 #endif
2376         }
2377         for(i = 0; i < 2; i++) {
2378                 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2379                         free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2380                         encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2381                 }
2382 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2383                 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2384                         free(encoder->private_->real_signal_mid_side_unaligned[i]);
2385                         encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2386                 }
2387 #endif
2388         }
2389 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2390         for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2391                 if(0 != encoder->private_->window_unaligned[i]) {
2392                         free(encoder->private_->window_unaligned[i]);
2393                         encoder->private_->window_unaligned[i] = 0;
2394                 }
2395         }
2396         if(0 != encoder->private_->windowed_signal_unaligned) {
2397                 free(encoder->private_->windowed_signal_unaligned);
2398                 encoder->private_->windowed_signal_unaligned = 0;
2399         }
2400 #endif
2401         for(channel = 0; channel < encoder->protected_->channels; channel++) {
2402                 for(i = 0; i < 2; i++) {
2403                         if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2404                                 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2405                                 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2406                         }
2407                 }
2408         }
2409         for(channel = 0; channel < 2; channel++) {
2410                 for(i = 0; i < 2; i++) {
2411                         if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2412                                 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2413                                 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2414                         }
2415                 }
2416         }
2417         if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2418                 free(encoder->private_->abs_residual_partition_sums_unaligned);
2419                 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2420         }
2421         if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2422                 free(encoder->private_->raw_bits_per_partition_unaligned);
2423                 encoder->private_->raw_bits_per_partition_unaligned = 0;
2424         }
2425         if(encoder->protected_->verify) {
2426                 for(i = 0; i < encoder->protected_->channels; i++) {
2427                         if(0 != encoder->private_->verify.input_fifo.data[i]) {
2428                                 free(encoder->private_->verify.input_fifo.data[i]);
2429                                 encoder->private_->verify.input_fifo.data[i] = 0;
2430                         }
2431                 }
2432         }
2433         FLAC__bitwriter_free(encoder->private_->frame);
2434 }
2435
2436 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2437 {
2438         FLAC__bool ok;
2439         unsigned i, channel;
2440
2441         FLAC__ASSERT(new_blocksize > 0);
2442         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2443         FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2444
2445         /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2446         if(new_blocksize <= encoder->private_->input_capacity)
2447                 return true;
2448
2449         ok = true;
2450
2451         /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx() and ..._intrin_sse2()
2452          * require that the input arrays (in our case the integer signals)
2453          * have a buffer of up to 3 zeroes in front (at negative indices) for
2454          * alignment purposes; we use 4 in front to keep the data well-aligned.
2455          */
2456
2457         for(i = 0; ok && i < encoder->protected_->channels; i++) {
2458                 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2459                 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2460                 encoder->private_->integer_signal[i] += 4;
2461 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2462 #if 0 /* @@@ currently unused */
2463                 if(encoder->protected_->max_lpc_order > 0)
2464                         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2465 #endif
2466 #endif
2467         }
2468         for(i = 0; ok && i < 2; i++) {
2469                 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]);
2470                 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2471                 encoder->private_->integer_signal_mid_side[i] += 4;
2472 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2473 #if 0 /* @@@ currently unused */
2474                 if(encoder->protected_->max_lpc_order > 0)
2475                         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]);
2476 #endif
2477 #endif
2478         }
2479 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2480         if(ok && encoder->protected_->max_lpc_order > 0) {
2481                 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2482                         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2483                 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2484         }
2485 #endif
2486         for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2487                 for(i = 0; ok && i < 2; i++) {
2488                         ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2489                 }
2490         }
2491         for(channel = 0; ok && channel < 2; channel++) {
2492                 for(i = 0; ok && i < 2; i++) {
2493                         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]);
2494                 }
2495         }
2496         /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2497         /*@@@ 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) */
2498         ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2499         if(encoder->protected_->do_escape_coding)
2500                 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2501
2502         /* now adjust the windows if the blocksize has changed */
2503 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2504         if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2505                 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2506                         switch(encoder->protected_->apodizations[i].type) {
2507                                 case FLAC__APODIZATION_BARTLETT:
2508                                         FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2509                                         break;
2510                                 case FLAC__APODIZATION_BARTLETT_HANN:
2511                                         FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2512                                         break;
2513                                 case FLAC__APODIZATION_BLACKMAN:
2514                                         FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2515                                         break;
2516                                 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2517                                         FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2518                                         break;
2519                                 case FLAC__APODIZATION_CONNES:
2520                                         FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2521                                         break;
2522                                 case FLAC__APODIZATION_FLATTOP:
2523                                         FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2524                                         break;
2525                                 case FLAC__APODIZATION_GAUSS:
2526                                         FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2527                                         break;
2528                                 case FLAC__APODIZATION_HAMMING:
2529                                         FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2530                                         break;
2531                                 case FLAC__APODIZATION_HANN:
2532                                         FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2533                                         break;
2534                                 case FLAC__APODIZATION_KAISER_BESSEL:
2535                                         FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2536                                         break;
2537                                 case FLAC__APODIZATION_NUTTALL:
2538                                         FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2539                                         break;
2540                                 case FLAC__APODIZATION_RECTANGLE:
2541                                         FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2542                                         break;
2543                                 case FLAC__APODIZATION_TRIANGLE:
2544                                         FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2545                                         break;
2546                                 case FLAC__APODIZATION_TUKEY:
2547                                         FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2548                                         break;
2549                                 case FLAC__APODIZATION_PARTIAL_TUKEY:
2550                                         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);
2551                                         break;
2552                                 case FLAC__APODIZATION_PUNCHOUT_TUKEY:
2553                                         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);
2554                                         break;
2555                                 case FLAC__APODIZATION_WELCH:
2556                                         FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2557                                         break;
2558                                 default:
2559                                         FLAC__ASSERT(0);
2560                                         /* double protection */
2561                                         FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2562                                         break;
2563                         }
2564                 }
2565         }
2566 #endif
2567
2568         if(ok)
2569                 encoder->private_->input_capacity = new_blocksize;
2570         else
2571                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2572
2573         return ok;
2574 }
2575
2576 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2577 {
2578         const FLAC__byte *buffer;
2579         size_t bytes;
2580
2581         FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2582
2583         if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2584                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2585                 return false;
2586         }
2587
2588         if(encoder->protected_->verify) {
2589                 encoder->private_->verify.output.data = buffer;
2590                 encoder->private_->verify.output.bytes = bytes;
2591                 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2592                         encoder->private_->verify.needs_magic_hack = true;
2593                 }
2594                 else {
2595                         if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2596                                 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2597                                 FLAC__bitwriter_clear(encoder->private_->frame);
2598                                 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2599                                         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2600                                 return false;
2601                         }
2602                 }
2603         }
2604
2605         if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2606                 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2607                 FLAC__bitwriter_clear(encoder->private_->frame);
2608                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2609                 return false;
2610         }
2611
2612         FLAC__bitwriter_release_buffer(encoder->private_->frame);
2613         FLAC__bitwriter_clear(encoder->private_->frame);
2614
2615         if(samples > 0) {
2616                 encoder->private_->streaminfo.data.stream_info.min_framesize = flac_min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2617                 encoder->private_->streaminfo.data.stream_info.max_framesize = flac_max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2618         }
2619
2620         return true;
2621 }
2622
2623 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2624 {
2625         FLAC__StreamEncoderWriteStatus status;
2626         FLAC__uint64 output_position = 0;
2627
2628 #if FLAC__HAS_OGG == 0
2629         (void)is_last_block;
2630 #endif
2631
2632         /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2633         if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2634                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2635                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2636         }
2637
2638         /*
2639          * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2640          */
2641         if(samples == 0) {
2642                 FLAC__MetadataType type = (buffer[0] & 0x7f);
2643                 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2644                         encoder->protected_->streaminfo_offset = output_position;
2645                 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2646                         encoder->protected_->seektable_offset = output_position;
2647         }
2648
2649         /*
2650          * Mark the current seek point if hit (if audio_offset == 0 that
2651          * means we're still writing metadata and haven't hit the first
2652          * frame yet)
2653          */
2654         if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2655                 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2656                 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2657                 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2658                 FLAC__uint64 test_sample;
2659                 unsigned i;
2660                 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2661                         test_sample = encoder->private_->seek_table->points[i].sample_number;
2662                         if(test_sample > frame_last_sample) {
2663                                 break;
2664                         }
2665                         else if(test_sample >= frame_first_sample) {
2666                                 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2667                                 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2668                                 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2669                                 encoder->private_->first_seekpoint_to_check++;
2670                                 /* DO NOT: "break;" and here's why:
2671                                  * The seektable template may contain more than one target
2672                                  * sample for any given frame; we will keep looping, generating
2673                                  * duplicate seekpoints for them, and we'll clean it up later,
2674                                  * just before writing the seektable back to the metadata.
2675                                  */
2676                         }
2677                         else {
2678                                 encoder->private_->first_seekpoint_to_check++;
2679                         }
2680                 }
2681         }
2682
2683 #if FLAC__HAS_OGG
2684         if(encoder->private_->is_ogg) {
2685                 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2686                         &encoder->protected_->ogg_encoder_aspect,
2687                         buffer,
2688                         bytes,
2689                         samples,
2690                         encoder->private_->current_frame_number,
2691                         is_last_block,
2692                         (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2693                         encoder,
2694                         encoder->private_->client_data
2695                 );
2696         }
2697         else
2698 #endif
2699         status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2700
2701         if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2702                 encoder->private_->bytes_written += bytes;
2703                 encoder->private_->samples_written += samples;
2704                 /* we keep a high watermark on the number of frames written because
2705                  * when the encoder goes back to write metadata, 'current_frame'
2706                  * will drop back to 0.
2707                  */
2708                 encoder->private_->frames_written = flac_max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2709         }
2710         else
2711                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2712
2713         return status;
2714 }
2715
2716 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2717 void update_metadata_(const FLAC__StreamEncoder *encoder)
2718 {
2719         FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2720         const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2721         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2722         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2723         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2724         const unsigned bps = metadata->data.stream_info.bits_per_sample;
2725         FLAC__StreamEncoderSeekStatus seek_status;
2726
2727         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2728
2729         /* All this is based on intimate knowledge of the stream header
2730          * layout, but a change to the header format that would break this
2731          * would also break all streams encoded in the previous format.
2732          */
2733
2734         /*
2735          * Write MD5 signature
2736          */
2737         {
2738                 const unsigned md5_offset =
2739                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2740                         (
2741                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2742                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2743                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2744                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2745                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2746                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2747                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2748                                 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2749                         ) / 8;
2750
2751                 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2752                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2753                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2754                         return;
2755                 }
2756                 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2757                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2758                         return;
2759                 }
2760         }
2761
2762         /*
2763          * Write total samples
2764          */
2765         {
2766                 const unsigned total_samples_byte_offset =
2767                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2768                         (
2769                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2770                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2771                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2772                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2773                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2774                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2775                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2776                                 - 4
2777                         ) / 8;
2778
2779                 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2780                 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2781                 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2782                 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2783                 b[4] = (FLAC__byte)(samples & 0xFF);
2784                 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) {
2785                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2786                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2787                         return;
2788                 }
2789                 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2790                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2791                         return;
2792                 }
2793         }
2794
2795         /*
2796          * Write min/max framesize
2797          */
2798         {
2799                 const unsigned min_framesize_offset =
2800                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2801                         (
2802                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2803                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2804                         ) / 8;
2805
2806                 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2807                 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2808                 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2809                 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2810                 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2811                 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2812                 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) {
2813                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2814                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2815                         return;
2816                 }
2817                 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2818                         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2819                         return;
2820                 }
2821         }
2822
2823         /*
2824          * Write seektable
2825          */
2826         if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2827                 unsigned i;
2828
2829                 FLAC__format_seektable_sort(encoder->private_->seek_table);
2830
2831                 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2832
2833                 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) {
2834                         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2835                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2836                         return;
2837                 }
2838
2839                 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2840                         FLAC__uint64 xx;
2841                         unsigned x;
2842                         xx = encoder->private_->seek_table->points[i].sample_number;
2843                         b[7] = (FLAC__byte)xx; xx >>= 8;
2844                         b[6] = (FLAC__byte)xx; xx >>= 8;
2845                         b[5] = (FLAC__byte)xx; xx >>= 8;
2846                         b[4] = (FLAC__byte)xx; xx >>= 8;
2847                         b[3] = (FLAC__byte)xx; xx >>= 8;
2848                         b[2] = (FLAC__byte)xx; xx >>= 8;
2849                         b[1] = (FLAC__byte)xx; xx >>= 8;
2850                         b[0] = (FLAC__byte)xx; xx >>= 8;
2851                         xx = encoder->private_->seek_table->points[i].stream_offset;
2852                         b[15] = (FLAC__byte)xx; xx >>= 8;
2853                         b[14] = (FLAC__byte)xx; xx >>= 8;
2854                         b[13] = (FLAC__byte)xx; xx >>= 8;
2855                         b[12] = (FLAC__byte)xx; xx >>= 8;
2856                         b[11] = (FLAC__byte)xx; xx >>= 8;
2857                         b[10] = (FLAC__byte)xx; xx >>= 8;
2858                         b[9] = (FLAC__byte)xx; xx >>= 8;
2859                         b[8] = (FLAC__byte)xx; xx >>= 8;
2860                         x = encoder->private_->seek_table->points[i].frame_samples;
2861                         b[17] = (FLAC__byte)x; x >>= 8;
2862                         b[16] = (FLAC__byte)x; x >>= 8;
2863                         if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2864                                 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2865                                 return;
2866                         }
2867                 }
2868         }
2869 }
2870
2871 #if FLAC__HAS_OGG
2872 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2873 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2874 {
2875         /* the # of bytes in the 1st packet that precede the STREAMINFO */
2876         static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2877                 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2878                 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2879                 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2880                 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2881                 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2882                 FLAC__STREAM_SYNC_LENGTH
2883         ;
2884         FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2885         const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2886         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2887         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2888         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2889         ogg_page page;
2890
2891         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2892         FLAC__ASSERT(0 != encoder->private_->seek_callback);
2893
2894         /* Pre-check that client supports seeking, since we don't want the
2895          * ogg_helper code to ever have to deal with this condition.
2896          */
2897         if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2898                 return;
2899
2900         /* All this is based on intimate knowledge of the stream header
2901          * layout, but a change to the header format that would break this
2902          * would also break all streams encoded in the previous format.
2903          */
2904
2905         /**
2906          ** Write STREAMINFO stats
2907          **/
2908         simple_ogg_page__init(&page);
2909         if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2910                 simple_ogg_page__clear(&page);
2911                 return; /* state already set */
2912         }
2913
2914         /*
2915          * Write MD5 signature
2916          */
2917         {
2918                 const unsigned md5_offset =
2919                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2920                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2921                         (
2922                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2923                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2924                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2925                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2926                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2927                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2928                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2929                                 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2930                         ) / 8;
2931
2932                 if(md5_offset + 16 > (unsigned)page.body_len) {
2933                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2934                         simple_ogg_page__clear(&page);
2935                         return;
2936                 }
2937                 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2938         }
2939
2940         /*
2941          * Write total samples
2942          */
2943         {
2944                 const unsigned total_samples_byte_offset =
2945                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2946                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2947                         (
2948                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2949                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2950                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2951                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2952                                 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2953                                 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2954                                 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2955                                 - 4
2956                         ) / 8;
2957
2958                 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2959                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2960                         simple_ogg_page__clear(&page);
2961                         return;
2962                 }
2963                 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2964                 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2965                 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2966                 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2967                 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2968                 b[4] = (FLAC__byte)(samples & 0xFF);
2969                 memcpy(page.body + total_samples_byte_offset, b, 5);
2970         }
2971
2972         /*
2973          * Write min/max framesize
2974          */
2975         {
2976                 const unsigned min_framesize_offset =
2977                         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2978                         FLAC__STREAM_METADATA_HEADER_LENGTH +
2979                         (
2980                                 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2981                                 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2982                         ) / 8;
2983
2984                 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2985                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2986                         simple_ogg_page__clear(&page);
2987                         return;
2988                 }
2989                 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2990                 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2991                 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2992                 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2993                 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2994                 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2995                 memcpy(page.body + min_framesize_offset, b, 6);
2996         }
2997         if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2998                 simple_ogg_page__clear(&page);
2999                 return; /* state already set */
3000         }
3001         simple_ogg_page__clear(&page);
3002
3003         /*
3004          * Write seektable
3005          */
3006         if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
3007                 unsigned i;
3008                 FLAC__byte *p;
3009
3010                 FLAC__format_seektable_sort(encoder->private_->seek_table);
3011
3012                 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
3013
3014                 simple_ogg_page__init(&page);
3015                 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
3016                         simple_ogg_page__clear(&page);
3017                         return; /* state already set */
3018                 }
3019
3020                 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
3021                         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
3022                         simple_ogg_page__clear(&page);
3023                         return;
3024                 }
3025
3026                 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
3027                         FLAC__uint64 xx;
3028                         unsigned x;
3029                         xx = encoder->private_->seek_table->points[i].sample_number;
3030                         b[7] = (FLAC__byte)xx; xx >>= 8;
3031                         b[6] = (FLAC__byte)xx; xx >>= 8;
3032                         b[5] = (FLAC__byte)xx; xx >>= 8;
3033                         b[4] = (FLAC__byte)xx; xx >>= 8;
3034                         b[3] = (FLAC__byte)xx; xx >>= 8;
3035                         b[2] = (FLAC__byte)xx; xx >>= 8;
3036                         b[1] = (FLAC__byte)xx; xx >>= 8;
3037                         b[0] = (FLAC__byte)xx; xx >>= 8;
3038                         xx = encoder->private_->seek_table->points[i].stream_offset;
3039                         b[15] = (FLAC__byte)xx; xx >>= 8;
3040                         b[14] = (FLAC__byte)xx; xx >>= 8;
3041                         b[13] = (FLAC__byte)xx; xx >>= 8;
3042                         b[12] = (FLAC__byte)xx; xx >>= 8;
3043                         b[11] = (FLAC__byte)xx; xx >>= 8;
3044                         b[10] = (FLAC__byte)xx; xx >>= 8;
3045                         b[9] = (FLAC__byte)xx; xx >>= 8;
3046                         b[8] = (FLAC__byte)xx; xx >>= 8;
3047                         x = encoder->private_->seek_table->points[i].frame_samples;
3048                         b[17] = (FLAC__byte)x; x >>= 8;
3049                         b[16] = (FLAC__byte)x; x >>= 8;
3050                         memcpy(p, b, 18);
3051                 }
3052
3053                 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
3054                         simple_ogg_page__clear(&page);
3055                         return; /* state already set */
3056                 }
3057                 simple_ogg_page__clear(&page);
3058         }
3059 }
3060 #endif
3061
3062 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
3063 {
3064         FLAC__uint16 crc;
3065         FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
3066
3067         /*
3068          * Accumulate raw signal to the MD5 signature
3069          */
3070         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)) {
3071                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3072                 return false;
3073         }
3074
3075         /*
3076          * Process the frame header and subframes into the frame bitbuffer
3077          */
3078         if(!process_subframes_(encoder, is_fractional_block)) {
3079                 /* the above function sets the state for us in case of an error */
3080                 return false;
3081         }
3082
3083         /*
3084          * Zero-pad the frame to a byte_boundary
3085          */
3086         if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
3087                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3088                 return false;
3089         }
3090
3091         /*
3092          * CRC-16 the whole thing
3093          */
3094         FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
3095         if(
3096                 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
3097                 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
3098         ) {
3099                 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3100                 return false;
3101         }
3102
3103         /*
3104          * Write it
3105          */
3106         if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
3107                 /* the above function sets the state for us in case of an error */
3108                 return false;
3109         }
3110
3111         /*
3112          * Get ready for the next frame
3113          */
3114         encoder->private_->current_sample_number = 0;
3115         encoder->private_->current_frame_number++;
3116         encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
3117
3118         return true;
3119 }
3120
3121 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
3122 {
3123         FLAC__FrameHeader frame_header;
3124         unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
3125         FLAC__bool do_independent, do_mid_side;
3126
3127         /*
3128          * Calculate the min,max Rice partition orders
3129          */
3130         if(is_fractional_block) {
3131                 max_partition_order = 0;
3132         }
3133         else {
3134                 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
3135                 max_partition_order = flac_min(max_partition_order, encoder->protected_->max_residual_partition_order);
3136         }
3137         min_partition_order = flac_min(min_partition_order, max_partition_order);
3138
3139         /*
3140          * Setup the frame
3141          */
3142         frame_header.blocksize = encoder->protected_->blocksize;
3143         frame_header.sample_rate = encoder->protected_->sample_rate;
3144         frame_header.channels = encoder->protected_->channels;
3145         frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
3146         frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
3147         frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
3148         frame_header.number.frame_number = encoder->private_->current_frame_number;
3149
3150         /*
3151          * Figure out what channel assignments to try
3152          */
3153         if(encoder->protected_->do_mid_side_stereo) {
3154                 if(encoder->protected_->loose_mid_side_stereo) {
3155                         if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
3156                                 do_independent = true;
3157                                 do_mid_side = true;
3158                         }
3159                         else {
3160                                 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
3161                                 do_mid_side = !do_independent;
3162                         }
3163                 }
3164                 else {
3165                         do_independent = true;
3166                         do_mid_side = true;
3167                 }
3168         }
3169         else {
3170                 do_independent = true;
3171                 do_mid_side = false;
3172         }
3173
3174         FLAC__ASSERT(do_independent || do_mid_side);
3175
3176         /*
3177          * Check for wasted bits; set effective bps for each subframe
3178          */
3179         if(do_independent) {
3180                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3181                         unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
3182                         if (w > encoder->protected_->bits_per_sample) {
3183                                 w = encoder->protected_->bits_per_sample;
3184                         }
3185                         encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
3186                         encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
3187                 }
3188         }
3189         if(do_mid_side) {
3190                 FLAC__ASSERT(encoder->protected_->channels == 2);
3191                 for(channel = 0; channel < 2; channel++) {
3192                         unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
3193                         if (w > encoder->protected_->bits_per_sample) {
3194                                 w = encoder->protected_->bits_per_sample;
3195                         }
3196                         encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
3197                         encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
3198                 }
3199         }
3200
3201         /*
3202          * First do a normal encoding pass of each independent channel
3203          */
3204         if(do_independent) {
3205                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3206                         if(!
3207                                 process_subframe_(
3208                                         encoder,
3209                                         min_partition_order,
3210                                         max_partition_order,
3211                                         &frame_header,
3212                                         encoder->private_->subframe_bps[channel],
3213                                         encoder->private_->integer_signal[channel],
3214                                         encoder->private_->subframe_workspace_ptr[channel],
3215                                         encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3216                                         encoder->private_->residual_workspace[channel],
3217                                         encoder->private_->best_subframe+channel,
3218                                         encoder->private_->best_subframe_bits+channel
3219                                 )
3220                         )
3221                                 return false;
3222                 }
3223         }
3224
3225         /*
3226          * Now do mid and side channels if requested
3227          */
3228         if(do_mid_side) {
3229                 FLAC__ASSERT(encoder->protected_->channels == 2);
3230
3231                 for(channel = 0; channel < 2; channel++) {
3232                         if(!
3233                                 process_subframe_(
3234                                         encoder,
3235                                         min_partition_order,
3236                                         max_partition_order,
3237                                         &frame_header,
3238                                         encoder->private_->subframe_bps_mid_side[channel],
3239                                         encoder->private_->integer_signal_mid_side[channel],
3240                                         encoder->private_->subframe_workspace_ptr_mid_side[channel],
3241                                         encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3242                                         encoder->private_->residual_workspace_mid_side[channel],
3243                                         encoder->private_->best_subframe_mid_side+channel,
3244                                         encoder->private_->best_subframe_bits_mid_side+channel
3245                                 )
3246                         )
3247                                 return false;
3248                 }
3249         }
3250
3251         /*
3252          * Compose the frame bitbuffer
3253          */
3254         if(do_mid_side) {
3255                 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3256                 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3257                 FLAC__ChannelAssignment channel_assignment;
3258
3259                 FLAC__ASSERT(encoder->protected_->channels == 2);
3260
3261                 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3262                         channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3263                 }
3264                 else {
3265                         unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3266                         unsigned min_bits;
3267                         int ca;
3268
3269                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3270                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE   == 1);
3271                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE  == 2);
3272                         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE    == 3);
3273                         FLAC__ASSERT(do_independent && do_mid_side);
3274
3275                         /* We have to figure out which channel assignent results in the smallest frame */
3276                         bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits         [1];
3277                         bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE  ] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits_mid_side[1];
3278                         bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits         [1] + encoder->private_->best_subframe_bits_mid_side[1];
3279                         bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE   ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3280
3281                         channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3282                         min_bits = bits[channel_assignment];
3283                         for(ca = 1; ca <= 3; ca++) {
3284                                 if(bits[ca] < min_bits) {
3285                                         min_bits = bits[ca];
3286                                         channel_assignment = (FLAC__ChannelAssignment)ca;
3287                                 }
3288                         }
3289                 }
3290
3291                 frame_header.channel_assignment = channel_assignment;
3292
3293                 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3294                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3295                         return false;
3296                 }
3297
3298                 switch(channel_assignment) {
3299                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3300                                 left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3301                                 right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
3302                                 break;
3303                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3304                                 left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3305                                 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3306                                 break;
3307                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3308                                 left_subframe  = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3309                                 right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
3310                                 break;
3311                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3312                                 left_subframe  = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3313                                 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3314                                 break;
3315                         default:
3316                                 FLAC__ASSERT(0);
3317                 }
3318
3319                 switch(channel_assignment) {
3320                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3321                                 left_bps  = encoder->private_->subframe_bps         [0];
3322                                 right_bps = encoder->private_->subframe_bps         [1];
3323                                 break;
3324                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3325                                 left_bps  = encoder->private_->subframe_bps         [0];
3326                                 right_bps = encoder->private_->subframe_bps_mid_side[1];
3327                                 break;
3328                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3329                                 left_bps  = encoder->private_->subframe_bps_mid_side[1];
3330                                 right_bps = encoder->private_->subframe_bps         [1];
3331                                 break;
3332                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3333                                 left_bps  = encoder->private_->subframe_bps_mid_side[0];
3334                                 right_bps = encoder->private_->subframe_bps_mid_side[1];
3335                                 break;
3336                         default:
3337                                 FLAC__ASSERT(0);
3338                 }
3339
3340                 /* note that encoder_add_subframe_ sets the state for us in case of an error */
3341                 if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3342                         return false;
3343                 if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3344                         return false;
3345         }
3346         else {
3347                 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3348                         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3349                         return false;
3350                 }
3351
3352                 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3353                         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)) {
3354                                 /* the above function sets the state for us in case of an error */
3355                                 return false;
3356                         }
3357                 }
3358         }
3359
3360         if(encoder->protected_->loose_mid_side_stereo) {
3361                 encoder->private_->loose_mid_side_stereo_frame_count++;
3362                 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3363                         encoder->private_->loose_mid_side_stereo_frame_count = 0;
3364         }
3365
3366         encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3367
3368         return true;
3369 }
3370
3371 FLAC__bool process_subframe_(
3372         FLAC__StreamEncoder *encoder,
3373         unsigned min_partition_order,
3374         unsigned max_partition_order,
3375         const FLAC__FrameHeader *frame_header,
3376         unsigned subframe_bps,
3377         const FLAC__int32 integer_signal[],
3378         FLAC__Subframe *subframe[2],
3379         FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3380         FLAC__int32 *residual[2],
3381         unsigned *best_subframe,
3382         unsigned *best_bits
3383 )
3384 {
3385 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3386         FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3387 #else
3388         FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3389 #endif
3390 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3391         FLAC__double lpc_residual_bits_per_sample;
3392         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 */
3393         FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3394         unsigned min_lpc_order, max_lpc_order, lpc_order;
3395         unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3396 #endif
3397         unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3398         unsigned rice_parameter;
3399         unsigned _candidate_bits, _best_bits;
3400         unsigned _best_subframe;
3401         /* only use RICE2 partitions if stream bps > 16 */
3402         const unsigned rice_parameter_limit = FLAC__stream_encoder_get_bits_per_sample(encoder) > 16? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
3403
3404         FLAC__ASSERT(frame_header->blocksize > 0);
3405
3406         /* verbatim subframe is the baseline against which we measure other compressed subframes */
3407         _best_subframe = 0;
3408         if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3409                 _best_bits = UINT_MAX;
3410         else
3411                 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3412
3413         if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3414                 unsigned signal_is_constant = false;
3415                 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);
3416                 /* check for constant subframe */
3417                 if(
3418                         !encoder->private_->disable_constant_subframes &&
3419 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3420                         fixed_residual_bits_per_sample[1] == 0.0
3421 #else
3422                         fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3423 #endif
3424                 ) {
3425                         /* the above means it's possible all samples are the same value; now double-check it: */
3426                         unsigned i;
3427                         signal_is_constant = true;
3428                         for(i = 1; i < frame_header->blocksize; i++) {
3429                                 if(integer_signal[0] != integer_signal[i]) {
3430                                         signal_is_constant = false;
3431                                         break;
3432                                 }
3433                         }
3434                 }
3435                 if(signal_is_constant) {
3436                         _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3437                         if(_candidate_bits < _best_bits) {
3438                                 _best_subframe = !_best_subframe;
3439                                 _best_bits = _candidate_bits;
3440                         }
3441                 }
3442                 else {
3443                         if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3444                                 /* encode fixed */
3445                                 if(encoder->protected_->do_exhaustive_model_search) {
3446                                         min_fixed_order = 0;
3447                                         max_fixed_order = FLAC__MAX_FIXED_ORDER;
3448                                 }
3449                                 else {
3450                                         min_fixed_order = max_fixed_order = guess_fixed_order;
3451                                 }
3452                                 if(max_fixed_order >= frame_header->blocksize)
3453                                         max_fixed_order = frame_header->blocksize - 1;
3454                                 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3455 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3456                                         if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3457                                                 continue; /* don't even try */
3458                                         rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > 0.0)? (unsigned)(fixed_residual_bits_per_sample[fixed_order]+0.5) : 0; /* 0.5 is for rounding */
3459 #else
3460                                         if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3461                                                 continue; /* don't even try */
3462                                         rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > FLAC__FP_ZERO)? (unsigned)FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]+FLAC__FP_ONE_HALF) : 0; /* 0.5 is for rounding */
3463 #endif
3464                                         rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3465                                         if(rice_parameter >= rice_parameter_limit) {
3466 #ifdef DEBUG_VERBOSE
3467                                                 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
3468 #endif
3469                                                 rice_parameter = rice_parameter_limit - 1;
3470                                         }
3471                                         _candidate_bits =
3472                                                 evaluate_fixed_subframe_(
3473                                                         encoder,
3474                                                         integer_signal,
3475                                                         residual[!_best_subframe],
3476                                                         encoder->private_->abs_residual_partition_sums,
3477                                                         encoder->private_->raw_bits_per_partition,
3478                                                         frame_header->blocksize,
3479                                                         subframe_bps,
3480                                                         fixed_order,
3481                                                         rice_parameter,
3482                                                         rice_parameter_limit,
3483                                                         min_partition_order,
3484                                                         max_partition_order,
3485                                                         encoder->protected_->do_escape_coding,
3486                                                         encoder->protected_->rice_parameter_search_dist,
3487                                                         subframe[!_best_subframe],
3488                                                         partitioned_rice_contents[!_best_subframe]
3489                                                 );
3490                                         if(_candidate_bits < _best_bits) {
3491                                                 _best_subframe = !_best_subframe;
3492                                                 _best_bits = _candidate_bits;
3493                                         }
3494                                 }
3495                         }
3496
3497 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3498                         /* encode lpc */
3499                         if(encoder->protected_->max_lpc_order > 0) {
3500                                 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3501                                         max_lpc_order = frame_header->blocksize-1;
3502                                 else
3503                                         max_lpc_order = encoder->protected_->max_lpc_order;
3504                                 if(max_lpc_order > 0) {
3505                                         unsigned a;
3506                                         for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3507                                                 FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3508                                                 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3509                                                 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3510                                                 if(autoc[0] != 0.0) {
3511                                                         FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encode