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