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