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