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