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