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