1 /* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007 Josh Coalson
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
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.
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.
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.
36 #if defined _MSC_VER || defined __MINGW32__
37 #include <io.h> /* for _setmode() */
38 #include <fcntl.h> /* for _O_BINARY */
40 #if defined __CYGWIN__ || defined __EMX__
41 #include <io.h> /* for setmode(), O_BINARY */
42 #include <fcntl.h> /* for _O_BINARY */
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 <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
55 #include "FLAC/assert.h"
56 #include "FLAC/stream_decoder.h"
57 #include "protected/stream_encoder.h"
58 #include "private/bitwriter.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"
68 #include "private/ogg_helper.h"
69 #include "private/ogg_mapping.h"
71 #include "private/stream_encoder_framing.h"
72 #include "private/window.h"
77 #define min(x,y) ((x)<(y)?(x):(y))
82 #define max(x,y) ((x)>(y)?(x):(y))
84 /* Exact Rice codeword length calculation is off by default. The simple
85 * (and fast) estimation (of how many bits a residual value will be
86 * encoded with) in this encoder is very good, almost always yielding
87 * compression within 0.1% of exact calculation.
89 #undef EXACT_RICE_BITS_CALCULATION
90 /* Rice parameter searching is off by default. The simple (and fast)
91 * parameter estimation in this encoder is very good, almost always
92 * yielding compression within 0.1% of the optimal parameters.
94 #undef ENABLE_RICE_PARAMETER_SEARCH
98 FLAC__int32 *data[FLAC__MAX_CHANNELS];
99 unsigned size; /* of each data[] in samples */
104 const FLAC__byte *data;
110 ENCODER_IN_MAGIC = 0,
111 ENCODER_IN_METADATA = 1,
115 static struct CompressionLevels {
116 FLAC__bool do_mid_side_stereo;
117 FLAC__bool loose_mid_side_stereo;
118 unsigned max_lpc_order;
119 unsigned qlp_coeff_precision;
120 FLAC__bool do_qlp_coeff_prec_search;
121 FLAC__bool do_escape_coding;
122 FLAC__bool do_exhaustive_model_search;
123 unsigned min_residual_partition_order;
124 unsigned max_residual_partition_order;
125 unsigned rice_parameter_search_dist;
126 } compression_levels_[] = {
127 { false, false, 0, 0, false, false, false, 0, 3, 0 },
128 { true , true , 0, 0, false, false, false, 0, 3, 0 },
129 { true , false, 0, 0, false, false, false, 0, 3, 0 },
130 { false, false, 6, 0, false, false, false, 0, 4, 0 },
131 { true , true , 8, 0, false, false, false, 0, 4, 0 },
132 { true , false, 8, 0, false, false, false, 0, 5, 0 },
133 { true , false, 8, 0, false, false, false, 0, 6, 0 },
134 { true , false, 8, 0, false, false, true , 0, 6, 0 },
135 { true , false, 12, 0, false, false, true , 0, 6, 0 }
139 /***********************************************************************
141 * Private class method prototypes
143 ***********************************************************************/
145 static void set_defaults_(FLAC__StreamEncoder *encoder);
146 static void free_(FLAC__StreamEncoder *encoder);
147 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
148 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
149 static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
150 static void update_metadata_(const FLAC__StreamEncoder *encoder);
152 static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
154 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
155 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
157 static FLAC__bool process_subframe_(
158 FLAC__StreamEncoder *encoder,
159 unsigned min_partition_order,
160 unsigned max_partition_order,
161 const FLAC__FrameHeader *frame_header,
162 unsigned subframe_bps,
163 const FLAC__int32 integer_signal[],
164 #ifndef FLAC__INTEGER_ONLY_LIBRARY
165 const FLAC__real real_signal[],
167 FLAC__Subframe *subframe[2],
168 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
169 FLAC__int32 *residual[2],
170 unsigned *best_subframe,
174 static FLAC__bool add_subframe_(
175 FLAC__StreamEncoder *encoder,
177 unsigned subframe_bps,
178 const FLAC__Subframe *subframe,
179 FLAC__BitWriter *frame
182 static unsigned evaluate_constant_subframe_(
183 FLAC__StreamEncoder *encoder,
184 const FLAC__int32 signal,
186 unsigned subframe_bps,
187 FLAC__Subframe *subframe
190 static unsigned evaluate_fixed_subframe_(
191 FLAC__StreamEncoder *encoder,
192 const FLAC__int32 signal[],
193 FLAC__int32 residual[],
194 FLAC__uint64 abs_residual_partition_sums[],
195 unsigned raw_bits_per_partition[],
197 unsigned subframe_bps,
199 unsigned rice_parameter,
200 unsigned min_partition_order,
201 unsigned max_partition_order,
202 FLAC__bool do_escape_coding,
203 unsigned rice_parameter_search_dist,
204 FLAC__Subframe *subframe,
205 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
208 #ifndef FLAC__INTEGER_ONLY_LIBRARY
209 static unsigned evaluate_lpc_subframe_(
210 FLAC__StreamEncoder *encoder,
211 const FLAC__int32 signal[],
212 FLAC__int32 residual[],
213 FLAC__uint64 abs_residual_partition_sums[],
214 unsigned raw_bits_per_partition[],
215 const FLAC__real lp_coeff[],
217 unsigned subframe_bps,
219 unsigned qlp_coeff_precision,
220 unsigned rice_parameter,
221 unsigned min_partition_order,
222 unsigned max_partition_order,
223 FLAC__bool do_escape_coding,
224 unsigned rice_parameter_search_dist,
225 FLAC__Subframe *subframe,
226 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
230 static unsigned evaluate_verbatim_subframe_(
231 FLAC__StreamEncoder *encoder,
232 const FLAC__int32 signal[],
234 unsigned subframe_bps,
235 FLAC__Subframe *subframe
238 static unsigned find_best_partition_order_(
239 struct FLAC__StreamEncoderPrivate *private_,
240 const FLAC__int32 residual[],
241 FLAC__uint64 abs_residual_partition_sums[],
242 unsigned raw_bits_per_partition[],
243 unsigned residual_samples,
244 unsigned predictor_order,
245 unsigned rice_parameter,
246 unsigned min_partition_order,
247 unsigned max_partition_order,
248 FLAC__bool do_escape_coding,
249 unsigned rice_parameter_search_dist,
250 FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
253 static void precompute_partition_info_sums_(
254 const FLAC__int32 residual[],
255 FLAC__uint64 abs_residual_partition_sums[],
256 unsigned residual_samples,
257 unsigned predictor_order,
258 unsigned min_partition_order,
259 unsigned max_partition_order
262 static void precompute_partition_info_escapes_(
263 const FLAC__int32 residual[],
264 unsigned raw_bits_per_partition[],
265 unsigned residual_samples,
266 unsigned predictor_order,
267 unsigned min_partition_order,
268 unsigned max_partition_order
271 static FLAC__bool set_partitioned_rice_(
272 #ifdef EXACT_RICE_BITS_CALCULATION
273 const FLAC__int32 residual[],
275 const FLAC__uint64 abs_residual_partition_sums[],
276 const unsigned raw_bits_per_partition[],
277 const unsigned residual_samples,
278 const unsigned predictor_order,
279 const unsigned suggested_rice_parameter,
280 const unsigned rice_parameter_search_dist,
281 const unsigned partition_order,
282 const FLAC__bool search_for_escapes,
283 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
287 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
289 /* verify-related routines: */
290 static void append_to_verify_fifo_(
291 verify_input_fifo *fifo,
292 const FLAC__int32 * const input[],
293 unsigned input_offset,
295 unsigned wide_samples
298 static void append_to_verify_fifo_interleaved_(
299 verify_input_fifo *fifo,
300 const FLAC__int32 input[],
301 unsigned input_offset,
303 unsigned wide_samples
306 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
307 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
308 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
309 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
311 static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
312 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
313 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
314 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);
315 static FILE *get_binary_stdout_(void);
318 /***********************************************************************
322 ***********************************************************************/
324 typedef struct FLAC__StreamEncoderPrivate {
325 unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
326 FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
327 FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
328 #ifndef FLAC__INTEGER_ONLY_LIBRARY
329 FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* the floating-point version of the input signal */
330 FLAC__real *real_signal_mid_side[2]; /* the floating-point version of the mid-side input signal (stereo only) */
331 FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
332 FLAC__real *windowed_signal; /* the real_signal[] * current window[] */
334 unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
335 unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
336 FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
337 FLAC__int32 *residual_workspace_mid_side[2][2];
338 FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
339 FLAC__Subframe subframe_workspace_mid_side[2][2];
340 FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
341 FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
342 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
343 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
344 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
345 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
346 unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
347 unsigned best_subframe_mid_side[2];
348 unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
349 unsigned best_subframe_bits_mid_side[2];
350 FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
351 unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
352 FLAC__BitWriter *frame; /* the current frame being worked on */
353 unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
354 unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
355 FLAC__ChannelAssignment last_channel_assignment;
356 FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
357 FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
358 unsigned current_sample_number;
359 unsigned current_frame_number;
360 struct FLAC__MD5Context md5context;
361 FLAC__CPUInfo cpuinfo;
362 #ifndef FLAC__INTEGER_ONLY_LIBRARY
363 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
365 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
367 #ifndef FLAC__INTEGER_ONLY_LIBRARY
368 void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
369 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[]);
370 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[]);
371 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[]);
373 FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
374 FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
375 FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
376 FLAC__bool disable_constant_subframes;
377 FLAC__bool disable_fixed_subframes;
378 FLAC__bool disable_verbatim_subframes;
382 FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
383 FLAC__StreamEncoderSeekCallback seek_callback;
384 FLAC__StreamEncoderTellCallback tell_callback;
385 FLAC__StreamEncoderWriteCallback write_callback;
386 FLAC__StreamEncoderMetadataCallback metadata_callback;
387 FLAC__StreamEncoderProgressCallback progress_callback;
389 unsigned first_seekpoint_to_check;
390 FILE *file; /* only used when encoding to a file */
391 FLAC__uint64 bytes_written;
392 FLAC__uint64 samples_written;
393 unsigned frames_written;
394 unsigned total_frames_estimate;
395 /* unaligned (original) pointers to allocated data */
396 FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
397 FLAC__int32 *integer_signal_mid_side_unaligned[2];
398 #ifndef FLAC__INTEGER_ONLY_LIBRARY
399 FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS];
400 FLAC__real *real_signal_mid_side_unaligned[2];
401 FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
402 FLAC__real *windowed_signal_unaligned;
404 FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
405 FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
406 FLAC__uint64 *abs_residual_partition_sums_unaligned;
407 unsigned *raw_bits_per_partition_unaligned;
409 * These fields have been moved here from private function local
410 * declarations merely to save stack space during encoding.
412 #ifndef FLAC__INTEGER_ONLY_LIBRARY
413 FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
415 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
417 * The data for the verify section
420 FLAC__StreamDecoder *decoder;
421 EncoderStateHint state_hint;
422 FLAC__bool needs_magic_hack;
423 verify_input_fifo input_fifo;
424 verify_output output;
426 FLAC__uint64 absolute_sample;
427 unsigned frame_number;
430 FLAC__int32 expected;
434 FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
435 } FLAC__StreamEncoderPrivate;
437 /***********************************************************************
439 * Public static class data
441 ***********************************************************************/
443 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
444 "FLAC__STREAM_ENCODER_OK",
445 "FLAC__STREAM_ENCODER_UNINITIALIZED",
446 "FLAC__STREAM_ENCODER_OGG_ERROR",
447 "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
448 "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
449 "FLAC__STREAM_ENCODER_CLIENT_ERROR",
450 "FLAC__STREAM_ENCODER_IO_ERROR",
451 "FLAC__STREAM_ENCODER_FRAMING_ERROR",
452 "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
455 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
456 "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
457 "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
458 "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
459 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
460 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
461 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
462 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
463 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
464 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
465 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
466 "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
467 "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
468 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
469 "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
472 FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
473 "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
474 "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
475 "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
476 "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
479 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
480 "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
481 "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
484 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
485 "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
486 "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
487 "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
490 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
491 "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
492 "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
493 "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
496 /* Number of samples that will be overread to watch for end of stream. By
497 * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
498 * always try to read blocksize+1 samples before encoding a block, so that
499 * even if the stream has a total sample count that is an integral multiple
500 * of the blocksize, we will still notice when we are encoding the last
501 * block. This is needed, for example, to correctly set the end-of-stream
502 * marker in Ogg FLAC.
504 * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
505 * not really any reason to change it.
507 static const unsigned OVERREAD_ = 1;
509 /***********************************************************************
511 * Class constructor/destructor
514 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
516 FLAC__StreamEncoder *encoder;
519 FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
521 encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
526 encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
527 if(encoder->protected_ == 0) {
532 encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
533 if(encoder->private_ == 0) {
534 free(encoder->protected_);
539 encoder->private_->frame = FLAC__bitwriter_new();
540 if(encoder->private_->frame == 0) {
541 free(encoder->private_);
542 free(encoder->protected_);
547 encoder->private_->file = 0;
549 set_defaults_(encoder);
551 encoder->private_->is_being_deleted = false;
553 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
554 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
555 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
557 for(i = 0; i < 2; i++) {
558 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
559 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
561 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
562 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
563 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
565 for(i = 0; i < 2; i++) {
566 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
567 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
570 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
571 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
572 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
574 for(i = 0; i < 2; i++) {
575 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
576 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
578 for(i = 0; i < 2; i++)
579 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
581 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
586 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
590 FLAC__ASSERT(0 != encoder);
591 FLAC__ASSERT(0 != encoder->protected_);
592 FLAC__ASSERT(0 != encoder->private_);
593 FLAC__ASSERT(0 != encoder->private_->frame);
595 encoder->private_->is_being_deleted = true;
597 (void)FLAC__stream_encoder_finish(encoder);
599 if(0 != encoder->private_->verify.decoder)
600 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
602 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
603 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
604 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
606 for(i = 0; i < 2; i++) {
607 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
608 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
610 for(i = 0; i < 2; i++)
611 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
613 FLAC__bitwriter_delete(encoder->private_->frame);
614 free(encoder->private_);
615 free(encoder->protected_);
619 /***********************************************************************
621 * Public class methods
623 ***********************************************************************/
625 static FLAC__StreamEncoderInitStatus init_stream_internal_(
626 FLAC__StreamEncoder *encoder,
627 FLAC__StreamEncoderReadCallback read_callback,
628 FLAC__StreamEncoderWriteCallback write_callback,
629 FLAC__StreamEncoderSeekCallback seek_callback,
630 FLAC__StreamEncoderTellCallback tell_callback,
631 FLAC__StreamEncoderMetadataCallback metadata_callback,
637 FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
639 FLAC__ASSERT(0 != encoder);
641 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
642 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
646 return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
649 if(0 == write_callback || (seek_callback && 0 == tell_callback))
650 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
652 if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
653 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
655 if(encoder->protected_->channels != 2) {
656 encoder->protected_->do_mid_side_stereo = false;
657 encoder->protected_->loose_mid_side_stereo = false;
659 else if(!encoder->protected_->do_mid_side_stereo)
660 encoder->protected_->loose_mid_side_stereo = false;
662 if(encoder->protected_->bits_per_sample >= 32)
663 encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
665 if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
666 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
668 if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
669 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
671 if(encoder->protected_->blocksize == 0) {
672 if(encoder->protected_->max_lpc_order == 0)
673 encoder->protected_->blocksize = 1152;
675 encoder->protected_->blocksize = 4096;
678 if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
679 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
681 if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
682 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
684 if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
685 return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
687 if(encoder->protected_->qlp_coeff_precision == 0) {
688 if(encoder->protected_->bits_per_sample < 16) {
689 /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
690 /* @@@ until then we'll make a guess */
691 encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
693 else if(encoder->protected_->bits_per_sample == 16) {
694 if(encoder->protected_->blocksize <= 192)
695 encoder->protected_->qlp_coeff_precision = 7;
696 else if(encoder->protected_->blocksize <= 384)
697 encoder->protected_->qlp_coeff_precision = 8;
698 else if(encoder->protected_->blocksize <= 576)
699 encoder->protected_->qlp_coeff_precision = 9;
700 else if(encoder->protected_->blocksize <= 1152)
701 encoder->protected_->qlp_coeff_precision = 10;
702 else if(encoder->protected_->blocksize <= 2304)
703 encoder->protected_->qlp_coeff_precision = 11;
704 else if(encoder->protected_->blocksize <= 4608)
705 encoder->protected_->qlp_coeff_precision = 12;
707 encoder->protected_->qlp_coeff_precision = 13;
710 if(encoder->protected_->blocksize <= 384)
711 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
712 else if(encoder->protected_->blocksize <= 1152)
713 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
715 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
717 FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
719 else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
720 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
722 if(encoder->protected_->streamable_subset) {
724 encoder->protected_->blocksize != 192 &&
725 encoder->protected_->blocksize != 576 &&
726 encoder->protected_->blocksize != 1152 &&
727 encoder->protected_->blocksize != 2304 &&
728 encoder->protected_->blocksize != 4608 &&
729 encoder->protected_->blocksize != 256 &&
730 encoder->protected_->blocksize != 512 &&
731 encoder->protected_->blocksize != 1024 &&
732 encoder->protected_->blocksize != 2048 &&
733 encoder->protected_->blocksize != 4096 &&
734 encoder->protected_->blocksize != 8192 &&
735 encoder->protected_->blocksize != 16384
737 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
739 encoder->protected_->sample_rate != 8000 &&
740 encoder->protected_->sample_rate != 16000 &&
741 encoder->protected_->sample_rate != 22050 &&
742 encoder->protected_->sample_rate != 24000 &&
743 encoder->protected_->sample_rate != 32000 &&
744 encoder->protected_->sample_rate != 44100 &&
745 encoder->protected_->sample_rate != 48000 &&
746 encoder->protected_->sample_rate != 96000
748 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
750 encoder->protected_->bits_per_sample != 8 &&
751 encoder->protected_->bits_per_sample != 12 &&
752 encoder->protected_->bits_per_sample != 16 &&
753 encoder->protected_->bits_per_sample != 20 &&
754 encoder->protected_->bits_per_sample != 24
756 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
757 if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
758 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
760 encoder->protected_->sample_rate <= 48000 &&
762 encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
763 encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
766 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
770 if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
771 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
772 if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
773 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
776 /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
777 if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
779 for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
780 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
781 FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
783 encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
784 encoder->protected_->metadata[0] = vc;
790 /* keep track of any SEEKTABLE block */
791 if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
793 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
794 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
795 encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
796 break; /* take only the first one */
801 /* validate metadata */
802 if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
803 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
804 metadata_has_seektable = false;
805 metadata_has_vorbis_comment = false;
806 metadata_picture_has_type1 = false;
807 metadata_picture_has_type2 = false;
808 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
809 const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
810 if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
811 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
812 else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
813 if(metadata_has_seektable) /* only one is allowed */
814 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
815 metadata_has_seektable = true;
816 if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
817 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
819 else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
820 if(metadata_has_vorbis_comment) /* only one is allowed */
821 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
822 metadata_has_vorbis_comment = true;
824 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
825 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
826 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
828 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
829 if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
830 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
831 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
832 if(metadata_picture_has_type1) /* there should only be 1 per stream */
833 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
834 metadata_picture_has_type1 = true;
835 /* standard icon must be 32x32 pixel PNG */
837 m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
839 (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
840 m->data.picture.width != 32 ||
841 m->data.picture.height != 32
844 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
846 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
847 if(metadata_picture_has_type2) /* there should only be 1 per stream */
848 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
849 metadata_picture_has_type2 = true;
854 encoder->private_->input_capacity = 0;
855 for(i = 0; i < encoder->protected_->channels; i++) {
856 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
857 #ifndef FLAC__INTEGER_ONLY_LIBRARY
858 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
861 for(i = 0; i < 2; i++) {
862 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
863 #ifndef FLAC__INTEGER_ONLY_LIBRARY
864 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
867 #ifndef FLAC__INTEGER_ONLY_LIBRARY
868 for(i = 0; i < encoder->protected_->num_apodizations; i++)
869 encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
870 encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
872 for(i = 0; i < encoder->protected_->channels; i++) {
873 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
874 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
875 encoder->private_->best_subframe[i] = 0;
877 for(i = 0; i < 2; i++) {
878 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
879 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
880 encoder->private_->best_subframe_mid_side[i] = 0;
882 encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
883 encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
884 #ifndef FLAC__INTEGER_ONLY_LIBRARY
885 encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
887 /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
888 /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply÷ by hand */
889 FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
890 FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
891 FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
892 FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
893 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);
895 if(encoder->private_->loose_mid_side_stereo_frames == 0)
896 encoder->private_->loose_mid_side_stereo_frames = 1;
897 encoder->private_->loose_mid_side_stereo_frame_count = 0;
898 encoder->private_->current_sample_number = 0;
899 encoder->private_->current_frame_number = 0;
901 encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
902 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? */
903 encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
906 * get the CPU info and set the function pointers
908 FLAC__cpu_info(&encoder->private_->cpuinfo);
909 /* first default to the non-asm routines */
910 #ifndef FLAC__INTEGER_ONLY_LIBRARY
911 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
913 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
914 #ifndef FLAC__INTEGER_ONLY_LIBRARY
915 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
916 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
917 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
919 /* now override with asm where appropriate */
920 #ifndef FLAC__INTEGER_ONLY_LIBRARY
921 # ifndef FLAC__NO_ASM
922 if(encoder->private_->cpuinfo.use_asm) {
923 # ifdef FLAC__CPU_IA32
924 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
925 # ifdef FLAC__HAS_NASM
927 if(encoder->private_->cpuinfo.data.ia32.sse) {
928 if(encoder->protected_->max_lpc_order < 4)
929 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
930 else if(encoder->protected_->max_lpc_order < 8)
931 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
932 else if(encoder->protected_->max_lpc_order < 12)
933 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
935 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
938 # endif /* FLAC__SSE_OS */
939 if(encoder->private_->cpuinfo.data.ia32._3dnow)
940 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
942 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
943 if(encoder->private_->cpuinfo.data.ia32.mmx) {
944 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
945 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
948 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
949 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
951 if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
952 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
953 # endif /* FLAC__HAS_NASM */
954 # endif /* FLAC__CPU_IA32 */
956 # endif /* !FLAC__NO_ASM */
957 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
958 /* finally override based on wide-ness if necessary */
959 if(encoder->private_->use_wide_by_block) {
960 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
963 /* set state to OK; from here on, errors are fatal and we'll override the state then */
964 encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
967 encoder->private_->is_ogg = is_ogg;
968 if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
969 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
970 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
974 encoder->private_->read_callback = read_callback;
975 encoder->private_->write_callback = write_callback;
976 encoder->private_->seek_callback = seek_callback;
977 encoder->private_->tell_callback = tell_callback;
978 encoder->private_->metadata_callback = metadata_callback;
979 encoder->private_->client_data = client_data;
981 if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
982 /* the above function sets the state for us in case of an error */
983 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
986 if(!FLAC__bitwriter_init(encoder->private_->frame)) {
987 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
988 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
992 * Set up the verify stuff if necessary
994 if(encoder->protected_->verify) {
996 * First, set up the fifo which will hold the
997 * original signal to compare against
999 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
1000 for(i = 0; i < encoder->protected_->channels; i++) {
1001 if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder->private_->verify.input_fifo.size))) {
1002 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1003 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1006 encoder->private_->verify.input_fifo.tail = 0;
1009 * Now set up a stream decoder for verification
1011 encoder->private_->verify.decoder = FLAC__stream_decoder_new();
1012 if(0 == encoder->private_->verify.decoder) {
1013 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1014 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1017 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) {
1018 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1019 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1022 encoder->private_->verify.error_stats.absolute_sample = 0;
1023 encoder->private_->verify.error_stats.frame_number = 0;
1024 encoder->private_->verify.error_stats.channel = 0;
1025 encoder->private_->verify.error_stats.sample = 0;
1026 encoder->private_->verify.error_stats.expected = 0;
1027 encoder->private_->verify.error_stats.got = 0;
1030 * These must be done before we write any metadata, because that
1031 * calls the write_callback, which uses these values.
1033 encoder->private_->first_seekpoint_to_check = 0;
1034 encoder->private_->samples_written = 0;
1035 encoder->protected_->streaminfo_offset = 0;
1036 encoder->protected_->seektable_offset = 0;
1037 encoder->protected_->audio_offset = 0;
1040 * write the stream header
1042 if(encoder->protected_->verify)
1043 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1044 if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1045 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1046 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1048 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1049 /* the above function sets the state for us in case of an error */
1050 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1054 * write the STREAMINFO metadata block
1056 if(encoder->protected_->verify)
1057 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1058 encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1059 encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1060 encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1061 encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1062 encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1063 encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1064 encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1065 encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1066 encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1067 encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1068 encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1069 memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1070 FLAC__MD5Init(&encoder->private_->md5context);
1071 if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1072 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1073 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1075 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1076 /* the above function sets the state for us in case of an error */
1077 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1081 * Now that the STREAMINFO block is written, we can init this to an
1082 * absurdly-high value...
1084 encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1085 /* ... and clear this to 0 */
1086 encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1089 * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1090 * if not, we will write an empty one (FLAC__add_metadata_block()
1091 * automatically supplies the vendor string).
1093 * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1094 * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
1095 * true it will have already insured that the metadata list is properly
1098 if(!metadata_has_vorbis_comment) {
1099 FLAC__StreamMetadata vorbis_comment;
1100 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1101 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1102 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1103 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1104 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1105 vorbis_comment.data.vorbis_comment.num_comments = 0;
1106 vorbis_comment.data.vorbis_comment.comments = 0;
1107 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1108 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1109 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1111 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1112 /* the above function sets the state for us in case of an error */
1113 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1118 * write the user's metadata blocks
1120 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1121 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1122 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1123 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1124 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1126 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1127 /* the above function sets the state for us in case of an error */
1128 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1132 /* now that all the metadata is written, we save the stream offset */
1133 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 */
1134 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1135 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1138 if(encoder->protected_->verify)
1139 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1141 return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1144 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1145 FLAC__StreamEncoder *encoder,
1146 FLAC__StreamEncoderWriteCallback write_callback,
1147 FLAC__StreamEncoderSeekCallback seek_callback,
1148 FLAC__StreamEncoderTellCallback tell_callback,
1149 FLAC__StreamEncoderMetadataCallback metadata_callback,
1153 return init_stream_internal_(
1155 /*read_callback=*/0,
1165 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1166 FLAC__StreamEncoder *encoder,
1167 FLAC__StreamEncoderReadCallback read_callback,
1168 FLAC__StreamEncoderWriteCallback write_callback,
1169 FLAC__StreamEncoderSeekCallback seek_callback,
1170 FLAC__StreamEncoderTellCallback tell_callback,
1171 FLAC__StreamEncoderMetadataCallback metadata_callback,
1175 return init_stream_internal_(
1187 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1188 FLAC__StreamEncoder *encoder,
1190 FLAC__StreamEncoderProgressCallback progress_callback,
1195 FLAC__StreamEncoderInitStatus init_status;
1197 FLAC__ASSERT(0 != encoder);
1198 FLAC__ASSERT(0 != file);
1200 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1201 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1203 /* double protection */
1205 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1206 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1210 * To make sure that our file does not go unclosed after an error, we
1211 * must assign the FILE pointer before any further error can occur in
1215 file = get_binary_stdout_(); /* just to be safe */
1217 encoder->private_->file = file;
1219 encoder->private_->progress_callback = progress_callback;
1220 encoder->private_->bytes_written = 0;
1221 encoder->private_->samples_written = 0;
1222 encoder->private_->frames_written = 0;
1224 init_status = init_stream_internal_(
1226 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1227 file_write_callback_,
1228 encoder->private_->file == stdout? 0 : file_seek_callback_,
1229 encoder->private_->file == stdout? 0 : file_tell_callback_,
1230 /*metadata_callback=*/0,
1234 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1235 /* the above function sets the state for us in case of an error */
1240 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1242 FLAC__ASSERT(blocksize != 0);
1243 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1249 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1250 FLAC__StreamEncoder *encoder,
1252 FLAC__StreamEncoderProgressCallback progress_callback,
1256 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1259 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1260 FLAC__StreamEncoder *encoder,
1262 FLAC__StreamEncoderProgressCallback progress_callback,
1266 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1269 static FLAC__StreamEncoderInitStatus init_file_internal_(
1270 FLAC__StreamEncoder *encoder,
1271 const char *filename,
1272 FLAC__StreamEncoderProgressCallback progress_callback,
1279 FLAC__ASSERT(0 != encoder);
1282 * To make sure that our file does not go unclosed after an error, we
1283 * have to do the same entrance checks here that are later performed
1284 * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1286 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1287 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1289 file = filename? fopen(filename, "w+b") : stdout;
1292 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1293 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1296 return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1299 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1300 FLAC__StreamEncoder *encoder,
1301 const char *filename,
1302 FLAC__StreamEncoderProgressCallback progress_callback,
1306 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1309 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1310 FLAC__StreamEncoder *encoder,
1311 const char *filename,
1312 FLAC__StreamEncoderProgressCallback progress_callback,
1316 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1319 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1321 FLAC__bool error = false;
1323 FLAC__ASSERT(0 != encoder);
1324 FLAC__ASSERT(0 != encoder->private_);
1325 FLAC__ASSERT(0 != encoder->protected_);
1327 if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1330 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1331 if(encoder->private_->current_sample_number != 0) {
1332 const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1333 encoder->protected_->blocksize = encoder->private_->current_sample_number;
1334 if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1339 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1341 if(!encoder->private_->is_being_deleted) {
1342 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1343 if(encoder->private_->seek_callback) {
1345 if(encoder->private_->is_ogg)
1346 update_ogg_metadata_(encoder);
1349 update_metadata_(encoder);
1351 /* check if an error occurred while updating metadata */
1352 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1355 if(encoder->private_->metadata_callback)
1356 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1359 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1361 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1366 if(0 != encoder->private_->file) {
1367 if(encoder->private_->file != stdout)
1368 fclose(encoder->private_->file);
1369 encoder->private_->file = 0;
1373 if(encoder->private_->is_ogg)
1374 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1378 set_defaults_(encoder);
1381 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1386 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1388 FLAC__ASSERT(0 != encoder);
1389 FLAC__ASSERT(0 != encoder->private_);
1390 FLAC__ASSERT(0 != encoder->protected_);
1391 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1394 /* can't check encoder->private_->is_ogg since that's not set until init time */
1395 FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1403 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1405 FLAC__ASSERT(0 != encoder);
1406 FLAC__ASSERT(0 != encoder->private_);
1407 FLAC__ASSERT(0 != encoder->protected_);
1408 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1410 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1411 encoder->protected_->verify = value;
1416 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1418 FLAC__ASSERT(0 != encoder);
1419 FLAC__ASSERT(0 != encoder->private_);
1420 FLAC__ASSERT(0 != encoder->protected_);
1421 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1423 encoder->protected_->streamable_subset = value;
1427 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1429 FLAC__ASSERT(0 != encoder);
1430 FLAC__ASSERT(0 != encoder->private_);
1431 FLAC__ASSERT(0 != encoder->protected_);
1432 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1434 encoder->protected_->channels = value;
1438 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1440 FLAC__ASSERT(0 != encoder);
1441 FLAC__ASSERT(0 != encoder->private_);
1442 FLAC__ASSERT(0 != encoder->protected_);
1443 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1445 encoder->protected_->bits_per_sample = value;
1449 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1451 FLAC__ASSERT(0 != encoder);
1452 FLAC__ASSERT(0 != encoder->private_);
1453 FLAC__ASSERT(0 != encoder->protected_);
1454 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1456 encoder->protected_->sample_rate = value;
1460 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1462 FLAC__bool ok = true;
1463 FLAC__ASSERT(0 != encoder);
1464 FLAC__ASSERT(0 != encoder->private_);
1465 FLAC__ASSERT(0 != encoder->protected_);
1466 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1468 if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1469 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1470 ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
1471 ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
1474 ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
1475 /* but it's too hard to specify the string in a locale-specific way */
1477 encoder->protected_->num_apodizations = 1;
1478 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1479 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1481 ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
1482 ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
1483 ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1484 ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
1485 ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
1486 ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1487 ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1488 ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
1492 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1494 FLAC__ASSERT(0 != encoder);
1495 FLAC__ASSERT(0 != encoder->private_);
1496 FLAC__ASSERT(0 != encoder->protected_);
1497 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1499 encoder->protected_->blocksize = value;
1503 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1505 FLAC__ASSERT(0 != encoder);
1506 FLAC__ASSERT(0 != encoder->private_);
1507 FLAC__ASSERT(0 != encoder->protected_);
1508 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1510 encoder->protected_->do_mid_side_stereo = value;
1514 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1516 FLAC__ASSERT(0 != encoder);
1517 FLAC__ASSERT(0 != encoder->private_);
1518 FLAC__ASSERT(0 != encoder->protected_);
1519 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1521 encoder->protected_->loose_mid_side_stereo = value;
1525 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1527 FLAC__ASSERT(0 != encoder);
1528 FLAC__ASSERT(0 != encoder->private_);
1529 FLAC__ASSERT(0 != encoder->protected_);
1530 FLAC__ASSERT(0 != specification);
1531 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1533 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1534 (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1536 encoder->protected_->num_apodizations = 0;
1538 const char *s = strchr(specification, ';');
1539 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1540 if (n==8 && 0 == strncmp("bartlett" , specification, n))
1541 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1542 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1543 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1544 else if(n==8 && 0 == strncmp("blackman" , specification, n))
1545 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1546 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1547 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1548 else if(n==6 && 0 == strncmp("connes" , specification, n))
1549 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1550 else if(n==7 && 0 == strncmp("flattop" , specification, n))
1551 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1552 else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
1553 FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1554 if (stddev > 0.0 && stddev <= 0.5) {
1555 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1556 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1559 else if(n==7 && 0 == strncmp("hamming" , specification, n))
1560 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1561 else if(n==4 && 0 == strncmp("hann" , specification, n))
1562 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1563 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1564 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1565 else if(n==7 && 0 == strncmp("nuttall" , specification, n))
1566 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1567 else if(n==9 && 0 == strncmp("rectangle" , specification, n))
1568 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1569 else if(n==8 && 0 == strncmp("triangle" , specification, n))
1570 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1571 else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
1572 FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1573 if (p >= 0.0 && p <= 1.0) {
1574 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1575 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1578 else if(n==5 && 0 == strncmp("welch" , specification, n))
1579 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1580 if (encoder->protected_->num_apodizations == 32)
1583 specification = s+1;
1587 if(encoder->protected_->num_apodizations == 0) {
1588 encoder->protected_->num_apodizations = 1;
1589 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1590 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1596 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1598 FLAC__ASSERT(0 != encoder);
1599 FLAC__ASSERT(0 != encoder->private_);
1600 FLAC__ASSERT(0 != encoder->protected_);
1601 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1603 encoder->protected_->max_lpc_order = value;
1607 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1609 FLAC__ASSERT(0 != encoder);
1610 FLAC__ASSERT(0 != encoder->private_);
1611 FLAC__ASSERT(0 != encoder->protected_);
1612 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1614 encoder->protected_->qlp_coeff_precision = value;
1618 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1620 FLAC__ASSERT(0 != encoder);
1621 FLAC__ASSERT(0 != encoder->private_);
1622 FLAC__ASSERT(0 != encoder->protected_);
1623 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1625 encoder->protected_->do_qlp_coeff_prec_search = value;
1629 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1631 FLAC__ASSERT(0 != encoder);
1632 FLAC__ASSERT(0 != encoder->private_);
1633 FLAC__ASSERT(0 != encoder->protected_);
1634 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1637 /*@@@ deprecated: */
1638 encoder->protected_->do_escape_coding = value;
1645 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1647 FLAC__ASSERT(0 != encoder);
1648 FLAC__ASSERT(0 != encoder->private_);
1649 FLAC__ASSERT(0 != encoder->protected_);
1650 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1652 encoder->protected_->do_exhaustive_model_search = value;
1656 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1658 FLAC__ASSERT(0 != encoder);
1659 FLAC__ASSERT(0 != encoder->private_);
1660 FLAC__ASSERT(0 != encoder->protected_);
1661 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1663 encoder->protected_->min_residual_partition_order = value;
1667 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1669 FLAC__ASSERT(0 != encoder);
1670 FLAC__ASSERT(0 != encoder->private_);
1671 FLAC__ASSERT(0 != encoder->protected_);
1672 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1674 encoder->protected_->max_residual_partition_order = value;
1678 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1680 FLAC__ASSERT(0 != encoder);
1681 FLAC__ASSERT(0 != encoder->private_);
1682 FLAC__ASSERT(0 != encoder->protected_);
1683 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1686 /*@@@ deprecated: */
1687 encoder->protected_->rice_parameter_search_dist = value;
1694 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1696 FLAC__ASSERT(0 != encoder);
1697 FLAC__ASSERT(0 != encoder->private_);
1698 FLAC__ASSERT(0 != encoder->protected_);
1699 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1701 encoder->protected_->total_samples_estimate = value;
1705 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1707 FLAC__ASSERT(0 != encoder);
1708 FLAC__ASSERT(0 != encoder->private_);
1709 FLAC__ASSERT(0 != encoder->protected_);
1710 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1716 /* realloc() does not do exactly what we want so... */
1717 if(encoder->protected_->metadata) {
1718 free(encoder->protected_->metadata);
1719 encoder->protected_->metadata = 0;
1720 encoder->protected_->num_metadata_blocks = 0;
1723 FLAC__StreamMetadata **m;
1724 if(0 == (m = (FLAC__StreamMetadata**)malloc(sizeof(m[0]) * num_blocks)))
1726 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1727 encoder->protected_->metadata = m;
1728 encoder->protected_->num_metadata_blocks = num_blocks;
1731 if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1738 * These three functions are not static, but not publically exposed in
1739 * include/FLAC/ either. They are used by the test suite.
1741 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1743 FLAC__ASSERT(0 != encoder);
1744 FLAC__ASSERT(0 != encoder->private_);
1745 FLAC__ASSERT(0 != encoder->protected_);
1746 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1748 encoder->private_->disable_constant_subframes = value;
1752 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1754 FLAC__ASSERT(0 != encoder);
1755 FLAC__ASSERT(0 != encoder->private_);
1756 FLAC__ASSERT(0 != encoder->protected_);
1757 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1759 encoder->private_->disable_fixed_subframes = value;
1763 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1765 FLAC__ASSERT(0 != encoder);
1766 FLAC__ASSERT(0 != encoder->private_);
1767 FLAC__ASSERT(0 != encoder->protected_);
1768 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1770 encoder->private_->disable_verbatim_subframes = value;
1774 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1776 FLAC__ASSERT(0 != encoder);
1777 FLAC__ASSERT(0 != encoder->private_);
1778 FLAC__ASSERT(0 != encoder->protected_);
1779 return encoder->protected_->state;
1782 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1784 FLAC__ASSERT(0 != encoder);
1785 FLAC__ASSERT(0 != encoder->private_);
1786 FLAC__ASSERT(0 != encoder->protected_);
1787 if(encoder->protected_->verify)
1788 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1790 return FLAC__STREAM_DECODER_UNINITIALIZED;
1793 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1795 FLAC__ASSERT(0 != encoder);
1796 FLAC__ASSERT(0 != encoder->private_);
1797 FLAC__ASSERT(0 != encoder->protected_);
1798 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1799 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1801 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1804 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)
1806 FLAC__ASSERT(0 != encoder);
1807 FLAC__ASSERT(0 != encoder->private_);
1808 FLAC__ASSERT(0 != encoder->protected_);
1809 if(0 != absolute_sample)
1810 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1811 if(0 != frame_number)
1812 *frame_number = encoder->private_->verify.error_stats.frame_number;
1814 *channel = encoder->private_->verify.error_stats.channel;
1816 *sample = encoder->private_->verify.error_stats.sample;
1818 *expected = encoder->private_->verify.error_stats.expected;
1820 *got = encoder->private_->verify.error_stats.got;
1823 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1825 FLAC__ASSERT(0 != encoder);
1826 FLAC__ASSERT(0 != encoder->private_);
1827 FLAC__ASSERT(0 != encoder->protected_);
1828 return encoder->protected_->verify;
1831 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1833 FLAC__ASSERT(0 != encoder);
1834 FLAC__ASSERT(0 != encoder->private_);
1835 FLAC__ASSERT(0 != encoder->protected_);
1836 return encoder->protected_->streamable_subset;
1839 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1841 FLAC__ASSERT(0 != encoder);
1842 FLAC__ASSERT(0 != encoder->private_);
1843 FLAC__ASSERT(0 != encoder->protected_);
1844 return encoder->protected_->channels;
1847 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1849 FLAC__ASSERT(0 != encoder);
1850 FLAC__ASSERT(0 != encoder->private_);
1851 FLAC__ASSERT(0 != encoder->protected_);
1852 return encoder->protected_->bits_per_sample;
1855 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1857 FLAC__ASSERT(0 != encoder);
1858 FLAC__ASSERT(0 != encoder->private_);
1859 FLAC__ASSERT(0 != encoder->protected_);
1860 return encoder->protected_->sample_rate;
1863 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1865 FLAC__ASSERT(0 != encoder);
1866 FLAC__ASSERT(0 != encoder->private_);
1867 FLAC__ASSERT(0 != encoder->protected_);
1868 return encoder->protected_->blocksize;
1871 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1873 FLAC__ASSERT(0 != encoder);
1874 FLAC__ASSERT(0 != encoder->private_);
1875 FLAC__ASSERT(0 != encoder->protected_);
1876 return encoder->protected_->do_mid_side_stereo;
1879 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1881 FLAC__ASSERT(0 != encoder);
1882 FLAC__ASSERT(0 != encoder->private_);
1883 FLAC__ASSERT(0 != encoder->protected_);
1884 return encoder->protected_->loose_mid_side_stereo;
1887 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1889 FLAC__ASSERT(0 != encoder);
1890 FLAC__ASSERT(0 != encoder->private_);
1891 FLAC__ASSERT(0 != encoder->protected_);
1892 return encoder->protected_->max_lpc_order;
1895 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1897 FLAC__ASSERT(0 != encoder);
1898 FLAC__ASSERT(0 != encoder->private_);
1899 FLAC__ASSERT(0 != encoder->protected_);
1900 return encoder->protected_->qlp_coeff_precision;
1903 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1905 FLAC__ASSERT(0 != encoder);
1906 FLAC__ASSERT(0 != encoder->private_);
1907 FLAC__ASSERT(0 != encoder->protected_);
1908 return encoder->protected_->do_qlp_coeff_prec_search;
1911 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1913 FLAC__ASSERT(0 != encoder);
1914 FLAC__ASSERT(0 != encoder->private_);
1915 FLAC__ASSERT(0 != encoder->protected_);
1916 return encoder->protected_->do_escape_coding;
1919 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1921 FLAC__ASSERT(0 != encoder);
1922 FLAC__ASSERT(0 != encoder->private_);
1923 FLAC__ASSERT(0 != encoder->protected_);
1924 return encoder->protected_->do_exhaustive_model_search;
1927 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1929 FLAC__ASSERT(0 != encoder);
1930 FLAC__ASSERT(0 != encoder->private_);
1931 FLAC__ASSERT(0 != encoder->protected_);
1932 return encoder->protected_->min_residual_partition_order;
1935 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1937 FLAC__ASSERT(0 != encoder);
1938 FLAC__ASSERT(0 != encoder->private_);
1939 FLAC__ASSERT(0 != encoder->protected_);
1940 return encoder->protected_->max_residual_partition_order;
1943 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1945 FLAC__ASSERT(0 != encoder);
1946 FLAC__ASSERT(0 != encoder->private_);
1947 FLAC__ASSERT(0 != encoder->protected_);
1948 return encoder->protected_->rice_parameter_search_dist;
1951 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1953 FLAC__ASSERT(0 != encoder);
1954 FLAC__ASSERT(0 != encoder->private_);
1955 FLAC__ASSERT(0 != encoder->protected_);
1956 return encoder->protected_->total_samples_estimate;
1959 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1961 unsigned i, j, channel;
1962 FLAC__int32 x, mid, side;
1963 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1965 FLAC__ASSERT(0 != encoder);
1966 FLAC__ASSERT(0 != encoder->private_);
1967 FLAC__ASSERT(0 != encoder->protected_);
1968 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1972 * we have several flavors of the same basic loop, optimized for
1973 * different conditions:
1975 if(encoder->protected_->max_lpc_order > 0) {
1976 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1978 * stereo coding: unroll channel loop
1979 * with LPC: calculate floating point version of signal
1982 if(encoder->protected_->verify)
1983 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
1985 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
1986 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1987 x = mid = side = buffer[0][j];
1988 encoder->private_->integer_signal[0][i] = x;
1989 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1990 encoder->private_->real_signal[0][i] = (FLAC__real)x;
1993 encoder->private_->integer_signal[1][i] = x;
1994 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1995 encoder->private_->real_signal[1][i] = (FLAC__real)x;
1999 mid >>= 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
2000 encoder->private_->integer_signal_mid_side[1][i] = side;
2001 encoder->private_->integer_signal_mid_side[0][i] = mid;
2002 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2003 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
2004 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
2006 encoder->private_->current_sample_number++;
2008 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2010 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2012 /* move unprocessed overread samples to beginnings of arrays */
2013 FLAC__ASSERT(i == blocksize+OVERREAD_);
2014 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2016 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2017 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2018 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2019 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2020 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2021 encoder->private_->real_signal[0][0] = encoder->private_->real_signal[0][i];
2022 encoder->private_->real_signal[1][0] = encoder->private_->real_signal[1][i];
2023 encoder->private_->real_signal_mid_side[0][0] = encoder->private_->real_signal_mid_side[0][i];
2024 encoder->private_->real_signal_mid_side[1][0] = encoder->private_->real_signal_mid_side[1][i];
2026 encoder->private_->current_sample_number = 1;
2028 } while(j < samples);
2032 * independent channel coding: buffer each channel in inner loop
2033 * with LPC: calculate floating point version of signal
2036 if(encoder->protected_->verify)
2037 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2039 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2040 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2041 for(channel = 0; channel < channels; channel++) {
2042 x = buffer[channel][j];
2043 encoder->private_->integer_signal[channel][i] = x;
2044 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2045 encoder->private_->real_signal[channel][i] = (FLAC__real)x;
2048 encoder->private_->current_sample_number++;
2050 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2052 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2054 /* move unprocessed overread samples to beginnings of arrays */
2055 FLAC__ASSERT(i == blocksize+OVERREAD_);
2056 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2058 for(channel = 0; channel < channels; channel++) {
2059 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2060 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2061 encoder->private_->real_signal[channel][0] = encoder->private_->real_signal[channel][i];
2064 encoder->private_->current_sample_number = 1;
2066 } while(j < samples);
2070 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2072 * stereo coding: unroll channel loop
2073 * without LPC: no need to calculate floating point version of signal
2076 if(encoder->protected_->verify)
2077 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2079 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2080 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2081 encoder->private_->integer_signal[0][i] = mid = side = buffer[0][j];
2083 encoder->private_->integer_signal[1][i] = x;
2086 mid >>= 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
2087 encoder->private_->integer_signal_mid_side[1][i] = side;
2088 encoder->private_->integer_signal_mid_side[0][i] = mid;
2089 encoder->private_->current_sample_number++;
2091 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2093 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2095 /* move unprocessed overread samples to beginnings of arrays */
2096 FLAC__ASSERT(i == blocksize+OVERREAD_);
2097 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2099 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2100 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2101 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2102 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2103 encoder->private_->current_sample_number = 1;
2105 } while(j < samples);
2109 * independent channel coding: buffer each channel in inner loop
2110 * without LPC: no need to calculate floating point version of signal
2113 if(encoder->protected_->verify)
2114 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2116 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2117 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2118 for(channel = 0; channel < channels; channel++)
2119 encoder->private_->integer_signal[channel][i] = buffer[channel][j];
2120 encoder->private_->current_sample_number++;
2122 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2124 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2126 /* move unprocessed overread samples to beginnings of arrays */
2127 FLAC__ASSERT(i == blocksize+OVERREAD_);
2128 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2130 for(channel = 0; channel < channels; channel++)
2131 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2132 encoder->private_->current_sample_number = 1;
2134 } while(j < samples);
2141 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2143 unsigned i, j, k, channel;
2144 FLAC__int32 x, mid, side;
2145 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2147 FLAC__ASSERT(0 != encoder);
2148 FLAC__ASSERT(0 != encoder->private_);
2149 FLAC__ASSERT(0 != encoder->protected_);
2150 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2154 * we have several flavors of the same basic loop, optimized for
2155 * different conditions:
2157 if(encoder->protected_->max_lpc_order > 0) {
2158 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2160 * stereo coding: unroll channel loop
2161 * with LPC: calculate floating point version of signal
2164 if(encoder->protected_->verify)
2165 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2167 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2168 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2169 x = mid = side = buffer[k++];
2170 encoder->private_->integer_signal[0][i] = x;
2171 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2172 encoder->private_->real_signal[0][i] = (FLAC__real)x;
2175 encoder->private_->integer_signal[1][i] = x;
2176 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2177 encoder->private_->real_signal[1][i] = (FLAC__real)x;
2181 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2182 encoder->private_->integer_signal_mid_side[1][i] = side;
2183 encoder->private_->integer_signal_mid_side[0][i] = mid;
2184 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2185 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
2186 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
2188 encoder->private_->current_sample_number++;
2190 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2192 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2194 /* move unprocessed overread samples to beginnings of arrays */
2195 FLAC__ASSERT(i == blocksize+OVERREAD_);
2196 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2198 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2199 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2200 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2201 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2202 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2203 encoder->private_->real_signal[0][0] = encoder->private_->real_signal[0][i];
2204 encoder->private_->real_signal[1][0] = encoder->private_->real_signal[1][i];
2205 encoder->private_->real_signal_mid_side[0][0] = encoder->private_->real_signal_mid_side[0][i];
2206 encoder->private_->real_signal_mid_side[1][0] = encoder->private_->real_signal_mid_side[1][i];
2208 encoder->private_->current_sample_number = 1;
2210 } while(j < samples);
2214 * independent channel coding: buffer each channel in inner loop
2215 * with LPC: calculate floating point version of signal
2218 if(encoder->protected_->verify)
2219 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2221 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2222 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2223 for(channel = 0; channel < channels; channel++) {
2225 encoder->private_->integer_signal[channel][i] = x;
2226 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2227 encoder->private_->real_signal[channel][i] = (FLAC__real)x;
2230 encoder->private_->current_sample_number++;
2232 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2234 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2236 /* move unprocessed overread samples to beginnings of arrays */
2237 FLAC__ASSERT(i == blocksize+OVERREAD_);
2238 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2240 for(channel = 0; channel < channels; channel++) {
2241 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2242 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2243 encoder->private_->real_signal[channel][0] = encoder->private_->real_signal[channel][i];
2246 encoder->private_->current_sample_number = 1;
2248 } while(j < samples);
2252 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2254 * stereo coding: unroll channel loop
2255 * without LPC: no need to calculate floating point version of signal
2258 if(encoder->protected_->verify)
2259 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2261 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2262 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2263 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2265 encoder->private_->integer_signal[1][i] = x;
2268 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2269 encoder->private_->integer_signal_mid_side[1][i] = side;
2270 encoder->private_->integer_signal_mid_side[0][i] = mid;
2271 encoder->private_->current_sample_number++;
2273 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2275 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2277 /* move unprocessed overread samples to beginnings of arrays */
2278 FLAC__ASSERT(i == blocksize+OVERREAD_);
2279 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2281 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2282 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2283 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2284 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2285 encoder->private_->current_sample_number = 1;
2287 } while(j < samples);
2291 * independent channel coding: buffer each channel in inner loop
2292 * without LPC: no need to calculate floating point version of signal
2295 if(encoder->protected_->verify)
2296 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2298 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2299 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2300 for(channel = 0; channel < channels; channel++)
2301 encoder->private_->integer_signal[channel][i] = buffer[k++];
2302 encoder->private_->current_sample_number++;
2304 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2306 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2308 /* move unprocessed overread samples to beginnings of arrays */
2309 FLAC__ASSERT(i == blocksize+OVERREAD_);
2310 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2312 for(channel = 0; channel < channels; channel++)
2313 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2314 encoder->private_->current_sample_number = 1;
2316 } while(j < samples);
2323 /***********************************************************************
2325 * Private class methods
2327 ***********************************************************************/
2329 void set_defaults_(FLAC__StreamEncoder *encoder)
2331 FLAC__ASSERT(0 != encoder);
2333 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2334 encoder->protected_->verify = true;
2336 encoder->protected_->verify = false;
2338 encoder->protected_->streamable_subset = true;
2339 encoder->protected_->do_mid_side_stereo = false;
2340 encoder->protected_->loose_mid_side_stereo = false;
2341 encoder->protected_->channels = 2;
2342 encoder->protected_->bits_per_sample = 16;
2343 encoder->protected_->sample_rate = 44100;
2344 encoder->protected_->blocksize = 0;
2345 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2346 encoder->protected_->num_apodizations = 1;
2347 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2348 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2350 encoder->protected_->max_lpc_order = 0;
2351 encoder->protected_->qlp_coeff_precision = 0;
2352 encoder->protected_->do_qlp_coeff_prec_search = false;
2353 encoder->protected_->do_exhaustive_model_search = false;
2354 encoder->protected_->do_escape_coding = false;
2355 encoder->protected_->min_residual_partition_order = 0;
2356 encoder->protected_->max_residual_partition_order = 0;
2357 encoder->protected_->rice_parameter_search_dist = 0;
2358 encoder->protected_->total_samples_estimate = 0;
2359 encoder->protected_->metadata = 0;
2360 encoder->protected_->num_metadata_blocks = 0;
2362 encoder->private_->seek_table = 0;
2363 encoder->private_->disable_constant_subframes = false;
2364 encoder->private_->disable_fixed_subframes = false;
2365 encoder->private_->disable_verbatim_subframes = false;
2367 encoder->private_->is_ogg = false;
2369 encoder->private_->read_callback = 0;
2370 encoder->private_->write_callback = 0;
2371 encoder->private_->seek_callback = 0;
2372 encoder->private_->tell_callback = 0;
2373 encoder->private_->metadata_callback = 0;
2374 encoder->private_->progress_callback = 0;
2375 encoder->private_->client_data = 0;
2378 FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2382 void free_(FLAC__StreamEncoder *encoder)
2384 unsigned i, channel;
2386 FLAC__ASSERT(0 != encoder);
2387 if(encoder->protected_->metadata) {
2388 free(encoder->protected_->metadata);
2389 encoder->protected_->metadata = 0;
2390 encoder->protected_->num_metadata_blocks = 0;
2392 for(i = 0; i < encoder->protected_->channels; i++) {
2393 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2394 free(encoder->private_->integer_signal_unaligned[i]);
2395 encoder->private_->integer_signal_unaligned[i] = 0;
2397 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2398 if(0 != encoder->private_->real_signal_unaligned[i]) {
2399 free(encoder->private_->real_signal_unaligned[i]);
2400 encoder->private_->real_signal_unaligned[i] = 0;
2404 for(i = 0; i < 2; i++) {
2405 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2406 free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2407 encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2409 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2410 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2411 free(encoder->private_->real_signal_mid_side_unaligned[i]);
2412 encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2416 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2417 for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2418 if(0 != encoder->private_->window_unaligned[i]) {
2419 free(encoder->private_->window_unaligned[i]);
2420 encoder->private_->window_unaligned[i] = 0;
2423 if(0 != encoder->private_->windowed_signal_unaligned) {
2424 free(encoder->private_->windowed_signal_unaligned);
2425 encoder->private_->windowed_signal_unaligned = 0;
2428 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2429 for(i = 0; i < 2; i++) {
2430 if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2431 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2432 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2436 for(channel = 0; channel < 2; channel++) {
2437 for(i = 0; i < 2; i++) {
2438 if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2439 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2440 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2444 if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2445 free(encoder->private_->abs_residual_partition_sums_unaligned);
2446 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2448 if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2449 free(encoder->private_->raw_bits_per_partition_unaligned);
2450 encoder->private_->raw_bits_per_partition_unaligned = 0;
2452 if(encoder->protected_->verify) {
2453 for(i = 0; i < encoder->protected_->channels; i++) {
2454 if(0 != encoder->private_->verify.input_fifo.data[i]) {
2455 free(encoder->private_->verify.input_fifo.data[i]);
2456 encoder->private_->verify.input_fifo.data[i] = 0;
2460 FLAC__bitwriter_free(encoder->private_->frame);
2463 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2466 unsigned i, channel;
2468 FLAC__ASSERT(new_blocksize > 0);
2469 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2470 FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2472 /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2473 if(new_blocksize <= encoder->private_->input_capacity)
2478 /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
2479 * requires that the input arrays (in our case the integer signals)
2480 * have a buffer of up to 3 zeroes in front (at negative indices) for
2481 * alignment purposes; we use 4 in front to keep the data well-aligned.
2484 for(i = 0; ok && i < encoder->protected_->channels; i++) {
2485 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2486 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2487 encoder->private_->integer_signal[i] += 4;
2488 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2489 if(encoder->protected_->max_lpc_order > 0)
2490 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2493 for(i = 0; ok && i < 2; i++) {
2494 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]);
2495 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2496 encoder->private_->integer_signal_mid_side[i] += 4;
2497 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2498 if(encoder->protected_->max_lpc_order > 0)
2499 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]);
2502 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2503 if(ok && encoder->protected_->max_lpc_order > 0) {
2504 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2505 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2506 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2509 for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2510 for(i = 0; ok && i < 2; i++) {
2511 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2514 for(channel = 0; ok && channel < 2; channel++) {
2515 for(i = 0; ok && i < 2; i++) {
2516 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]);
2519 /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2520 /*@@@ new_blocksize*2 is too pessimistic, but to fix, we need smarter logic because a smaller new_blocksize can actually increase the # of partitions; would require moving this out into a separate function, then checking its capacity against the need of the current blocksize&min/max_partition_order (and maybe predictor order) */
2521 ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2522 if(encoder->protected_->do_escape_coding)
2523 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2525 /* now adjust the windows if the blocksize has changed */
2526 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2527 if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2528 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2529 switch(encoder->protected_->apodizations[i].type) {
2530 case FLAC__APODIZATION_BARTLETT:
2531 FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2533 case FLAC__APODIZATION_BARTLETT_HANN:
2534 FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2536 case FLAC__APODIZATION_BLACKMAN:
2537 FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2539 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2540 FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2542 case FLAC__APODIZATION_CONNES:
2543 FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2545 case FLAC__APODIZATION_FLATTOP:
2546 FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2548 case FLAC__APODIZATION_GAUSS:
2549 FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2551 case FLAC__APODIZATION_HAMMING:
2552 FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2554 case FLAC__APODIZATION_HANN:
2555 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2557 case FLAC__APODIZATION_KAISER_BESSEL:
2558 FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2560 case FLAC__APODIZATION_NUTTALL:
2561 FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2563 case FLAC__APODIZATION_RECTANGLE:
2564 FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2566 case FLAC__APODIZATION_TRIANGLE:
2567 FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2569 case FLAC__APODIZATION_TUKEY:
2570 FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2572 case FLAC__APODIZATION_WELCH:
2573 FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2577 /* double protection */
2578 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2586 encoder->private_->input_capacity = new_blocksize;
2588 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2593 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2595 const FLAC__byte *buffer;
2598 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2600 if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2601 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2605 if(encoder->protected_->verify) {
2606 encoder->private_->verify.output.data = buffer;
2607 encoder->private_->verify.output.bytes = bytes;
2608 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2609 encoder->private_->verify.needs_magic_hack = true;
2612 if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2613 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2614 FLAC__bitwriter_clear(encoder->private_->frame);
2615 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2616 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2622 if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2623 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2624 FLAC__bitwriter_clear(encoder->private_->frame);
2625 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2629 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2630 FLAC__bitwriter_clear(encoder->private_->frame);
2633 encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2634 encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2640 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2642 FLAC__StreamEncoderWriteStatus status;
2643 FLAC__uint64 output_position = 0;
2645 /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2646 if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2647 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2648 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2652 * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2655 FLAC__MetadataType type = (buffer[0] & 0x7f);
2656 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2657 encoder->protected_->streaminfo_offset = output_position;
2658 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2659 encoder->protected_->seektable_offset = output_position;
2663 * Mark the current seek point if hit (if audio_offset == 0 that
2664 * means we're still writing metadata and haven't hit the first
2667 if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2668 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2669 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2670 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2671 FLAC__uint64 test_sample;
2673 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2674 test_sample = encoder->private_->seek_table->points[i].sample_number;
2675 if(test_sample > frame_last_sample) {
2678 else if(test_sample >= frame_first_sample) {
2679 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2680 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2681 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2682 encoder->private_->first_seekpoint_to_check++;
2683 /* DO NOT: "break;" and here's why:
2684 * The seektable template may contain more than one target
2685 * sample for any given frame; we will keep looping, generating
2686 * duplicate seekpoints for them, and we'll clean it up later,
2687 * just before writing the seektable back to the metadata.
2691 encoder->private_->first_seekpoint_to_check++;
2697 if(encoder->private_->is_ogg) {
2698 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2699 &encoder->protected_->ogg_encoder_aspect,
2703 encoder->private_->current_frame_number,
2705 (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2707 encoder->private_->client_data
2712 status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2714 if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2715 encoder->private_->bytes_written += bytes;
2716 encoder->private_->samples_written += samples;
2717 /* we keep a high watermark on the number of frames written because
2718 * when the encoder goes back to write metadata, 'current_frame'
2719 * will drop back to 0.
2721 encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2724 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2729 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2730 void update_metadata_(const FLAC__StreamEncoder *encoder)
2732 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2733 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2734 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2735 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2736 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2737 const unsigned bps = metadata->data.stream_info.bits_per_sample;
2738 FLAC__StreamEncoderSeekStatus seek_status;
2740 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2742 /* All this is based on intimate knowledge of the stream header
2743 * layout, but a change to the header format that would break this
2744 * would also break all streams encoded in the previous format.
2748 * Write MD5 signature
2751 const unsigned md5_offset =
2752 FLAC__STREAM_METADATA_HEADER_LENGTH +
2754 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2755 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2756 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2757 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2758 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2759 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2760 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2761 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2764 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2765 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2766 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2769 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2770 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2776 * Write total samples
2779 const unsigned total_samples_byte_offset =
2780 FLAC__STREAM_METADATA_HEADER_LENGTH +
2782 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2783 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2784 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2785 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2786 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2787 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2788 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2792 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2793 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2794 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2795 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2796 b[4] = (FLAC__byte)(samples & 0xFF);
2797 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) {
2798 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2799 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2802 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2803 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2809 * Write min/max framesize
2812 const unsigned min_framesize_offset =
2813 FLAC__STREAM_METADATA_HEADER_LENGTH +
2815 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2816 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2819 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2820 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2821 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2822 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2823 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2824 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2825 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) {
2826 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2827 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2830 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2831 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2839 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2842 FLAC__format_seektable_sort(encoder->private_->seek_table);
2844 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2846 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) {
2847 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2848 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2852 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2855 xx = encoder->private_->seek_table->points[i].sample_number;
2856 b[7] = (FLAC__byte)xx; xx >>= 8;
2857 b[6] = (FLAC__byte)xx; xx >>= 8;
2858 b[5] = (FLAC__byte)xx; xx >>= 8;
2859 b[4] = (FLAC__byte)xx; xx >>= 8;
2860 b[3] = (FLAC__byte)xx; xx >>= 8;
2861 b[2] = (FLAC__byte)xx; xx >>= 8;
2862 b[1] = (FLAC__byte)xx; xx >>= 8;
2863 b[0] = (FLAC__byte)xx; xx >>= 8;
2864 xx = encoder->private_->seek_table->points[i].stream_offset;
2865 b[15] = (FLAC__byte)xx; xx >>= 8;
2866 b[14] = (FLAC__byte)xx; xx >>= 8;
2867 b[13] = (FLAC__byte)xx; xx >>= 8;
2868 b[12] = (FLAC__byte)xx; xx >>= 8;
2869 b[11] = (FLAC__byte)xx; xx >>= 8;
2870 b[10] = (FLAC__byte)xx; xx >>= 8;
2871 b[9] = (FLAC__byte)xx; xx >>= 8;
2872 b[8] = (FLAC__byte)xx; xx >>= 8;
2873 x = encoder->private_->seek_table->points[i].frame_samples;
2874 b[17] = (FLAC__byte)x; x >>= 8;
2875 b[16] = (FLAC__byte)x; x >>= 8;
2876 if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2877 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2885 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2886 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2888 /* the # of bytes in the 1st packet that precede the STREAMINFO */
2889 static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2890 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2891 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2892 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2893 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2894 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2895 FLAC__STREAM_SYNC_LENGTH
2897 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2898 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2899 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2900 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2901 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2904 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2905 FLAC__ASSERT(0 != encoder->private_->seek_callback);
2907 /* Pre-check that client supports seeking, since we don't want the
2908 * ogg_helper code to ever have to deal with this condition.
2910 if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2913 /* All this is based on intimate knowledge of the stream header
2914 * layout, but a change to the header format that would break this
2915 * would also break all streams encoded in the previous format.
2919 ** Write STREAMINFO stats
2921 simple_ogg_page__init(&page);
2922 if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2923 simple_ogg_page__clear(&page);
2924 return; /* state already set */
2928 * Write MD5 signature
2931 const unsigned md5_offset =
2932 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2933 FLAC__STREAM_METADATA_HEADER_LENGTH +
2935 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2936 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2937 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2938 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2939 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2940 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2941 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2942 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2945 if(md5_offset + 16 > (unsigned)page.body_len) {
2946 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2947 simple_ogg_page__clear(&page);
2950 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2954 * Write total samples
2957 const unsigned total_samples_byte_offset =
2958 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2959 FLAC__STREAM_METADATA_HEADER_LENGTH +
2961 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2962 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2963 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2964 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2965 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2966 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2967 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2971 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2972 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2973 simple_ogg_page__clear(&page);
2976 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2977 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2978 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2979 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2980 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2981 b[4] = (FLAC__byte)(samples & 0xFF);
2982 memcpy(page.body + total_samples_byte_offset, b, 5);
2986 * Write min/max framesize
2989 const unsigned min_framesize_offset =
2990 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2991 FLAC__STREAM_METADATA_HEADER_LENGTH +
2993 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2994 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2997 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2998 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2999 simple_ogg_page__clear(&page);
3002 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
3003 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
3004 b[2] = (FLAC__byte)(min_framesize & 0xFF);
3005 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
3006 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
3007 b[5] = (FLAC__byte)(max_framesize & 0xFF);
3008 memcpy(page.body + min_framesize_offset, b, 6);
3010 if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
3011 simple_ogg_page__clear(&page);
3012 return; /* state already set */
3014 simple_ogg_page__clear(&page);
3019 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
3023 FLAC__format_seektable_sort(encoder->private_->seek_table);
3025 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
3027 simple_ogg_page__init(&page);
3028 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
3029 simple_ogg_page__clear(&page);
3030 return; /* state already set */
3033 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
3034 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
3035 simple_ogg_page__clear(&page);
3039 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
3042 xx = encoder->private_->seek_table->points[i].sample_number;
3043 b[7] = (FLAC__byte)xx; xx >>= 8;
3044 b[6] = (FLAC__byte)xx; xx >>= 8;
3045 b[5] = (FLAC__byte)xx; xx >>= 8;
3046 b[4] = (FLAC__byte)xx; xx >>= 8;
3047 b[3] = (FLAC__byte)xx; xx >>= 8;
3048 b[2] = (FLAC__byte)xx; xx >>= 8;
3049 b[1] = (FLAC__byte)xx; xx >>= 8;
3050 b[0] = (FLAC__byte)xx; xx >>= 8;
3051 xx = encoder->private_->seek_table->points[i].stream_offset;
3052 b[15] = (FLAC__byte)xx; xx >>= 8;
3053 b[14] = (FLAC__byte)xx; xx >>= 8;
3054 b[13] = (FLAC__byte)xx; xx >>= 8;
3055 b[12] = (FLAC__byte)xx; xx >>= 8;
3056 b[11] = (FLAC__byte)xx; xx >>= 8;
3057 b[10] = (FLAC__byte)xx; xx >>= 8;
3058 b[9] = (FLAC__byte)xx; xx >>= 8;
3059 b[8] = (FLAC__byte)xx; xx >>= 8;
3060 x = encoder->private_->seek_table->points[i].frame_samples;
3061 b[17] = (FLAC__byte)x; x >>= 8;
3062 b[16] = (FLAC__byte)x; x >>= 8;
3066 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
3067 simple_ogg_page__clear(&page);
3068 return; /* state already set */
3070 simple_ogg_page__clear(&page);
3075 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
3078 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
3081 * Accumulate raw signal to the MD5 signature
3083 if(!FLAC__MD5Accumulate(&encoder->private_->md5context, (const FLAC__int32 * const *)encoder->private_->integer_signal, encoder->protected_->channels, encoder->protected_->blocksize, (encoder->protected_->bits_per_sample+7) / 8)) {
3084 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3089 * Process the frame header and subframes into the frame bitbuffer
3091 if(!process_subframes_(encoder, is_fractional_block)) {
3092 /* the above function sets the state for us in case of an error */
3097 * Zero-pad the frame to a byte_boundary
3099 if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
3100 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3105 * CRC-16 the whole thing
3107 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
3109 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
3110 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
3112 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3119 if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
3120 /* the above function sets the state for us in case of an error */
3125 * Get ready for the next frame
3127 encoder->private_->current_sample_number = 0;
3128 encoder->private_->current_frame_number++;
3129 encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
3134 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
3136 FLAC__FrameHeader frame_header;
3137 unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
3138 FLAC__bool do_independent, do_mid_side;
3141 * Calculate the min,max Rice partition orders
3143 if(is_fractional_block) {
3144 max_partition_order = 0;
3147 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
3148 max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
3150 min_partition_order = min(min_partition_order, max_partition_order);
3155 frame_header.blocksize = encoder->protected_->blocksize;
3156 frame_header.sample_rate = encoder->protected_->sample_rate;
3157 frame_header.channels = encoder->protected_->channels;
3158 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
3159 frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
3160 frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
3161 frame_header.number.frame_number = encoder->private_->current_frame_number;
3164 * Figure out what channel assignments to try
3166 if(encoder->protected_->do_mid_side_stereo) {
3167 if(encoder->protected_->loose_mid_side_stereo) {
3168 if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
3169 do_independent = true;
3173 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
3174 do_mid_side = !do_independent;
3178 do_independent = true;
3183 do_independent = true;
3184 do_mid_side = false;
3187 FLAC__ASSERT(do_independent || do_mid_side);
3190 * Check for wasted bits; set effective bps for each subframe
3192 if(do_independent) {
3193 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3194 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
3195 encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
3196 encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
3200 FLAC__ASSERT(encoder->protected_->channels == 2);
3201 for(channel = 0; channel < 2; channel++) {
3202 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
3203 encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
3204 encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
3209 * First do a normal encoding pass of each independent channel
3211 if(do_independent) {
3212 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3216 min_partition_order,
3217 max_partition_order,
3219 encoder->private_->subframe_bps[channel],
3220 encoder->private_->integer_signal[channel],
3221 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3222 encoder->private_->real_signal[channel],
3224 encoder->private_->subframe_workspace_ptr[channel],
3225 encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3226 encoder->private_->residual_workspace[channel],
3227 encoder->private_->best_subframe+channel,
3228 encoder->private_->best_subframe_bits+channel
3236 * Now do mid and side channels if requested
3239 FLAC__ASSERT(encoder->protected_->channels == 2);
3241 for(channel = 0; channel < 2; channel++) {
3245 min_partition_order,
3246 max_partition_order,
3248 encoder->private_->subframe_bps_mid_side[channel],
3249 encoder->private_->integer_signal_mid_side[channel],
3250 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3251 encoder->private_->real_signal_mid_side[channel],
3253 encoder->private_->subframe_workspace_ptr_mid_side[channel],
3254 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3255 encoder->private_->residual_workspace_mid_side[channel],
3256 encoder->private_->best_subframe_mid_side+channel,
3257 encoder->private_->best_subframe_bits_mid_side+channel
3265 * Compose the frame bitbuffer
3268 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3269 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3270 FLAC__ChannelAssignment channel_assignment;
3272 FLAC__ASSERT(encoder->protected_->channels == 2);
3274 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3275 channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3278 unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3282 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3283 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
3284 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
3285 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
3286 FLAC__ASSERT(do_independent && do_mid_side);
3288 /* We have to figure out which channel assignent results in the smallest frame */
3289 bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
3290 bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
3291 bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
3292 bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3294 channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3295 min_bits = bits[channel_assignment];
3296 for(ca = 1; ca <= 3; ca++) {
3297 if(bits[ca] < min_bits) {
3298 min_bits = bits[ca];
3299 channel_assignment = (FLAC__ChannelAssignment)ca;
3304 frame_header.channel_assignment = channel_assignment;
3306 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3307 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3311 switch(channel_assignment) {
3312 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3313 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3314 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3316 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3317 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3318 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3320 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3321 left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3322 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3324 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3325 left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3326 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3332 switch(channel_assignment) {
3333 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3334 left_bps = encoder->private_->subframe_bps [0];
3335 right_bps = encoder->private_->subframe_bps [1];
3337 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3338 left_bps = encoder->private_->subframe_bps [0];
3339 right_bps = encoder->private_->subframe_bps_mid_side[1];
3341 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3342 left_bps = encoder->private_->subframe_bps_mid_side[1];
3343 right_bps = encoder->private_->subframe_bps [1];
3345 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3346 left_bps = encoder->private_->subframe_bps_mid_side[0];
3347 right_bps = encoder->private_->subframe_bps_mid_side[1];
3353 /* note that encoder_add_subframe_ sets the state for us in case of an error */
3354 if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3356 if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3360 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3361 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3365 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3366 if(!add_subframe_(encoder, frame_header.blocksize, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame)) {
3367 /* the above function sets the state for us in case of an error */
3373 if(encoder->protected_->loose_mid_side_stereo) {
3374 encoder->private_->loose_mid_side_stereo_frame_count++;
3375 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3376 encoder->private_->loose_mid_side_stereo_frame_count = 0;
3379 encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3384 FLAC__bool process_subframe_(
3385 FLAC__StreamEncoder *encoder,
3386 unsigned min_partition_order,
3387 unsigned max_partition_order,
3388 const FLAC__FrameHeader *frame_header,
3389 unsigned subframe_bps,
3390 const FLAC__int32 integer_signal[],
3391 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3392 const FLAC__real real_signal[],
3394 FLAC__Subframe *subframe[2],
3395 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3396 FLAC__int32 *residual[2],
3397 unsigned *best_subframe,
3401 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3402 FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3404 FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3406 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3407 FLAC__double lpc_residual_bits_per_sample;
3408 FLAC__real autoc[FLAC__MAX_LPC_ORDER+1]; /* WATCHOUT: the size is important even though encoder->protected_->max_lpc_order might be less; some asm routines need all the space */
3409 FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3410 unsigned min_lpc_order, max_lpc_order, lpc_order;
3411 unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3413 unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3414 unsigned rice_parameter;
3415 unsigned _candidate_bits, _best_bits;
3416 unsigned _best_subframe;
3418 FLAC__ASSERT(frame_header->blocksize > 0);
3420 /* verbatim subframe is the baseline against which we measure other compressed subframes */
3422 if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3423 _best_bits = UINT_MAX;
3425 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3427 if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3428 unsigned signal_is_constant = false;
3429 guess_fixed_order = encoder->private_->local_fixed_compute_best_predictor(integer_signal+FLAC__MAX_FIXED_ORDER, frame_header->blocksize-FLAC__MAX_FIXED_ORDER, fixed_residual_bits_per_sample);
3430 /* check for constant subframe */
3432 !encoder->private_->disable_constant_subframes &&
3433 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3434 fixed_residual_bits_per_sample[1] == 0.0
3436 fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3439 /* the above means it's possible all samples are the same value; now double-check it: */
3441 signal_is_constant = true;
3442 for(i = 1; i < frame_header->blocksize; i++) {
3443 if(integer_signal[0] != integer_signal[i]) {
3444 signal_is_constant = false;
3449 if(signal_is_constant) {
3450 _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3451 if(_candidate_bits < _best_bits) {
3452 _best_subframe = !_best_subframe;
3453 _best_bits = _candidate_bits;
3457 if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3459 if(encoder->protected_->do_exhaustive_model_search) {
3460 min_fixed_order = 0;
3461 max_fixed_order = FLAC__MAX_FIXED_ORDER;
3464 min_fixed_order = max_fixed_order = guess_fixed_order;
3466 if(max_fixed_order >= frame_header->blocksize)
3467 max_fixed_order = frame_header->blocksize - 1;
3468 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3469 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3470 if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3471 continue; /* don't even try */
3472 rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > 0.0)? (unsigned)(fixed_residual_bits_per_sample[fixed_order]+0.5) : 0; /* 0.5 is for rounding */
3474 if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3475 continue; /* don't even try */
3476 rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > FLAC__FP_ZERO)? (unsigned)FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]+FLAC__FP_ONE_HALF) : 0; /* 0.5 is for rounding */
3478 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3479 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3480 #ifdef DEBUG_VERBOSE
3481 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3483 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3486 evaluate_fixed_subframe_(
3489 residual[!_best_subframe],
3490 encoder->private_->abs_residual_partition_sums,
3491 encoder->private_->raw_bits_per_partition,
3492 frame_header->blocksize,
3496 min_partition_order,
3497 max_partition_order,
3498 encoder->protected_->do_escape_coding,
3499 encoder->protected_->rice_parameter_search_dist,
3500 subframe[!_best_subframe],
3501 partitioned_rice_contents[!_best_subframe]
3503 if(_candidate_bits < _best_bits) {
3504 _best_subframe = !_best_subframe;
3505 _best_bits = _candidate_bits;
3510 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3512 if(encoder->protected_->max_lpc_order > 0) {
3513 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3514 max_lpc_order = frame_header->blocksize-1;
3516 max_lpc_order = encoder->protected_->max_lpc_order;
3517 if(max_lpc_order > 0) {
3519 for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3520 FLAC__lpc_window_data(real_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3521 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3522 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3523 if(autoc[0] != 0.0) {
3524 FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3525 if(encoder->protected_->do_exhaustive_model_search) {
3529 const unsigned guess_lpc_order =
3530 FLAC__lpc_compute_best_order(
3533 frame_header->blocksize,
3535 encoder->protected_->do_qlp_coeff_prec_search?
3536 FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
3537 encoder->protected_->qlp_coeff_precision
3540 min_lpc_order = max_lpc_order = guess_lpc_order;
3542 if(max_lpc_order >= frame_header->blocksize)
3543 max_lpc_order = frame_header->blocksize - 1;
3544 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
3545 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
3546 if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
3547 continue; /* don't even try */
3548 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
3549 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3550 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3551 #ifdef DEBUG_VERBOSE
3552 fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3554 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3556 if(encoder->protected_->do_qlp_coeff_prec_search) {
3557 min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
3558 /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
3559 if(subframe_bps <= 17) {
3560 max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
3561 max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
3564 max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
3567 min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
3569 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
3571 evaluate_lpc_subframe_(
3574 residual[!_best_subframe],
3575 encoder->private_->abs_residual_partition_sums,
3576 encoder->private_->raw_bits_per_partition,
3577 encoder->private_->lp_coeff[lpc_order-1],
3578 frame_header->blocksize,
3581 qlp_coeff_precision,
3583 min_partition_order,
3584 max_partition_order,
3585 encoder->protected_->do_escape_coding,
3586 encoder->protected_->rice_parameter_search_dist,
3587 subframe[!_best_subframe],
3588 partitioned_rice_contents[!_best_subframe]
3590 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
3591 if(_candidate_bits < _best_bits) {
3592 _best_subframe = !_best_subframe;
3593 _best_bits = _candidate_bits;
3602 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3606 /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3607 if(_best_bits == UINT_MAX) {
3608 FLAC__ASSERT(_best_subframe == 0);
3609 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3612 *best_subframe = _best_subframe;
3613 *best_bits = _best_bits;
3618 FLAC__bool add_subframe_(
3619 FLAC__StreamEncoder *encoder,
3621 unsigned subframe_bps,
3622 const FLAC__Subframe *subframe,
3623 FLAC__BitWriter *frame
3626 switch(subframe->type) {
3627 case FLAC__SUBFRAME_TYPE_CONSTANT:
3628 if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3629 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3633 case FLAC__SUBFRAME_TYPE_FIXED:
3634 if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3635 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3639 case FLAC__SUBFRAME_TYPE_LPC:
3640 if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3641 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3645 case FLAC__SUBFRAME_TYPE_VERBATIM:
3646 if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3647 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3658 #define SPOTCHECK_ESTIMATE 0
3659 #if SPOTCHECK_ESTIMATE
3660 static void spotcheck_subframe_estimate_(
3661 FLAC__StreamEncoder *encoder,
3663 unsigned subframe_bps,
3664 const FLAC__Subframe *subframe,
3669 FLAC__BitWriter *frame = FLAC__bitwriter_new();
3671 fprintf(stderr, "EST: can't allocate frame\n");
3674 if(!FLAC__bitwriter_init(frame)) {
3675 fprintf(stderr, "EST: can't init frame\n");
3678 ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
3681 const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
3682 if(estimate != actual)
3683 fprintf(stderr, "EST: bad, frame#%u sub#%%d type=%8s est=%u, actual=%u, delta=%d\n", encoder->private_->current_frame_number, FLAC__SubframeTypeString[subframe->type], estimate, actual, (int)actual-(int)estimate);
3685 FLAC__bitwriter_delete(frame);
3689 unsigned evaluate_constant_subframe_(
3690 FLAC__StreamEncoder *encoder,
3691 const FLAC__int32 signal,
3693 unsigned subframe_bps,
3694 FLAC__Subframe *subframe
3698 subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3699 subframe->data.constant.value = signal;
3701 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
3703 #if SPOTCHECK_ESTIMATE
3704 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3706 (void)encoder, (void)blocksize;
3712 unsigned evaluate_fixed_subframe_(
3713 FLAC__StreamEncoder *encoder,
3714 const FLAC__int32 signal[],
3715 FLAC__int32 residual[],
3716 FLAC__uint64 abs_residual_partition_sums[],
3717 unsigned raw_bits_per_partition[],
3719 unsigned subframe_bps,
3721 unsigned rice_parameter,
3722 unsigned min_partition_order,
3723 unsigned max_partition_order,
3724 FLAC__bool do_escape_coding,
3725 unsigned rice_parameter_search_dist,
3726 FLAC__Subframe *subframe,
3727 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3730 unsigned i, residual_bits, estimate;
3731 const unsigned residual_samples = blocksize - order;
3733 FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3735 subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3737 subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3738 subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3739 subframe->data.fixed.residual = residual;
3742 find_best_partition_order_(
3745 abs_residual_partition_sums,
3746 raw_bits_per_partition,
3750 min_partition_order,
3751 max_partition_order,
3753 rice_parameter_search_dist,
3754 &subframe->data.fixed.entropy_coding_method.data.partitioned_rice
3757 subframe->data.fixed.order = order;
3758 for(i = 0; i < order; i++)
3759 subframe->data.fixed.warmup[i] = signal[i];
3761 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
3763 #if SPOTCHECK_ESTIMATE
3764 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3770 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3771 unsigned evaluate_lpc_subframe_(
3772 FLAC__StreamEncoder *encoder,
3773 const FLAC__int32 signal[],
3774 FLAC__int32 residual[],
3775 FLAC__uint64 abs_residual_partition_sums[],
3776 unsigned raw_bits_per_partition[],
3777 const FLAC__real lp_coeff[],
3779 unsigned subframe_bps,
3781 unsigned qlp_coeff_precision,
3782 unsigned rice_parameter,
3783 unsigned min_partition_order,
3784 unsigned max_partition_order,
3785 FLAC__bool do_escape_coding,
3786 unsigned rice_parameter_search_dist,
3787 FLAC__Subframe *subframe,
3788 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3791 FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
3792 unsigned i, residual_bits, estimate;
3793 int quantization, ret;
3794 const unsigned residual_samples = blocksize - order;
3796 /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3797 if(subframe_bps <= 16) {
3798 FLAC__ASSERT(order > 0);
3799 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3800 qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3803 ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3805 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3807 if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3808 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3809 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3811 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3813 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3815 subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3817 subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3818 subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3819 subframe->data.lpc.residual = residual;
3822 find_best_partition_order_(
3825 abs_residual_partition_sums,
3826 raw_bits_per_partition,
3830 min_partition_order,
3831 max_partition_order,
3833 rice_parameter_search_dist,
3834 &subframe->data.lpc.entropy_coding_method.data.partitioned_rice
3837 subframe->data.lpc.order = order;
3838 subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3839 subframe->data.lpc.quantization_level = quantization;
3840 memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3841 for(i = 0; i < order; i++)
3842 subframe->data.lpc.warmup[i] = signal[i];
3844 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits;
3846 #if SPOTCHECK_ESTIMATE
3847 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3854 unsigned evaluate_verbatim_subframe_(
3855 FLAC__StreamEncoder *encoder,
3856 const FLAC__int32 signal[],
3858 unsigned subframe_bps,
3859 FLAC__Subframe *subframe
3864 subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3866 subframe->data.verbatim.data = signal;
3868 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
3870 #if SPOTCHECK_ESTIMATE
3871 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3879 unsigned find_best_partition_order_(
3880 FLAC__StreamEncoderPrivate *private_,
3881 const FLAC__int32 residual[],
3882 FLAC__uint64 abs_residual_partition_sums[],
3883 unsigned raw_bits_per_partition[],
3884 unsigned residual_samples,
3885 unsigned predictor_order,
3886 unsigned rice_parameter,
3887 unsigned min_partition_order,
3888 unsigned max_partition_order,
3889 FLAC__bool do_escape_coding,
3890 unsigned rice_parameter_search_dist,
3891 FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
3894 unsigned residual_bits, best_residual_bits = 0;
3895 unsigned best_parameters_index = 0;
3896 const unsigned blocksize = residual_samples + predictor_order;
3898 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3899 min_partition_order = min(min_partition_order, max_partition_order);
3901 precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order);
3903 if(do_escape_coding)
3904 precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3907 int partition_order;
3910 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3912 set_partitioned_rice_(
3913 #ifdef EXACT_RICE_BITS_CALCULATION
3916 abs_residual_partition_sums+sum,
3917 raw_bits_per_partition+sum,
3921 rice_parameter_search_dist,
3922 (unsigned)partition_order,
3924 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3929 FLAC__ASSERT(best_residual_bits != 0);
3932 sum += 1u << partition_order;
3933 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3934 best_residual_bits = residual_bits;
3935 best_parameters_index = !best_parameters_index;
3936 best_partitioned_rice->order = partition_order;
3942 * We are allowed to de-const the pointer based on our special knowledge;
3943 * it is const to the outside world.
3946 FLAC__EntropyCodingMethod_PartitionedRiceContents* best_partitioned_rice_contents = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_partitioned_rice->contents;
3947 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(best_partitioned_rice_contents, max(6, best_partitioned_rice->order));
3948 memcpy(best_partitioned_rice_contents->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
3949 memcpy(best_partitioned_rice_contents->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
3952 return best_residual_bits;
3955 void precompute_partition_info_sums_(
3956 const FLAC__int32 residual[],
3957 FLAC__uint64 abs_residual_partition_sums[],
3958 unsigned residual_samples,
3959 unsigned predictor_order,
3960 unsigned min_partition_order,
3961 unsigned max_partition_order
3964 int partition_order;
3965 unsigned from_partition, to_partition = 0;
3966 const unsigned blocksize = residual_samples + predictor_order;
3968 /* first do max_partition_order */
3969 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3970 FLAC__uint64 abs_residual_partition_sum; /* OPT: can reasonably be FLAC__uint32 for bps <= 17 and maybe higher */
3971 unsigned partition, partition_sample, partition_samples, residual_sample;
3972 const unsigned partitions = 1u << partition_order;
3973 const unsigned default_partition_samples = blocksize >> partition_order;
3975 FLAC__ASSERT(default_partition_samples > predictor_order);
3977 for(partition = residual_sample = 0; partition < partitions; partition++) {
3978 partition_samples = default_partition_samples;
3980 partition_samples -= predictor_order;
3981 abs_residual_partition_sum = 0;
3982 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++, residual_sample++) {
3983 #if defined _MSC_VER
3984 /* OPT: abs() may be faster for some compilers */
3985 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3987 const FLAC__int32 r = residual[residual_sample];
3989 abs_residual_partition_sum -= r;
3991 abs_residual_partition_sum += r;
3994 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3996 to_partition = partitions;
4000 /* now merge partitions for lower orders */
4001 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
4004 const unsigned partitions = 1u << partition_order;
4005 for(i = 0; i < partitions; i++) {
4006 s = abs_residual_partition_sums[from_partition];
4008 abs_residual_partition_sums[to_partition] = s + abs_residual_partition_sums[from_partition];
4015 void precompute_partition_info_escapes_(
4016 const FLAC__int32 residual[],
4017 unsigned raw_bits_per_partition[],
4018 unsigned residual_samples,
4019 unsigned predictor_order,
4020 unsigned min_partition_order,
4021 unsigned max_partition_order
4024 int partition_order;
4025 unsigned from_partition, to_partition = 0;
4026 const unsigned blocksize = residual_samples + predictor_order;
4028 /* first do max_partition_order */
4029 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
4032 unsigned partition, partition_sample, partition_samples, residual_sample;
4033 const unsigned partitions = 1u << partition_order;
4034 const unsigned default_partition_samples = blocksize >> partition_order;
4036 FLAC__ASSERT(default_partition_samples > predictor_order);
4038 for(partition = residual_sample = 0; partition < partitions; partition++) {
4039 partition_samples = default_partition_samples;
4041 partition_samples -= predictor_order;
4043 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
4044 r = residual[residual_sample++];
4045 /* OPT: maybe faster: rmax |= r ^ (r>>31) */
4051 /* now we know all residual values are in the range [-rmax-1,rmax] */
4052 raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
4054 to_partition = partitions;
4055 break; /*@@@ yuck, should remove the 'for' loop instead */
4058 /* now merge partitions for lower orders */
4059 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
4062 const unsigned partitions = 1u << partition_order;
4063 for(i = 0; i < partitions; i++) {
4064 m = raw_bits_per_partition[from_partition];
4066 raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
4073 #ifdef EXACT_RICE_BITS_CALCULATION
4074 static __inline unsigned count_rice_bits_in_partition_(
4075 const unsigned rice_parameter,
4076 const unsigned partition_samples,
4077 const FLAC__int32 *residual
4080 unsigned i, partition_bits =
4081 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN +
4082 (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
4084 for(i = 0; i < partition_samples; i++)
4085 partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
4086 return partition_bits;
4089 static __inline unsigned count_rice_bits_in_partition_(
4090 const unsigned rice_parameter,
4091 const unsigned partition_samples,
4092 const FLAC__uint64 abs_residual_partition_sum
4096 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN +
4097 (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
4100 (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
4101 : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
4103 - (partition_samples >> 1)
4104 /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
4105 * The actual number of bits used is closer to the sum for all i in the partition of abs(residual[i])>>(rice_parameter-1)
4106 * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
4107 * So the subtraction term tries to guess how many extra bits were contributed.
4108 * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
4114 FLAC__bool set_partitioned_rice_(
4115 #ifdef EXACT_RICE_BITS_CALCULATION
4116 const FLAC__int32 residual[],
4118 const FLAC__uint64 abs_residual_partition_sums[],
4119 const unsigned raw_bits_per_partition[],
4120 const unsigned residual_samples,
4121 const unsigned predictor_order,
4122 const unsigned suggested_rice_parameter,
4123 const unsigned rice_parameter_search_dist,
4124 const unsigned partition_order,
4125 const FLAC__bool search_for_escapes,
4126 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
4130 unsigned rice_parameter, partition_bits;
4131 unsigned best_partition_bits, best_rice_parameter = 0;
4132 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
4133 unsigned *parameters, *raw_bits;
4134 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4135 unsigned min_rice_parameter, max_rice_parameter;
4137 (void)rice_parameter_search_dist;
4140 FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
4142 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
4143 parameters = partitioned_rice_contents->parameters;
4144 raw_bits = partitioned_rice_contents->raw_bits;
4146 if(partition_order == 0) {
4147 best_partition_bits = 0xffffffff;
4148 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4149 if(rice_parameter_search_dist) {
4150 if(suggested_rice_parameter < rice_parameter_search_dist)
4151 min_rice_parameter = 0;
4153 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
4154 max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
4155 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
4156 #ifdef DEBUG_VERBOSE
4157 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
4159 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
4163 min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
4165 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4167 rice_parameter = suggested_rice_parameter;
4169 #ifdef EXACT_RICE_BITS_CALCULATION
4170 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
4172 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
4174 if(partition_bits < best_partition_bits) {
4175 best_rice_parameter = rice_parameter;
4176 best_partition_bits = partition_bits;
4178 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4181 if(search_for_escapes) {
4182 partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[0] * residual_samples;
4183 if(partition_bits <= best_partition_bits) {
4184 raw_bits[0] = raw_bits_per_partition[0];
4185 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
4186 best_partition_bits = partition_bits;
4189 parameters[0] = best_rice_parameter;
4190 bits_ += best_partition_bits;
4193 unsigned partition, residual_sample;
4194 unsigned partition_samples;
4195 FLAC__uint64 mean, k;
4196 const unsigned partitions = 1u << partition_order;
4197 for(partition = residual_sample = 0; partition < partitions; partition++) {
4198 partition_samples = (residual_samples+predictor_order) >> partition_order;
4199 if(partition == 0) {
4200 if(partition_samples <= predictor_order)
4203 partition_samples -= predictor_order;
4205 mean = abs_residual_partition_sums[partition];
4206 /* we are basically calculating the size in bits of the
4207 * average residual magnitude in the partition:
4208 * rice_parameter = floor(log2(mean/partition_samples))
4209 * 'mean' is not a good name for the variable, it is
4210 * actually the sum of magnitudes of all residual values
4211 * in the partition, so the actual mean is
4212 * mean/partition_samples
4214 for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
4216 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
4217 #ifdef DEBUG_VERBOSE
4218 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
4220 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
4223 best_partition_bits = 0xffffffff;
4224 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4225 if(rice_parameter_search_dist) {
4226 if(rice_parameter < rice_parameter_search_dist)
4227 min_rice_parameter = 0;
4229 min_rice_parameter = rice_parameter - rice_parameter_search_dist;
4230 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
4231 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
4232 #ifdef DEBUG_VERBOSE
4233 fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
4235 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
4239 min_rice_parameter = max_rice_parameter = rice_parameter;
4241 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4243 #ifdef EXACT_RICE_BITS_CALCULATION
4244 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
4246 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
4248 if(partition_bits < best_partition_bits) {
4249 best_rice_parameter = rice_parameter;
4250 best_partition_bits = partition_bits;
4252 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4255 if(search_for_escapes) {
4256 partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[partition] * partition_samples;
4257 if(partition_bits <= best_partition_bits) {
4258 raw_bits[partition] = raw_bits_per_partition[partition];
4259 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
4260 best_partition_bits = partition_bits;
4263 parameters[partition] = best_rice_parameter;
4264 bits_ += best_partition_bits;
4265 residual_sample += partition_samples;
4273 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
4278 for(i = 0; i < samples && !(x&1); i++)
4285 for(shift = 0; !(x&1); shift++)
4290 for(i = 0; i < samples; i++)
4291 signal[i] >>= shift;
4297 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4301 for(channel = 0; channel < channels; channel++)
4302 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
4304 fifo->tail += wide_samples;
4306 FLAC__ASSERT(fifo->tail <= fifo->size);
4309 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4312 unsigned sample, wide_sample;
4313 unsigned tail = fifo->tail;
4315 sample = input_offset * channels;
4316 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
4317 for(channel = 0; channel < channels; channel++)
4318 fifo->data[channel][tail] = input[sample++];
4323 FLAC__ASSERT(fifo->tail <= fifo->size);
4326 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4328 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4329 const size_t encoded_bytes = encoder->private_->verify.output.bytes;
4332 if(encoder->private_->verify.needs_magic_hack) {
4333 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
4334 *bytes = FLAC__STREAM_SYNC_LENGTH;
4335 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
4336 encoder->private_->verify.needs_magic_hack = false;
4339 if(encoded_bytes == 0) {
4341 * If we get here, a FIFO underflow has occurred,
4342 * which means there is a bug somewhere.
4345 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
4347 else if(encoded_bytes < *bytes)
4348 *bytes = encoded_bytes;
4349 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
4350 encoder->private_->verify.output.data += *bytes;
4351 encoder->private_->verify.output.bytes -= *bytes;
4354 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
4357 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
4359 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
4361 const unsigned channels = frame->header.channels;
4362 const unsigned blocksize = frame->header.blocksize;
4363 const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
4367 for(channel = 0; channel < channels; channel++) {
4368 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
4369 unsigned i, sample = 0;
4370 FLAC__int32 expect = 0, got = 0;
4372 for(i = 0; i < blocksize; i++) {
4373 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
4375 expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
4376 got = (FLAC__int32)buffer[channel][i];
4380 FLAC__ASSERT(i < blocksize);
4381 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
4382 encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
4383 encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
4384 encoder->private_->verify.error_stats.channel = channel;
4385 encoder->private_->verify.error_stats.sample = sample;
4386 encoder->private_->verify.error_stats.expected = expect;
4387 encoder->private_->verify.error_stats.got = got;
4388 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
4389 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
4392 /* dequeue the frame from the fifo */
4393 encoder->private_->verify.input_fifo.tail -= blocksize;
4394 FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
4395 for(channel = 0; channel < channels; channel++)
4396 memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail * sizeof(encoder->private_->verify.input_fifo.data[0][0]));
4397 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4400 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4402 (void)decoder, (void)metadata, (void)client_data;
4405 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4407 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4408 (void)decoder, (void)status;
4409 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4412 FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4416 *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
4418 if (feof(encoder->private_->file))
4419 return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
4420 else if (ferror(encoder->private_->file))
4421 return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
4423 return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
4426 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4430 if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
4431 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4433 return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4436 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4442 offset = ftello(encoder->private_->file);
4445 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4448 *absolute_byte_offset = (FLAC__uint64)offset;
4449 return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4453 #ifdef FLAC__VALGRIND_TESTING
4454 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4456 size_t ret = fwrite(ptr, size, nmemb, stream);
4462 #define local__fwrite fwrite
4465 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
4467 (void)client_data, (void)current_frame;
4469 if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4470 FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
4472 /* We would like to be able to use 'samples > 0' in the
4473 * clause here but currently because of the nature of our
4474 * Ogg writing implementation, 'samples' is always 0 (see
4475 * ogg_encoder_aspect.c). The downside is extra progress
4478 encoder->private_->is_ogg? true :
4483 /* NOTE: We have to add +bytes, +samples, and +1 to the stats
4484 * because at this point in the callback chain, the stats
4485 * have not been updated. Only after we return and control
4486 * gets back to write_frame_() are the stats updated
4488 encoder->private_->progress_callback(encoder, encoder->private_->bytes_written+bytes, encoder->private_->samples_written+samples, encoder->private_->frames_written+(samples?1:0), encoder->private_->total_frames_estimate, encoder->private_->client_data);
4490 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4493 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4497 * This will forcibly set stdout to binary mode (for OSes that require it)
4499 FILE *get_binary_stdout_(void)
4501 /* if something breaks here it is probably due to the presence or
4502 * absence of an underscore before the identifiers 'setmode',
4503 * 'fileno', and/or 'O_BINARY'; check your system header files.
4505 #if defined _MSC_VER || defined __MINGW32__
4506 _setmode(_fileno(stdout), _O_BINARY);
4507 #elif defined __CYGWIN__
4508 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4509 setmode(_fileno(stdout), _O_BINARY);
4510 #elif defined __EMX__
4511 setmode(fileno(stdout), O_BINARY);