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