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
926 if(encoder->private_->cpuinfo.data.ia32.sse) {
927 if(encoder->protected_->max_lpc_order < 4)
928 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
929 else if(encoder->protected_->max_lpc_order < 8)
930 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
931 else if(encoder->protected_->max_lpc_order < 12)
932 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
934 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
936 else if(encoder->private_->cpuinfo.data.ia32._3dnow)
937 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
939 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
940 if(encoder->private_->cpuinfo.data.ia32.mmx) {
941 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
942 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
945 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
946 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
948 if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
949 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
950 # endif /* FLAC__HAS_NASM */
951 # endif /* FLAC__CPU_IA32 */
953 # endif /* !FLAC__NO_ASM */
954 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
955 /* finally override based on wide-ness if necessary */
956 if(encoder->private_->use_wide_by_block) {
957 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
960 /* set state to OK; from here on, errors are fatal and we'll override the state then */
961 encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
964 encoder->private_->is_ogg = is_ogg;
965 if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
966 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
967 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
971 encoder->private_->read_callback = read_callback;
972 encoder->private_->write_callback = write_callback;
973 encoder->private_->seek_callback = seek_callback;
974 encoder->private_->tell_callback = tell_callback;
975 encoder->private_->metadata_callback = metadata_callback;
976 encoder->private_->client_data = client_data;
978 if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
979 /* the above function sets the state for us in case of an error */
980 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
983 if(!FLAC__bitwriter_init(encoder->private_->frame)) {
984 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
985 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
989 * Set up the verify stuff if necessary
991 if(encoder->protected_->verify) {
993 * First, set up the fifo which will hold the
994 * original signal to compare against
996 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
997 for(i = 0; i < encoder->protected_->channels; i++) {
998 if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder->private_->verify.input_fifo.size))) {
999 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1000 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1003 encoder->private_->verify.input_fifo.tail = 0;
1006 * Now set up a stream decoder for verification
1008 encoder->private_->verify.decoder = FLAC__stream_decoder_new();
1009 if(0 == encoder->private_->verify.decoder) {
1010 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1011 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1014 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) {
1015 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1016 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1019 encoder->private_->verify.error_stats.absolute_sample = 0;
1020 encoder->private_->verify.error_stats.frame_number = 0;
1021 encoder->private_->verify.error_stats.channel = 0;
1022 encoder->private_->verify.error_stats.sample = 0;
1023 encoder->private_->verify.error_stats.expected = 0;
1024 encoder->private_->verify.error_stats.got = 0;
1027 * These must be done before we write any metadata, because that
1028 * calls the write_callback, which uses these values.
1030 encoder->private_->first_seekpoint_to_check = 0;
1031 encoder->private_->samples_written = 0;
1032 encoder->protected_->streaminfo_offset = 0;
1033 encoder->protected_->seektable_offset = 0;
1034 encoder->protected_->audio_offset = 0;
1037 * write the stream header
1039 if(encoder->protected_->verify)
1040 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1041 if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1042 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1043 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1045 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1046 /* the above function sets the state for us in case of an error */
1047 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1051 * write the STREAMINFO metadata block
1053 if(encoder->protected_->verify)
1054 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1055 encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1056 encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1057 encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1058 encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1059 encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1060 encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1061 encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1062 encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1063 encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1064 encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1065 encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1066 memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1067 FLAC__MD5Init(&encoder->private_->md5context);
1068 if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1069 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1070 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1072 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1073 /* the above function sets the state for us in case of an error */
1074 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1078 * Now that the STREAMINFO block is written, we can init this to an
1079 * absurdly-high value...
1081 encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1082 /* ... and clear this to 0 */
1083 encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1086 * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1087 * if not, we will write an empty one (FLAC__add_metadata_block()
1088 * automatically supplies the vendor string).
1090 * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1091 * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
1092 * true it will have already insured that the metadata list is properly
1095 if(!metadata_has_vorbis_comment) {
1096 FLAC__StreamMetadata vorbis_comment;
1097 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1098 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1099 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1100 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1101 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1102 vorbis_comment.data.vorbis_comment.num_comments = 0;
1103 vorbis_comment.data.vorbis_comment.comments = 0;
1104 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1105 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1106 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1108 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1109 /* the above function sets the state for us in case of an error */
1110 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1115 * write the user's metadata blocks
1117 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1118 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1119 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1120 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1121 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1123 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1124 /* the above function sets the state for us in case of an error */
1125 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1129 /* now that all the metadata is written, we save the stream offset */
1130 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 */
1131 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1132 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1135 if(encoder->protected_->verify)
1136 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1138 return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1141 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1142 FLAC__StreamEncoder *encoder,
1143 FLAC__StreamEncoderWriteCallback write_callback,
1144 FLAC__StreamEncoderSeekCallback seek_callback,
1145 FLAC__StreamEncoderTellCallback tell_callback,
1146 FLAC__StreamEncoderMetadataCallback metadata_callback,
1150 return init_stream_internal_(
1152 /*read_callback=*/0,
1162 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1163 FLAC__StreamEncoder *encoder,
1164 FLAC__StreamEncoderReadCallback read_callback,
1165 FLAC__StreamEncoderWriteCallback write_callback,
1166 FLAC__StreamEncoderSeekCallback seek_callback,
1167 FLAC__StreamEncoderTellCallback tell_callback,
1168 FLAC__StreamEncoderMetadataCallback metadata_callback,
1172 return init_stream_internal_(
1184 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1185 FLAC__StreamEncoder *encoder,
1187 FLAC__StreamEncoderProgressCallback progress_callback,
1192 FLAC__StreamEncoderInitStatus init_status;
1194 FLAC__ASSERT(0 != encoder);
1195 FLAC__ASSERT(0 != file);
1197 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1198 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1200 /* double protection */
1202 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1203 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1207 * To make sure that our file does not go unclosed after an error, we
1208 * must assign the FILE pointer before any further error can occur in
1212 file = get_binary_stdout_(); /* just to be safe */
1214 encoder->private_->file = file;
1216 encoder->private_->progress_callback = progress_callback;
1217 encoder->private_->bytes_written = 0;
1218 encoder->private_->samples_written = 0;
1219 encoder->private_->frames_written = 0;
1221 init_status = init_stream_internal_(
1223 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1224 file_write_callback_,
1225 encoder->private_->file == stdout? 0 : file_seek_callback_,
1226 encoder->private_->file == stdout? 0 : file_tell_callback_,
1227 /*metadata_callback=*/0,
1231 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1232 /* the above function sets the state for us in case of an error */
1237 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1239 FLAC__ASSERT(blocksize != 0);
1240 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1246 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1247 FLAC__StreamEncoder *encoder,
1249 FLAC__StreamEncoderProgressCallback progress_callback,
1253 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1256 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1257 FLAC__StreamEncoder *encoder,
1259 FLAC__StreamEncoderProgressCallback progress_callback,
1263 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1266 static FLAC__StreamEncoderInitStatus init_file_internal_(
1267 FLAC__StreamEncoder *encoder,
1268 const char *filename,
1269 FLAC__StreamEncoderProgressCallback progress_callback,
1276 FLAC__ASSERT(0 != encoder);
1279 * To make sure that our file does not go unclosed after an error, we
1280 * have to do the same entrance checks here that are later performed
1281 * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1283 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1284 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1286 file = filename? fopen(filename, "w+b") : stdout;
1289 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1290 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1293 return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1296 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1297 FLAC__StreamEncoder *encoder,
1298 const char *filename,
1299 FLAC__StreamEncoderProgressCallback progress_callback,
1303 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1306 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1307 FLAC__StreamEncoder *encoder,
1308 const char *filename,
1309 FLAC__StreamEncoderProgressCallback progress_callback,
1313 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1316 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1318 FLAC__bool error = false;
1320 FLAC__ASSERT(0 != encoder);
1321 FLAC__ASSERT(0 != encoder->private_);
1322 FLAC__ASSERT(0 != encoder->protected_);
1324 if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1327 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1328 if(encoder->private_->current_sample_number != 0) {
1329 const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1330 encoder->protected_->blocksize = encoder->private_->current_sample_number;
1331 if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1336 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1338 if(!encoder->private_->is_being_deleted) {
1339 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1340 if(encoder->private_->seek_callback) {
1342 if(encoder->private_->is_ogg)
1343 update_ogg_metadata_(encoder);
1346 update_metadata_(encoder);
1348 /* check if an error occurred while updating metadata */
1349 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1352 if(encoder->private_->metadata_callback)
1353 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1356 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1358 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1363 if(0 != encoder->private_->file) {
1364 if(encoder->private_->file != stdout)
1365 fclose(encoder->private_->file);
1366 encoder->private_->file = 0;
1370 if(encoder->private_->is_ogg)
1371 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1375 set_defaults_(encoder);
1378 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1383 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1385 FLAC__ASSERT(0 != encoder);
1386 FLAC__ASSERT(0 != encoder->private_);
1387 FLAC__ASSERT(0 != encoder->protected_);
1388 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1391 /* can't check encoder->private_->is_ogg since that's not set until init time */
1392 FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1400 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1402 FLAC__ASSERT(0 != encoder);
1403 FLAC__ASSERT(0 != encoder->private_);
1404 FLAC__ASSERT(0 != encoder->protected_);
1405 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1407 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1408 encoder->protected_->verify = value;
1413 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1415 FLAC__ASSERT(0 != encoder);
1416 FLAC__ASSERT(0 != encoder->private_);
1417 FLAC__ASSERT(0 != encoder->protected_);
1418 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1420 encoder->protected_->streamable_subset = value;
1424 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1426 FLAC__ASSERT(0 != encoder);
1427 FLAC__ASSERT(0 != encoder->private_);
1428 FLAC__ASSERT(0 != encoder->protected_);
1429 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1431 encoder->protected_->channels = value;
1435 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1437 FLAC__ASSERT(0 != encoder);
1438 FLAC__ASSERT(0 != encoder->private_);
1439 FLAC__ASSERT(0 != encoder->protected_);
1440 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1442 encoder->protected_->bits_per_sample = value;
1446 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1448 FLAC__ASSERT(0 != encoder);
1449 FLAC__ASSERT(0 != encoder->private_);
1450 FLAC__ASSERT(0 != encoder->protected_);
1451 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1453 encoder->protected_->sample_rate = value;
1457 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1459 FLAC__bool ok = true;
1460 FLAC__ASSERT(0 != encoder);
1461 FLAC__ASSERT(0 != encoder->private_);
1462 FLAC__ASSERT(0 != encoder->protected_);
1463 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1465 if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1466 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1467 ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
1468 ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
1471 ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
1472 /* but it's too hard to specify the string in a locale-specific way */
1474 encoder->protected_->num_apodizations = 1;
1475 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1476 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1478 ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
1479 ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
1480 ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1481 ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
1482 ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
1483 ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1484 ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1485 ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
1489 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1491 FLAC__ASSERT(0 != encoder);
1492 FLAC__ASSERT(0 != encoder->private_);
1493 FLAC__ASSERT(0 != encoder->protected_);
1494 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1496 encoder->protected_->blocksize = value;
1500 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1502 FLAC__ASSERT(0 != encoder);
1503 FLAC__ASSERT(0 != encoder->private_);
1504 FLAC__ASSERT(0 != encoder->protected_);
1505 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1507 encoder->protected_->do_mid_side_stereo = value;
1511 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1513 FLAC__ASSERT(0 != encoder);
1514 FLAC__ASSERT(0 != encoder->private_);
1515 FLAC__ASSERT(0 != encoder->protected_);
1516 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1518 encoder->protected_->loose_mid_side_stereo = value;
1522 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1524 FLAC__ASSERT(0 != encoder);
1525 FLAC__ASSERT(0 != encoder->private_);
1526 FLAC__ASSERT(0 != encoder->protected_);
1527 FLAC__ASSERT(0 != specification);
1528 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1530 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1531 (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1533 encoder->protected_->num_apodizations = 0;
1535 const char *s = strchr(specification, ';');
1536 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1537 if (n==8 && 0 == strncmp("bartlett" , specification, n))
1538 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1539 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1540 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1541 else if(n==8 && 0 == strncmp("blackman" , specification, n))
1542 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1543 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1544 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1545 else if(n==6 && 0 == strncmp("connes" , specification, n))
1546 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1547 else if(n==7 && 0 == strncmp("flattop" , specification, n))
1548 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1549 else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
1550 FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1551 if (stddev > 0.0 && stddev <= 0.5) {
1552 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1553 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1556 else if(n==7 && 0 == strncmp("hamming" , specification, n))
1557 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1558 else if(n==4 && 0 == strncmp("hann" , specification, n))
1559 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1560 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1561 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1562 else if(n==7 && 0 == strncmp("nuttall" , specification, n))
1563 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1564 else if(n==9 && 0 == strncmp("rectangle" , specification, n))
1565 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1566 else if(n==8 && 0 == strncmp("triangle" , specification, n))
1567 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1568 else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
1569 FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1570 if (p >= 0.0 && p <= 1.0) {
1571 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1572 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1575 else if(n==5 && 0 == strncmp("welch" , specification, n))
1576 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1577 if (encoder->protected_->num_apodizations == 32)
1580 specification = s+1;
1584 if(encoder->protected_->num_apodizations == 0) {
1585 encoder->protected_->num_apodizations = 1;
1586 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1587 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1593 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1595 FLAC__ASSERT(0 != encoder);
1596 FLAC__ASSERT(0 != encoder->private_);
1597 FLAC__ASSERT(0 != encoder->protected_);
1598 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1600 encoder->protected_->max_lpc_order = value;
1604 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1606 FLAC__ASSERT(0 != encoder);
1607 FLAC__ASSERT(0 != encoder->private_);
1608 FLAC__ASSERT(0 != encoder->protected_);
1609 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1611 encoder->protected_->qlp_coeff_precision = value;
1615 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1617 FLAC__ASSERT(0 != encoder);
1618 FLAC__ASSERT(0 != encoder->private_);
1619 FLAC__ASSERT(0 != encoder->protected_);
1620 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1622 encoder->protected_->do_qlp_coeff_prec_search = value;
1626 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1628 FLAC__ASSERT(0 != encoder);
1629 FLAC__ASSERT(0 != encoder->private_);
1630 FLAC__ASSERT(0 != encoder->protected_);
1631 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1634 /*@@@ deprecated: */
1635 encoder->protected_->do_escape_coding = value;
1642 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1644 FLAC__ASSERT(0 != encoder);
1645 FLAC__ASSERT(0 != encoder->private_);
1646 FLAC__ASSERT(0 != encoder->protected_);
1647 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1649 encoder->protected_->do_exhaustive_model_search = value;
1653 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1655 FLAC__ASSERT(0 != encoder);
1656 FLAC__ASSERT(0 != encoder->private_);
1657 FLAC__ASSERT(0 != encoder->protected_);
1658 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1660 encoder->protected_->min_residual_partition_order = value;
1664 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1666 FLAC__ASSERT(0 != encoder);
1667 FLAC__ASSERT(0 != encoder->private_);
1668 FLAC__ASSERT(0 != encoder->protected_);
1669 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1671 encoder->protected_->max_residual_partition_order = value;
1675 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1677 FLAC__ASSERT(0 != encoder);
1678 FLAC__ASSERT(0 != encoder->private_);
1679 FLAC__ASSERT(0 != encoder->protected_);
1680 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1683 /*@@@ deprecated: */
1684 encoder->protected_->rice_parameter_search_dist = value;
1691 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1693 FLAC__ASSERT(0 != encoder);
1694 FLAC__ASSERT(0 != encoder->private_);
1695 FLAC__ASSERT(0 != encoder->protected_);
1696 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1698 encoder->protected_->total_samples_estimate = value;
1702 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1704 FLAC__ASSERT(0 != encoder);
1705 FLAC__ASSERT(0 != encoder->private_);
1706 FLAC__ASSERT(0 != encoder->protected_);
1707 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1713 /* realloc() does not do exactly what we want so... */
1714 if(encoder->protected_->metadata) {
1715 free(encoder->protected_->metadata);
1716 encoder->protected_->metadata = 0;
1717 encoder->protected_->num_metadata_blocks = 0;
1720 FLAC__StreamMetadata **m;
1721 if(0 == (m = (FLAC__StreamMetadata**)malloc(sizeof(m[0]) * num_blocks)))
1723 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1724 encoder->protected_->metadata = m;
1725 encoder->protected_->num_metadata_blocks = num_blocks;
1728 if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1735 * These three functions are not static, but not publically exposed in
1736 * include/FLAC/ either. They are used by the test suite.
1738 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1740 FLAC__ASSERT(0 != encoder);
1741 FLAC__ASSERT(0 != encoder->private_);
1742 FLAC__ASSERT(0 != encoder->protected_);
1743 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1745 encoder->private_->disable_constant_subframes = value;
1749 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1751 FLAC__ASSERT(0 != encoder);
1752 FLAC__ASSERT(0 != encoder->private_);
1753 FLAC__ASSERT(0 != encoder->protected_);
1754 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1756 encoder->private_->disable_fixed_subframes = value;
1760 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1762 FLAC__ASSERT(0 != encoder);
1763 FLAC__ASSERT(0 != encoder->private_);
1764 FLAC__ASSERT(0 != encoder->protected_);
1765 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1767 encoder->private_->disable_verbatim_subframes = value;
1771 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1773 FLAC__ASSERT(0 != encoder);
1774 FLAC__ASSERT(0 != encoder->private_);
1775 FLAC__ASSERT(0 != encoder->protected_);
1776 return encoder->protected_->state;
1779 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1781 FLAC__ASSERT(0 != encoder);
1782 FLAC__ASSERT(0 != encoder->private_);
1783 FLAC__ASSERT(0 != encoder->protected_);
1784 if(encoder->protected_->verify)
1785 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1787 return FLAC__STREAM_DECODER_UNINITIALIZED;
1790 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1792 FLAC__ASSERT(0 != encoder);
1793 FLAC__ASSERT(0 != encoder->private_);
1794 FLAC__ASSERT(0 != encoder->protected_);
1795 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1796 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1798 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1801 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)
1803 FLAC__ASSERT(0 != encoder);
1804 FLAC__ASSERT(0 != encoder->private_);
1805 FLAC__ASSERT(0 != encoder->protected_);
1806 if(0 != absolute_sample)
1807 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1808 if(0 != frame_number)
1809 *frame_number = encoder->private_->verify.error_stats.frame_number;
1811 *channel = encoder->private_->verify.error_stats.channel;
1813 *sample = encoder->private_->verify.error_stats.sample;
1815 *expected = encoder->private_->verify.error_stats.expected;
1817 *got = encoder->private_->verify.error_stats.got;
1820 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1822 FLAC__ASSERT(0 != encoder);
1823 FLAC__ASSERT(0 != encoder->private_);
1824 FLAC__ASSERT(0 != encoder->protected_);
1825 return encoder->protected_->verify;
1828 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1830 FLAC__ASSERT(0 != encoder);
1831 FLAC__ASSERT(0 != encoder->private_);
1832 FLAC__ASSERT(0 != encoder->protected_);
1833 return encoder->protected_->streamable_subset;
1836 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1838 FLAC__ASSERT(0 != encoder);
1839 FLAC__ASSERT(0 != encoder->private_);
1840 FLAC__ASSERT(0 != encoder->protected_);
1841 return encoder->protected_->channels;
1844 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1846 FLAC__ASSERT(0 != encoder);
1847 FLAC__ASSERT(0 != encoder->private_);
1848 FLAC__ASSERT(0 != encoder->protected_);
1849 return encoder->protected_->bits_per_sample;
1852 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1854 FLAC__ASSERT(0 != encoder);
1855 FLAC__ASSERT(0 != encoder->private_);
1856 FLAC__ASSERT(0 != encoder->protected_);
1857 return encoder->protected_->sample_rate;
1860 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1862 FLAC__ASSERT(0 != encoder);
1863 FLAC__ASSERT(0 != encoder->private_);
1864 FLAC__ASSERT(0 != encoder->protected_);
1865 return encoder->protected_->blocksize;
1868 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1870 FLAC__ASSERT(0 != encoder);
1871 FLAC__ASSERT(0 != encoder->private_);
1872 FLAC__ASSERT(0 != encoder->protected_);
1873 return encoder->protected_->do_mid_side_stereo;
1876 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1878 FLAC__ASSERT(0 != encoder);
1879 FLAC__ASSERT(0 != encoder->private_);
1880 FLAC__ASSERT(0 != encoder->protected_);
1881 return encoder->protected_->loose_mid_side_stereo;
1884 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1886 FLAC__ASSERT(0 != encoder);
1887 FLAC__ASSERT(0 != encoder->private_);
1888 FLAC__ASSERT(0 != encoder->protected_);
1889 return encoder->protected_->max_lpc_order;
1892 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1894 FLAC__ASSERT(0 != encoder);
1895 FLAC__ASSERT(0 != encoder->private_);
1896 FLAC__ASSERT(0 != encoder->protected_);
1897 return encoder->protected_->qlp_coeff_precision;
1900 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1902 FLAC__ASSERT(0 != encoder);
1903 FLAC__ASSERT(0 != encoder->private_);
1904 FLAC__ASSERT(0 != encoder->protected_);
1905 return encoder->protected_->do_qlp_coeff_prec_search;
1908 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1910 FLAC__ASSERT(0 != encoder);
1911 FLAC__ASSERT(0 != encoder->private_);
1912 FLAC__ASSERT(0 != encoder->protected_);
1913 return encoder->protected_->do_escape_coding;
1916 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1918 FLAC__ASSERT(0 != encoder);
1919 FLAC__ASSERT(0 != encoder->private_);
1920 FLAC__ASSERT(0 != encoder->protected_);
1921 return encoder->protected_->do_exhaustive_model_search;
1924 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1926 FLAC__ASSERT(0 != encoder);
1927 FLAC__ASSERT(0 != encoder->private_);
1928 FLAC__ASSERT(0 != encoder->protected_);
1929 return encoder->protected_->min_residual_partition_order;
1932 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1934 FLAC__ASSERT(0 != encoder);
1935 FLAC__ASSERT(0 != encoder->private_);
1936 FLAC__ASSERT(0 != encoder->protected_);
1937 return encoder->protected_->max_residual_partition_order;
1940 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1942 FLAC__ASSERT(0 != encoder);
1943 FLAC__ASSERT(0 != encoder->private_);
1944 FLAC__ASSERT(0 != encoder->protected_);
1945 return encoder->protected_->rice_parameter_search_dist;
1948 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1950 FLAC__ASSERT(0 != encoder);
1951 FLAC__ASSERT(0 != encoder->private_);
1952 FLAC__ASSERT(0 != encoder->protected_);
1953 return encoder->protected_->total_samples_estimate;
1956 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1958 unsigned i, j, channel;
1959 FLAC__int32 x, mid, side;
1960 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1962 FLAC__ASSERT(0 != encoder);
1963 FLAC__ASSERT(0 != encoder->private_);
1964 FLAC__ASSERT(0 != encoder->protected_);
1965 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1969 * we have several flavors of the same basic loop, optimized for
1970 * different conditions:
1972 if(encoder->protected_->max_lpc_order > 0) {
1973 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1975 * stereo coding: unroll channel loop
1976 * with LPC: calculate floating point version of signal
1979 if(encoder->protected_->verify)
1980 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
1982 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
1983 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1984 x = mid = side = buffer[0][j];
1985 encoder->private_->integer_signal[0][i] = x;
1986 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1987 encoder->private_->real_signal[0][i] = (FLAC__real)x;
1990 encoder->private_->integer_signal[1][i] = x;
1991 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1992 encoder->private_->real_signal[1][i] = (FLAC__real)x;
1996 mid >>= 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
1997 encoder->private_->integer_signal_mid_side[1][i] = side;
1998 encoder->private_->integer_signal_mid_side[0][i] = mid;
1999 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2000 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
2001 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
2003 encoder->private_->current_sample_number++;
2005 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2007 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2009 /* move unprocessed overread samples to beginnings of arrays */
2010 FLAC__ASSERT(i == blocksize+OVERREAD_);
2011 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2013 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2014 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2015 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2016 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2017 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2018 encoder->private_->real_signal[0][0] = encoder->private_->real_signal[0][i];
2019 encoder->private_->real_signal[1][0] = encoder->private_->real_signal[1][i];
2020 encoder->private_->real_signal_mid_side[0][0] = encoder->private_->real_signal_mid_side[0][i];
2021 encoder->private_->real_signal_mid_side[1][0] = encoder->private_->real_signal_mid_side[1][i];
2023 encoder->private_->current_sample_number = 1;
2025 } while(j < samples);
2029 * independent channel coding: buffer each channel in inner loop
2030 * with LPC: calculate floating point version of signal
2033 if(encoder->protected_->verify)
2034 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2036 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2037 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2038 for(channel = 0; channel < channels; channel++) {
2039 x = buffer[channel][j];
2040 encoder->private_->integer_signal[channel][i] = x;
2041 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2042 encoder->private_->real_signal[channel][i] = (FLAC__real)x;
2045 encoder->private_->current_sample_number++;
2047 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2049 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2051 /* move unprocessed overread samples to beginnings of arrays */
2052 FLAC__ASSERT(i == blocksize+OVERREAD_);
2053 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2055 for(channel = 0; channel < channels; channel++) {
2056 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2057 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2058 encoder->private_->real_signal[channel][0] = encoder->private_->real_signal[channel][i];
2061 encoder->private_->current_sample_number = 1;
2063 } while(j < samples);
2067 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2069 * stereo coding: unroll channel loop
2070 * without LPC: no need to calculate floating point version of signal
2073 if(encoder->protected_->verify)
2074 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2076 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2077 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2078 encoder->private_->integer_signal[0][i] = mid = side = buffer[0][j];
2080 encoder->private_->integer_signal[1][i] = x;
2083 mid >>= 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
2084 encoder->private_->integer_signal_mid_side[1][i] = side;
2085 encoder->private_->integer_signal_mid_side[0][i] = mid;
2086 encoder->private_->current_sample_number++;
2088 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2090 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2092 /* move unprocessed overread samples to beginnings of arrays */
2093 FLAC__ASSERT(i == blocksize+OVERREAD_);
2094 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2096 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2097 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2098 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2099 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2100 encoder->private_->current_sample_number = 1;
2102 } while(j < samples);
2106 * independent channel coding: buffer each channel in inner loop
2107 * without LPC: no need to calculate floating point version of signal
2110 if(encoder->protected_->verify)
2111 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2113 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2114 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2115 for(channel = 0; channel < channels; channel++)
2116 encoder->private_->integer_signal[channel][i] = buffer[channel][j];
2117 encoder->private_->current_sample_number++;
2119 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2121 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2123 /* move unprocessed overread samples to beginnings of arrays */
2124 FLAC__ASSERT(i == blocksize+OVERREAD_);
2125 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2127 for(channel = 0; channel < channels; channel++)
2128 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2129 encoder->private_->current_sample_number = 1;
2131 } while(j < samples);
2138 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2140 unsigned i, j, k, channel;
2141 FLAC__int32 x, mid, side;
2142 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2144 FLAC__ASSERT(0 != encoder);
2145 FLAC__ASSERT(0 != encoder->private_);
2146 FLAC__ASSERT(0 != encoder->protected_);
2147 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2151 * we have several flavors of the same basic loop, optimized for
2152 * different conditions:
2154 if(encoder->protected_->max_lpc_order > 0) {
2155 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2157 * stereo coding: unroll channel loop
2158 * with LPC: calculate floating point version of signal
2161 if(encoder->protected_->verify)
2162 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2164 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2165 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2166 x = mid = side = buffer[k++];
2167 encoder->private_->integer_signal[0][i] = x;
2168 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2169 encoder->private_->real_signal[0][i] = (FLAC__real)x;
2172 encoder->private_->integer_signal[1][i] = x;
2173 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2174 encoder->private_->real_signal[1][i] = (FLAC__real)x;
2178 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2179 encoder->private_->integer_signal_mid_side[1][i] = side;
2180 encoder->private_->integer_signal_mid_side[0][i] = mid;
2181 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2182 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
2183 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
2185 encoder->private_->current_sample_number++;
2187 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2189 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2191 /* move unprocessed overread samples to beginnings of arrays */
2192 FLAC__ASSERT(i == blocksize+OVERREAD_);
2193 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2195 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2196 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2197 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2198 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2199 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2200 encoder->private_->real_signal[0][0] = encoder->private_->real_signal[0][i];
2201 encoder->private_->real_signal[1][0] = encoder->private_->real_signal[1][i];
2202 encoder->private_->real_signal_mid_side[0][0] = encoder->private_->real_signal_mid_side[0][i];
2203 encoder->private_->real_signal_mid_side[1][0] = encoder->private_->real_signal_mid_side[1][i];
2205 encoder->private_->current_sample_number = 1;
2207 } while(j < samples);
2211 * independent channel coding: buffer each channel in inner loop
2212 * with LPC: calculate floating point version of signal
2215 if(encoder->protected_->verify)
2216 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2218 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2219 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2220 for(channel = 0; channel < channels; channel++) {
2222 encoder->private_->integer_signal[channel][i] = x;
2223 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2224 encoder->private_->real_signal[channel][i] = (FLAC__real)x;
2227 encoder->private_->current_sample_number++;
2229 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2231 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2233 /* move unprocessed overread samples to beginnings of arrays */
2234 FLAC__ASSERT(i == blocksize+OVERREAD_);
2235 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2237 for(channel = 0; channel < channels; channel++) {
2238 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2239 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2240 encoder->private_->real_signal[channel][0] = encoder->private_->real_signal[channel][i];
2243 encoder->private_->current_sample_number = 1;
2245 } while(j < samples);
2249 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2251 * stereo coding: unroll channel loop
2252 * without LPC: no need to calculate floating point version of signal
2255 if(encoder->protected_->verify)
2256 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2258 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2259 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2260 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2262 encoder->private_->integer_signal[1][i] = x;
2265 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2266 encoder->private_->integer_signal_mid_side[1][i] = side;
2267 encoder->private_->integer_signal_mid_side[0][i] = mid;
2268 encoder->private_->current_sample_number++;
2270 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2272 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2274 /* move unprocessed overread samples to beginnings of arrays */
2275 FLAC__ASSERT(i == blocksize+OVERREAD_);
2276 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2278 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2279 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2280 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2281 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2282 encoder->private_->current_sample_number = 1;
2284 } while(j < samples);
2288 * independent channel coding: buffer each channel in inner loop
2289 * without LPC: no need to calculate floating point version of signal
2292 if(encoder->protected_->verify)
2293 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2295 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2296 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2297 for(channel = 0; channel < channels; channel++)
2298 encoder->private_->integer_signal[channel][i] = buffer[k++];
2299 encoder->private_->current_sample_number++;
2301 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2303 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2305 /* move unprocessed overread samples to beginnings of arrays */
2306 FLAC__ASSERT(i == blocksize+OVERREAD_);
2307 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2309 for(channel = 0; channel < channels; channel++)
2310 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2311 encoder->private_->current_sample_number = 1;
2313 } while(j < samples);
2320 /***********************************************************************
2322 * Private class methods
2324 ***********************************************************************/
2326 void set_defaults_(FLAC__StreamEncoder *encoder)
2328 FLAC__ASSERT(0 != encoder);
2330 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2331 encoder->protected_->verify = true;
2333 encoder->protected_->verify = false;
2335 encoder->protected_->streamable_subset = true;
2336 encoder->protected_->do_mid_side_stereo = false;
2337 encoder->protected_->loose_mid_side_stereo = false;
2338 encoder->protected_->channels = 2;
2339 encoder->protected_->bits_per_sample = 16;
2340 encoder->protected_->sample_rate = 44100;
2341 encoder->protected_->blocksize = 0;
2342 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2343 encoder->protected_->num_apodizations = 1;
2344 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2345 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2347 encoder->protected_->max_lpc_order = 0;
2348 encoder->protected_->qlp_coeff_precision = 0;
2349 encoder->protected_->do_qlp_coeff_prec_search = false;
2350 encoder->protected_->do_exhaustive_model_search = false;
2351 encoder->protected_->do_escape_coding = false;
2352 encoder->protected_->min_residual_partition_order = 0;
2353 encoder->protected_->max_residual_partition_order = 0;
2354 encoder->protected_->rice_parameter_search_dist = 0;
2355 encoder->protected_->total_samples_estimate = 0;
2356 encoder->protected_->metadata = 0;
2357 encoder->protected_->num_metadata_blocks = 0;
2359 encoder->private_->seek_table = 0;
2360 encoder->private_->disable_constant_subframes = false;
2361 encoder->private_->disable_fixed_subframes = false;
2362 encoder->private_->disable_verbatim_subframes = false;
2364 encoder->private_->is_ogg = false;
2366 encoder->private_->read_callback = 0;
2367 encoder->private_->write_callback = 0;
2368 encoder->private_->seek_callback = 0;
2369 encoder->private_->tell_callback = 0;
2370 encoder->private_->metadata_callback = 0;
2371 encoder->private_->progress_callback = 0;
2372 encoder->private_->client_data = 0;
2375 FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2379 void free_(FLAC__StreamEncoder *encoder)
2381 unsigned i, channel;
2383 FLAC__ASSERT(0 != encoder);
2384 if(encoder->protected_->metadata) {
2385 free(encoder->protected_->metadata);
2386 encoder->protected_->metadata = 0;
2387 encoder->protected_->num_metadata_blocks = 0;
2389 for(i = 0; i < encoder->protected_->channels; i++) {
2390 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2391 free(encoder->private_->integer_signal_unaligned[i]);
2392 encoder->private_->integer_signal_unaligned[i] = 0;
2394 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2395 if(0 != encoder->private_->real_signal_unaligned[i]) {
2396 free(encoder->private_->real_signal_unaligned[i]);
2397 encoder->private_->real_signal_unaligned[i] = 0;
2401 for(i = 0; i < 2; i++) {
2402 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2403 free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2404 encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2406 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2407 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2408 free(encoder->private_->real_signal_mid_side_unaligned[i]);
2409 encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2413 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2414 for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2415 if(0 != encoder->private_->window_unaligned[i]) {
2416 free(encoder->private_->window_unaligned[i]);
2417 encoder->private_->window_unaligned[i] = 0;
2420 if(0 != encoder->private_->windowed_signal_unaligned) {
2421 free(encoder->private_->windowed_signal_unaligned);
2422 encoder->private_->windowed_signal_unaligned = 0;
2425 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2426 for(i = 0; i < 2; i++) {
2427 if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2428 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2429 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2433 for(channel = 0; channel < 2; channel++) {
2434 for(i = 0; i < 2; i++) {
2435 if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2436 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2437 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2441 if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2442 free(encoder->private_->abs_residual_partition_sums_unaligned);
2443 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2445 if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2446 free(encoder->private_->raw_bits_per_partition_unaligned);
2447 encoder->private_->raw_bits_per_partition_unaligned = 0;
2449 if(encoder->protected_->verify) {
2450 for(i = 0; i < encoder->protected_->channels; i++) {
2451 if(0 != encoder->private_->verify.input_fifo.data[i]) {
2452 free(encoder->private_->verify.input_fifo.data[i]);
2453 encoder->private_->verify.input_fifo.data[i] = 0;
2457 FLAC__bitwriter_free(encoder->private_->frame);
2460 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2463 unsigned i, channel;
2465 FLAC__ASSERT(new_blocksize > 0);
2466 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2467 FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2469 /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2470 if(new_blocksize <= encoder->private_->input_capacity)
2475 /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
2476 * requires that the input arrays (in our case the integer signals)
2477 * have a buffer of up to 3 zeroes in front (at negative indices) for
2478 * alignment purposes; we use 4 in front to keep the data well-aligned.
2481 for(i = 0; ok && i < encoder->protected_->channels; i++) {
2482 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2483 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2484 encoder->private_->integer_signal[i] += 4;
2485 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2486 if(encoder->protected_->max_lpc_order > 0)
2487 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2490 for(i = 0; ok && i < 2; i++) {
2491 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]);
2492 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2493 encoder->private_->integer_signal_mid_side[i] += 4;
2494 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2495 if(encoder->protected_->max_lpc_order > 0)
2496 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]);
2499 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2500 if(ok && encoder->protected_->max_lpc_order > 0) {
2501 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2502 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2503 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2506 for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2507 for(i = 0; ok && i < 2; i++) {
2508 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2511 for(channel = 0; ok && channel < 2; channel++) {
2512 for(i = 0; ok && i < 2; i++) {
2513 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]);
2516 /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2517 /*@@@ 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) */
2518 ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2519 if(encoder->protected_->do_escape_coding)
2520 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2522 /* now adjust the windows if the blocksize has changed */
2523 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2524 if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2525 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2526 switch(encoder->protected_->apodizations[i].type) {
2527 case FLAC__APODIZATION_BARTLETT:
2528 FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2530 case FLAC__APODIZATION_BARTLETT_HANN:
2531 FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2533 case FLAC__APODIZATION_BLACKMAN:
2534 FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2536 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2537 FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2539 case FLAC__APODIZATION_CONNES:
2540 FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2542 case FLAC__APODIZATION_FLATTOP:
2543 FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2545 case FLAC__APODIZATION_GAUSS:
2546 FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2548 case FLAC__APODIZATION_HAMMING:
2549 FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2551 case FLAC__APODIZATION_HANN:
2552 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2554 case FLAC__APODIZATION_KAISER_BESSEL:
2555 FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2557 case FLAC__APODIZATION_NUTTALL:
2558 FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2560 case FLAC__APODIZATION_RECTANGLE:
2561 FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2563 case FLAC__APODIZATION_TRIANGLE:
2564 FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2566 case FLAC__APODIZATION_TUKEY:
2567 FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2569 case FLAC__APODIZATION_WELCH:
2570 FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2574 /* double protection */
2575 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2583 encoder->private_->input_capacity = new_blocksize;
2585 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2590 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2592 const FLAC__byte *buffer;
2595 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2597 if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2598 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2602 if(encoder->protected_->verify) {
2603 encoder->private_->verify.output.data = buffer;
2604 encoder->private_->verify.output.bytes = bytes;
2605 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2606 encoder->private_->verify.needs_magic_hack = true;
2609 if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2610 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2611 FLAC__bitwriter_clear(encoder->private_->frame);
2612 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2613 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2619 if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2620 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2621 FLAC__bitwriter_clear(encoder->private_->frame);
2622 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2626 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2627 FLAC__bitwriter_clear(encoder->private_->frame);
2630 encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2631 encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2637 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2639 FLAC__StreamEncoderWriteStatus status;
2640 FLAC__uint64 output_position = 0;
2642 /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2643 if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2644 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2645 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2649 * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2652 FLAC__MetadataType type = (buffer[0] & 0x7f);
2653 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2654 encoder->protected_->streaminfo_offset = output_position;
2655 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2656 encoder->protected_->seektable_offset = output_position;
2660 * Mark the current seek point if hit (if audio_offset == 0 that
2661 * means we're still writing metadata and haven't hit the first
2664 if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2665 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2666 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2667 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2668 FLAC__uint64 test_sample;
2670 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2671 test_sample = encoder->private_->seek_table->points[i].sample_number;
2672 if(test_sample > frame_last_sample) {
2675 else if(test_sample >= frame_first_sample) {
2676 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2677 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2678 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2679 encoder->private_->first_seekpoint_to_check++;
2680 /* DO NOT: "break;" and here's why:
2681 * The seektable template may contain more than one target
2682 * sample for any given frame; we will keep looping, generating
2683 * duplicate seekpoints for them, and we'll clean it up later,
2684 * just before writing the seektable back to the metadata.
2688 encoder->private_->first_seekpoint_to_check++;
2694 if(encoder->private_->is_ogg) {
2695 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2696 &encoder->protected_->ogg_encoder_aspect,
2700 encoder->private_->current_frame_number,
2702 (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2704 encoder->private_->client_data
2709 status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2711 if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2712 encoder->private_->bytes_written += bytes;
2713 encoder->private_->samples_written += samples;
2714 /* we keep a high watermark on the number of frames written because
2715 * when the encoder goes back to write metadata, 'current_frame'
2716 * will drop back to 0.
2718 encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2721 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2726 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2727 void update_metadata_(const FLAC__StreamEncoder *encoder)
2729 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2730 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2731 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2732 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2733 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2734 const unsigned bps = metadata->data.stream_info.bits_per_sample;
2735 FLAC__StreamEncoderSeekStatus seek_status;
2737 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2739 /* All this is based on intimate knowledge of the stream header
2740 * layout, but a change to the header format that would break this
2741 * would also break all streams encoded in the previous format.
2745 * Write MD5 signature
2748 const unsigned md5_offset =
2749 FLAC__STREAM_METADATA_HEADER_LENGTH +
2751 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2752 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2753 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2754 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2755 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2756 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2757 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2758 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2761 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2762 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2763 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2766 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2767 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2773 * Write total samples
2776 const unsigned total_samples_byte_offset =
2777 FLAC__STREAM_METADATA_HEADER_LENGTH +
2779 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2780 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2781 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2782 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2783 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2784 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2785 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2789 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2790 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2791 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2792 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2793 b[4] = (FLAC__byte)(samples & 0xFF);
2794 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) {
2795 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2796 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2799 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2800 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2806 * Write min/max framesize
2809 const unsigned min_framesize_offset =
2810 FLAC__STREAM_METADATA_HEADER_LENGTH +
2812 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2813 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2816 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2817 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2818 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2819 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2820 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2821 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2822 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) {
2823 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2824 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2827 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2828 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2836 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2839 FLAC__format_seektable_sort(encoder->private_->seek_table);
2841 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2843 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) {
2844 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2845 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2849 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2852 xx = encoder->private_->seek_table->points[i].sample_number;
2853 b[7] = (FLAC__byte)xx; xx >>= 8;
2854 b[6] = (FLAC__byte)xx; xx >>= 8;
2855 b[5] = (FLAC__byte)xx; xx >>= 8;
2856 b[4] = (FLAC__byte)xx; xx >>= 8;
2857 b[3] = (FLAC__byte)xx; xx >>= 8;
2858 b[2] = (FLAC__byte)xx; xx >>= 8;
2859 b[1] = (FLAC__byte)xx; xx >>= 8;
2860 b[0] = (FLAC__byte)xx; xx >>= 8;
2861 xx = encoder->private_->seek_table->points[i].stream_offset;
2862 b[15] = (FLAC__byte)xx; xx >>= 8;
2863 b[14] = (FLAC__byte)xx; xx >>= 8;
2864 b[13] = (FLAC__byte)xx; xx >>= 8;
2865 b[12] = (FLAC__byte)xx; xx >>= 8;
2866 b[11] = (FLAC__byte)xx; xx >>= 8;
2867 b[10] = (FLAC__byte)xx; xx >>= 8;
2868 b[9] = (FLAC__byte)xx; xx >>= 8;
2869 b[8] = (FLAC__byte)xx; xx >>= 8;
2870 x = encoder->private_->seek_table->points[i].frame_samples;
2871 b[17] = (FLAC__byte)x; x >>= 8;
2872 b[16] = (FLAC__byte)x; x >>= 8;
2873 if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2874 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2882 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2883 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2885 /* the # of bytes in the 1st packet that precede the STREAMINFO */
2886 static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2887 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2888 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2889 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2890 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2891 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2892 FLAC__STREAM_SYNC_LENGTH
2894 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2895 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2896 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2897 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2898 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2901 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2902 FLAC__ASSERT(0 != encoder->private_->seek_callback);
2904 /* Pre-check that client supports seeking, since we don't want the
2905 * ogg_helper code to ever have to deal with this condition.
2907 if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2910 /* All this is based on intimate knowledge of the stream header
2911 * layout, but a change to the header format that would break this
2912 * would also break all streams encoded in the previous format.
2916 ** Write STREAMINFO stats
2918 simple_ogg_page__init(&page);
2919 if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2920 simple_ogg_page__clear(&page);
2921 return; /* state already set */
2925 * Write MD5 signature
2928 const unsigned md5_offset =
2929 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2930 FLAC__STREAM_METADATA_HEADER_LENGTH +
2932 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2933 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2934 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2935 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2936 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2937 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2938 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2939 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2942 if(md5_offset + 16 > (unsigned)page.body_len) {
2943 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2944 simple_ogg_page__clear(&page);
2947 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2951 * Write total samples
2954 const unsigned total_samples_byte_offset =
2955 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2956 FLAC__STREAM_METADATA_HEADER_LENGTH +
2958 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2959 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2960 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2961 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2962 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2963 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2964 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2968 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2969 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2970 simple_ogg_page__clear(&page);
2973 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2974 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2975 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2976 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2977 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2978 b[4] = (FLAC__byte)(samples & 0xFF);
2979 memcpy(page.body + total_samples_byte_offset, b, 5);
2983 * Write min/max framesize
2986 const unsigned min_framesize_offset =
2987 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2988 FLAC__STREAM_METADATA_HEADER_LENGTH +
2990 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2991 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2994 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2995 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2996 simple_ogg_page__clear(&page);
2999 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
3000 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
3001 b[2] = (FLAC__byte)(min_framesize & 0xFF);
3002 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
3003 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
3004 b[5] = (FLAC__byte)(max_framesize & 0xFF);
3005 memcpy(page.body + min_framesize_offset, b, 6);
3007 if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
3008 simple_ogg_page__clear(&page);
3009 return; /* state already set */
3011 simple_ogg_page__clear(&page);
3016 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
3020 FLAC__format_seektable_sort(encoder->private_->seek_table);
3022 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
3024 simple_ogg_page__init(&page);
3025 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
3026 simple_ogg_page__clear(&page);
3027 return; /* state already set */
3030 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
3031 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
3032 simple_ogg_page__clear(&page);
3036 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
3039 xx = encoder->private_->seek_table->points[i].sample_number;
3040 b[7] = (FLAC__byte)xx; xx >>= 8;
3041 b[6] = (FLAC__byte)xx; xx >>= 8;
3042 b[5] = (FLAC__byte)xx; xx >>= 8;
3043 b[4] = (FLAC__byte)xx; xx >>= 8;
3044 b[3] = (FLAC__byte)xx; xx >>= 8;
3045 b[2] = (FLAC__byte)xx; xx >>= 8;
3046 b[1] = (FLAC__byte)xx; xx >>= 8;
3047 b[0] = (FLAC__byte)xx; xx >>= 8;
3048 xx = encoder->private_->seek_table->points[i].stream_offset;
3049 b[15] = (FLAC__byte)xx; xx >>= 8;
3050 b[14] = (FLAC__byte)xx; xx >>= 8;
3051 b[13] = (FLAC__byte)xx; xx >>= 8;
3052 b[12] = (FLAC__byte)xx; xx >>= 8;
3053 b[11] = (FLAC__byte)xx; xx >>= 8;
3054 b[10] = (FLAC__byte)xx; xx >>= 8;
3055 b[9] = (FLAC__byte)xx; xx >>= 8;
3056 b[8] = (FLAC__byte)xx; xx >>= 8;
3057 x = encoder->private_->seek_table->points[i].frame_samples;
3058 b[17] = (FLAC__byte)x; x >>= 8;
3059 b[16] = (FLAC__byte)x; x >>= 8;
3063 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
3064 simple_ogg_page__clear(&page);
3065 return; /* state already set */
3067 simple_ogg_page__clear(&page);
3072 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
3075 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
3078 * Accumulate raw signal to the MD5 signature
3080 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)) {
3081 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3086 * Process the frame header and subframes into the frame bitbuffer
3088 if(!process_subframes_(encoder, is_fractional_block)) {
3089 /* the above function sets the state for us in case of an error */
3094 * Zero-pad the frame to a byte_boundary
3096 if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
3097 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3102 * CRC-16 the whole thing
3104 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
3106 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
3107 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
3109 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3116 if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
3117 /* the above function sets the state for us in case of an error */
3122 * Get ready for the next frame
3124 encoder->private_->current_sample_number = 0;
3125 encoder->private_->current_frame_number++;
3126 encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
3131 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
3133 FLAC__FrameHeader frame_header;
3134 unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
3135 FLAC__bool do_independent, do_mid_side;
3138 * Calculate the min,max Rice partition orders
3140 if(is_fractional_block) {
3141 max_partition_order = 0;
3144 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
3145 max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
3147 min_partition_order = min(min_partition_order, max_partition_order);
3152 frame_header.blocksize = encoder->protected_->blocksize;
3153 frame_header.sample_rate = encoder->protected_->sample_rate;
3154 frame_header.channels = encoder->protected_->channels;
3155 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
3156 frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
3157 frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
3158 frame_header.number.frame_number = encoder->private_->current_frame_number;
3161 * Figure out what channel assignments to try
3163 if(encoder->protected_->do_mid_side_stereo) {
3164 if(encoder->protected_->loose_mid_side_stereo) {
3165 if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
3166 do_independent = true;
3170 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
3171 do_mid_side = !do_independent;
3175 do_independent = true;
3180 do_independent = true;
3181 do_mid_side = false;
3184 FLAC__ASSERT(do_independent || do_mid_side);
3187 * Check for wasted bits; set effective bps for each subframe
3189 if(do_independent) {
3190 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3191 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
3192 encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
3193 encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
3197 FLAC__ASSERT(encoder->protected_->channels == 2);
3198 for(channel = 0; channel < 2; channel++) {
3199 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
3200 encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
3201 encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
3206 * First do a normal encoding pass of each independent channel
3208 if(do_independent) {
3209 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3213 min_partition_order,
3214 max_partition_order,
3216 encoder->private_->subframe_bps[channel],
3217 encoder->private_->integer_signal[channel],
3218 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3219 encoder->private_->real_signal[channel],
3221 encoder->private_->subframe_workspace_ptr[channel],
3222 encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3223 encoder->private_->residual_workspace[channel],
3224 encoder->private_->best_subframe+channel,
3225 encoder->private_->best_subframe_bits+channel
3233 * Now do mid and side channels if requested
3236 FLAC__ASSERT(encoder->protected_->channels == 2);
3238 for(channel = 0; channel < 2; channel++) {
3242 min_partition_order,
3243 max_partition_order,
3245 encoder->private_->subframe_bps_mid_side[channel],
3246 encoder->private_->integer_signal_mid_side[channel],
3247 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3248 encoder->private_->real_signal_mid_side[channel],
3250 encoder->private_->subframe_workspace_ptr_mid_side[channel],
3251 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3252 encoder->private_->residual_workspace_mid_side[channel],
3253 encoder->private_->best_subframe_mid_side+channel,
3254 encoder->private_->best_subframe_bits_mid_side+channel
3262 * Compose the frame bitbuffer
3265 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3266 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3267 FLAC__ChannelAssignment channel_assignment;
3269 FLAC__ASSERT(encoder->protected_->channels == 2);
3271 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3272 channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3275 unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3279 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3280 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
3281 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
3282 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
3283 FLAC__ASSERT(do_independent && do_mid_side);
3285 /* We have to figure out which channel assignent results in the smallest frame */
3286 bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
3287 bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
3288 bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
3289 bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3291 channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3292 min_bits = bits[channel_assignment];
3293 for(ca = 1; ca <= 3; ca++) {
3294 if(bits[ca] < min_bits) {
3295 min_bits = bits[ca];
3296 channel_assignment = (FLAC__ChannelAssignment)ca;
3301 frame_header.channel_assignment = channel_assignment;
3303 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3304 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3308 switch(channel_assignment) {
3309 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3310 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3311 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3313 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3314 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3315 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3317 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3318 left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3319 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3321 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3322 left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3323 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3329 switch(channel_assignment) {
3330 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3331 left_bps = encoder->private_->subframe_bps [0];
3332 right_bps = encoder->private_->subframe_bps [1];
3334 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3335 left_bps = encoder->private_->subframe_bps [0];
3336 right_bps = encoder->private_->subframe_bps_mid_side[1];
3338 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3339 left_bps = encoder->private_->subframe_bps_mid_side[1];
3340 right_bps = encoder->private_->subframe_bps [1];
3342 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3343 left_bps = encoder->private_->subframe_bps_mid_side[0];
3344 right_bps = encoder->private_->subframe_bps_mid_side[1];
3350 /* note that encoder_add_subframe_ sets the state for us in case of an error */
3351 if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3353 if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3357 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3358 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3362 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3363 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)) {
3364 /* the above function sets the state for us in case of an error */
3370 if(encoder->protected_->loose_mid_side_stereo) {
3371 encoder->private_->loose_mid_side_stereo_frame_count++;
3372 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3373 encoder->private_->loose_mid_side_stereo_frame_count = 0;
3376 encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3381 FLAC__bool process_subframe_(
3382 FLAC__StreamEncoder *encoder,
3383 unsigned min_partition_order,
3384 unsigned max_partition_order,
3385 const FLAC__FrameHeader *frame_header,
3386 unsigned subframe_bps,
3387 const FLAC__int32 integer_signal[],
3388 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3389 const FLAC__real real_signal[],
3391 FLAC__Subframe *subframe[2],
3392 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3393 FLAC__int32 *residual[2],
3394 unsigned *best_subframe,
3398 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3399 FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3401 FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3403 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3404 FLAC__double lpc_residual_bits_per_sample;
3405 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 */
3406 FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3407 unsigned min_lpc_order, max_lpc_order, lpc_order;
3408 unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3410 unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3411 unsigned rice_parameter;
3412 unsigned _candidate_bits, _best_bits;
3413 unsigned _best_subframe;
3415 FLAC__ASSERT(frame_header->blocksize > 0);
3417 /* verbatim subframe is the baseline against which we measure other compressed subframes */
3419 if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3420 _best_bits = UINT_MAX;
3422 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3424 if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3425 unsigned signal_is_constant = false;
3426 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);
3427 /* check for constant subframe */
3429 !encoder->private_->disable_constant_subframes &&
3430 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3431 fixed_residual_bits_per_sample[1] == 0.0
3433 fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3436 /* the above means it's possible all samples are the same value; now double-check it: */
3438 signal_is_constant = true;
3439 for(i = 1; i < frame_header->blocksize; i++) {
3440 if(integer_signal[0] != integer_signal[i]) {
3441 signal_is_constant = false;
3446 if(signal_is_constant) {
3447 _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3448 if(_candidate_bits < _best_bits) {
3449 _best_subframe = !_best_subframe;
3450 _best_bits = _candidate_bits;
3454 if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3456 if(encoder->protected_->do_exhaustive_model_search) {
3457 min_fixed_order = 0;
3458 max_fixed_order = FLAC__MAX_FIXED_ORDER;
3461 min_fixed_order = max_fixed_order = guess_fixed_order;
3463 if(max_fixed_order >= frame_header->blocksize)
3464 max_fixed_order = frame_header->blocksize - 1;
3465 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3466 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3467 if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3468 continue; /* don't even try */
3469 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 */
3471 if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3472 continue; /* don't even try */
3473 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 */
3475 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3476 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3477 #ifdef DEBUG_VERBOSE
3478 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3480 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3483 evaluate_fixed_subframe_(
3486 residual[!_best_subframe],
3487 encoder->private_->abs_residual_partition_sums,
3488 encoder->private_->raw_bits_per_partition,
3489 frame_header->blocksize,
3493 min_partition_order,
3494 max_partition_order,
3495 encoder->protected_->do_escape_coding,
3496 encoder->protected_->rice_parameter_search_dist,
3497 subframe[!_best_subframe],
3498 partitioned_rice_contents[!_best_subframe]
3500 if(_candidate_bits < _best_bits) {
3501 _best_subframe = !_best_subframe;
3502 _best_bits = _candidate_bits;
3507 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3509 if(encoder->protected_->max_lpc_order > 0) {
3510 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3511 max_lpc_order = frame_header->blocksize-1;
3513 max_lpc_order = encoder->protected_->max_lpc_order;
3514 if(max_lpc_order > 0) {
3516 for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3517 FLAC__lpc_window_data(real_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3518 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3519 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3520 if(autoc[0] != 0.0) {
3521 FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3522 if(encoder->protected_->do_exhaustive_model_search) {
3526 const unsigned guess_lpc_order =
3527 FLAC__lpc_compute_best_order(
3530 frame_header->blocksize,
3532 encoder->protected_->do_qlp_coeff_prec_search?
3533 FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
3534 encoder->protected_->qlp_coeff_precision
3537 min_lpc_order = max_lpc_order = guess_lpc_order;
3539 if(max_lpc_order >= frame_header->blocksize)
3540 max_lpc_order = frame_header->blocksize - 1;
3541 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
3542 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
3543 if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
3544 continue; /* don't even try */
3545 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
3546 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3547 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3548 #ifdef DEBUG_VERBOSE
3549 fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3551 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3553 if(encoder->protected_->do_qlp_coeff_prec_search) {
3554 min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
3555 /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
3556 if(subframe_bps <= 17) {
3557 max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
3558 max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
3561 max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
3564 min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
3566 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
3568 evaluate_lpc_subframe_(
3571 residual[!_best_subframe],
3572 encoder->private_->abs_residual_partition_sums,
3573 encoder->private_->raw_bits_per_partition,
3574 encoder->private_->lp_coeff[lpc_order-1],
3575 frame_header->blocksize,
3578 qlp_coeff_precision,
3580 min_partition_order,
3581 max_partition_order,
3582 encoder->protected_->do_escape_coding,
3583 encoder->protected_->rice_parameter_search_dist,
3584 subframe[!_best_subframe],
3585 partitioned_rice_contents[!_best_subframe]
3587 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
3588 if(_candidate_bits < _best_bits) {
3589 _best_subframe = !_best_subframe;
3590 _best_bits = _candidate_bits;
3599 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3603 /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3604 if(_best_bits == UINT_MAX) {
3605 FLAC__ASSERT(_best_subframe == 0);
3606 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3609 *best_subframe = _best_subframe;
3610 *best_bits = _best_bits;
3615 FLAC__bool add_subframe_(
3616 FLAC__StreamEncoder *encoder,
3618 unsigned subframe_bps,
3619 const FLAC__Subframe *subframe,
3620 FLAC__BitWriter *frame
3623 switch(subframe->type) {
3624 case FLAC__SUBFRAME_TYPE_CONSTANT:
3625 if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3626 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3630 case FLAC__SUBFRAME_TYPE_FIXED:
3631 if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3632 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3636 case FLAC__SUBFRAME_TYPE_LPC:
3637 if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3638 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3642 case FLAC__SUBFRAME_TYPE_VERBATIM:
3643 if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3644 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3655 #define SPOTCHECK_ESTIMATE 0
3656 #if SPOTCHECK_ESTIMATE
3657 static void spotcheck_subframe_estimate_(
3658 FLAC__StreamEncoder *encoder,
3660 unsigned subframe_bps,
3661 const FLAC__Subframe *subframe,
3666 FLAC__BitWriter *frame = FLAC__bitwriter_new();
3668 fprintf(stderr, "EST: can't allocate frame\n");
3671 if(!FLAC__bitwriter_init(frame)) {
3672 fprintf(stderr, "EST: can't init frame\n");
3675 ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
3678 const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
3679 if(estimate != actual)
3680 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);
3682 FLAC__bitwriter_delete(frame);
3686 unsigned evaluate_constant_subframe_(
3687 FLAC__StreamEncoder *encoder,
3688 const FLAC__int32 signal,
3690 unsigned subframe_bps,
3691 FLAC__Subframe *subframe
3695 subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3696 subframe->data.constant.value = signal;
3698 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
3700 #if SPOTCHECK_ESTIMATE
3701 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3703 (void)encoder, (void)blocksize;
3709 unsigned evaluate_fixed_subframe_(
3710 FLAC__StreamEncoder *encoder,
3711 const FLAC__int32 signal[],
3712 FLAC__int32 residual[],
3713 FLAC__uint64 abs_residual_partition_sums[],
3714 unsigned raw_bits_per_partition[],
3716 unsigned subframe_bps,
3718 unsigned rice_parameter,
3719 unsigned min_partition_order,
3720 unsigned max_partition_order,
3721 FLAC__bool do_escape_coding,
3722 unsigned rice_parameter_search_dist,
3723 FLAC__Subframe *subframe,
3724 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3727 unsigned i, residual_bits, estimate;
3728 const unsigned residual_samples = blocksize - order;
3730 FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3732 subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3734 subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3735 subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3736 subframe->data.fixed.residual = residual;
3739 find_best_partition_order_(
3742 abs_residual_partition_sums,
3743 raw_bits_per_partition,
3747 min_partition_order,
3748 max_partition_order,
3750 rice_parameter_search_dist,
3751 &subframe->data.fixed.entropy_coding_method.data.partitioned_rice
3754 subframe->data.fixed.order = order;
3755 for(i = 0; i < order; i++)
3756 subframe->data.fixed.warmup[i] = signal[i];
3758 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
3760 #if SPOTCHECK_ESTIMATE
3761 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3767 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3768 unsigned evaluate_lpc_subframe_(
3769 FLAC__StreamEncoder *encoder,
3770 const FLAC__int32 signal[],
3771 FLAC__int32 residual[],
3772 FLAC__uint64 abs_residual_partition_sums[],
3773 unsigned raw_bits_per_partition[],
3774 const FLAC__real lp_coeff[],
3776 unsigned subframe_bps,
3778 unsigned qlp_coeff_precision,
3779 unsigned rice_parameter,
3780 unsigned min_partition_order,
3781 unsigned max_partition_order,
3782 FLAC__bool do_escape_coding,
3783 unsigned rice_parameter_search_dist,
3784 FLAC__Subframe *subframe,
3785 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3788 FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
3789 unsigned i, residual_bits, estimate;
3790 int quantization, ret;
3791 const unsigned residual_samples = blocksize - order;
3793 /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3794 if(subframe_bps <= 16) {
3795 FLAC__ASSERT(order > 0);
3796 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3797 qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3800 ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3802 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3804 if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3805 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3806 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3808 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3810 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3812 subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3814 subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3815 subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3816 subframe->data.lpc.residual = residual;
3819 find_best_partition_order_(
3822 abs_residual_partition_sums,
3823 raw_bits_per_partition,
3827 min_partition_order,
3828 max_partition_order,
3830 rice_parameter_search_dist,
3831 &subframe->data.lpc.entropy_coding_method.data.partitioned_rice
3834 subframe->data.lpc.order = order;
3835 subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3836 subframe->data.lpc.quantization_level = quantization;
3837 memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3838 for(i = 0; i < order; i++)
3839 subframe->data.lpc.warmup[i] = signal[i];
3841 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;
3843 #if SPOTCHECK_ESTIMATE
3844 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3851 unsigned evaluate_verbatim_subframe_(
3852 FLAC__StreamEncoder *encoder,
3853 const FLAC__int32 signal[],
3855 unsigned subframe_bps,
3856 FLAC__Subframe *subframe
3861 subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3863 subframe->data.verbatim.data = signal;
3865 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
3867 #if SPOTCHECK_ESTIMATE
3868 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3876 unsigned find_best_partition_order_(
3877 FLAC__StreamEncoderPrivate *private_,
3878 const FLAC__int32 residual[],
3879 FLAC__uint64 abs_residual_partition_sums[],
3880 unsigned raw_bits_per_partition[],
3881 unsigned residual_samples,
3882 unsigned predictor_order,
3883 unsigned rice_parameter,
3884 unsigned min_partition_order,
3885 unsigned max_partition_order,
3886 FLAC__bool do_escape_coding,
3887 unsigned rice_parameter_search_dist,
3888 FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
3891 unsigned residual_bits, best_residual_bits = 0;
3892 unsigned best_parameters_index = 0;
3893 const unsigned blocksize = residual_samples + predictor_order;
3895 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3896 min_partition_order = min(min_partition_order, max_partition_order);
3898 precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order);
3900 if(do_escape_coding)
3901 precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3904 int partition_order;
3907 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3909 set_partitioned_rice_(
3910 #ifdef EXACT_RICE_BITS_CALCULATION
3913 abs_residual_partition_sums+sum,
3914 raw_bits_per_partition+sum,
3918 rice_parameter_search_dist,
3919 (unsigned)partition_order,
3921 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3926 FLAC__ASSERT(best_residual_bits != 0);
3929 sum += 1u << partition_order;
3930 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3931 best_residual_bits = residual_bits;
3932 best_parameters_index = !best_parameters_index;
3933 best_partitioned_rice->order = partition_order;
3939 * We are allowed to de-const the pointer based on our special knowledge;
3940 * it is const to the outside world.
3943 FLAC__EntropyCodingMethod_PartitionedRiceContents* best_partitioned_rice_contents = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_partitioned_rice->contents;
3944 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(best_partitioned_rice_contents, max(6, best_partitioned_rice->order));
3945 memcpy(best_partitioned_rice_contents->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
3946 memcpy(best_partitioned_rice_contents->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
3949 return best_residual_bits;
3952 void precompute_partition_info_sums_(
3953 const FLAC__int32 residual[],
3954 FLAC__uint64 abs_residual_partition_sums[],
3955 unsigned residual_samples,
3956 unsigned predictor_order,
3957 unsigned min_partition_order,
3958 unsigned max_partition_order
3961 int partition_order;
3962 unsigned from_partition, to_partition = 0;
3963 const unsigned blocksize = residual_samples + predictor_order;
3965 /* first do max_partition_order */
3966 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3967 FLAC__uint64 abs_residual_partition_sum; /* OPT: can reasonably be FLAC__uint32 for bps <= 17 and maybe higher */
3968 unsigned partition, partition_sample, partition_samples, residual_sample;
3969 const unsigned partitions = 1u << partition_order;
3970 const unsigned default_partition_samples = blocksize >> partition_order;
3972 FLAC__ASSERT(default_partition_samples > predictor_order);
3974 for(partition = residual_sample = 0; partition < partitions; partition++) {
3975 partition_samples = default_partition_samples;
3977 partition_samples -= predictor_order;
3978 abs_residual_partition_sum = 0;
3979 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++, residual_sample++) {
3980 #if defined _MSC_VER
3981 /* OPT: abs() may be faster for some compilers */
3982 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3984 const FLAC__int32 r = residual[residual_sample];
3986 abs_residual_partition_sum -= r;
3988 abs_residual_partition_sum += r;
3991 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3993 to_partition = partitions;
3997 /* now merge partitions for lower orders */
3998 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
4001 const unsigned partitions = 1u << partition_order;
4002 for(i = 0; i < partitions; i++) {
4003 s = abs_residual_partition_sums[from_partition];
4005 abs_residual_partition_sums[to_partition] = s + abs_residual_partition_sums[from_partition];
4012 void precompute_partition_info_escapes_(
4013 const FLAC__int32 residual[],
4014 unsigned raw_bits_per_partition[],
4015 unsigned residual_samples,
4016 unsigned predictor_order,
4017 unsigned min_partition_order,
4018 unsigned max_partition_order
4021 int partition_order;
4022 unsigned from_partition, to_partition = 0;
4023 const unsigned blocksize = residual_samples + predictor_order;
4025 /* first do max_partition_order */
4026 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
4029 unsigned partition, partition_sample, partition_samples, residual_sample;
4030 const unsigned partitions = 1u << partition_order;
4031 const unsigned default_partition_samples = blocksize >> partition_order;
4033 FLAC__ASSERT(default_partition_samples > predictor_order);
4035 for(partition = residual_sample = 0; partition < partitions; partition++) {
4036 partition_samples = default_partition_samples;
4038 partition_samples -= predictor_order;
4040 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
4041 r = residual[residual_sample++];
4042 /* OPT: maybe faster: rmax |= r ^ (r>>31) */
4048 /* now we know all residual values are in the range [-rmax-1,rmax] */
4049 raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
4051 to_partition = partitions;
4052 break; /*@@@ yuck, should remove the 'for' loop instead */
4055 /* now merge partitions for lower orders */
4056 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
4059 const unsigned partitions = 1u << partition_order;
4060 for(i = 0; i < partitions; i++) {
4061 m = raw_bits_per_partition[from_partition];
4063 raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
4070 #ifdef EXACT_RICE_BITS_CALCULATION
4071 static __inline unsigned count_rice_bits_in_partition_(
4072 const unsigned rice_parameter,
4073 const unsigned partition_samples,
4074 const FLAC__int32 *residual
4077 unsigned i, partition_bits =
4078 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN +
4079 (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
4081 for(i = 0; i < partition_samples; i++)
4082 partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
4083 return partition_bits;
4086 static __inline unsigned count_rice_bits_in_partition_(
4087 const unsigned rice_parameter,
4088 const unsigned partition_samples,
4089 const FLAC__uint64 abs_residual_partition_sum
4093 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN +
4094 (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
4097 (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
4098 : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
4100 - (partition_samples >> 1)
4101 /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
4102 * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
4103 * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
4104 * So the subtraction term tries to guess how many extra bits were contributed.
4105 * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
4111 FLAC__bool set_partitioned_rice_(
4112 #ifdef EXACT_RICE_BITS_CALCULATION
4113 const FLAC__int32 residual[],
4115 const FLAC__uint64 abs_residual_partition_sums[],
4116 const unsigned raw_bits_per_partition[],
4117 const unsigned residual_samples,
4118 const unsigned predictor_order,
4119 const unsigned suggested_rice_parameter,
4120 const unsigned rice_parameter_search_dist,
4121 const unsigned partition_order,
4122 const FLAC__bool search_for_escapes,
4123 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
4127 unsigned rice_parameter, partition_bits;
4128 unsigned best_partition_bits, best_rice_parameter = 0;
4129 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
4130 unsigned *parameters, *raw_bits;
4131 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4132 unsigned min_rice_parameter, max_rice_parameter;
4134 (void)rice_parameter_search_dist;
4137 FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
4139 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
4140 parameters = partitioned_rice_contents->parameters;
4141 raw_bits = partitioned_rice_contents->raw_bits;
4143 if(partition_order == 0) {
4144 best_partition_bits = 0xffffffff;
4145 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4146 if(rice_parameter_search_dist) {
4147 if(suggested_rice_parameter < rice_parameter_search_dist)
4148 min_rice_parameter = 0;
4150 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
4151 max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
4152 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
4153 #ifdef DEBUG_VERBOSE
4154 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
4156 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
4160 min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
4162 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4164 rice_parameter = suggested_rice_parameter;
4166 #ifdef EXACT_RICE_BITS_CALCULATION
4167 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
4169 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
4171 if(partition_bits < best_partition_bits) {
4172 best_rice_parameter = rice_parameter;
4173 best_partition_bits = partition_bits;
4175 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4178 if(search_for_escapes) {
4179 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;
4180 if(partition_bits <= best_partition_bits) {
4181 raw_bits[0] = raw_bits_per_partition[0];
4182 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
4183 best_partition_bits = partition_bits;
4186 parameters[0] = best_rice_parameter;
4187 bits_ += best_partition_bits;
4190 unsigned partition, residual_sample;
4191 unsigned partition_samples;
4192 FLAC__uint64 mean, k;
4193 const unsigned partitions = 1u << partition_order;
4194 for(partition = residual_sample = 0; partition < partitions; partition++) {
4195 partition_samples = (residual_samples+predictor_order) >> partition_order;
4196 if(partition == 0) {
4197 if(partition_samples <= predictor_order)
4200 partition_samples -= predictor_order;
4202 mean = abs_residual_partition_sums[partition];
4203 /* we are basically calculating the size in bits of the
4204 * average residual magnitude in the partition:
4205 * rice_parameter = floor(log2(mean/partition_samples))
4206 * 'mean' is not a good name for the variable, it is
4207 * actually the sum of magnitudes of all residual values
4208 * in the partition, so the actual mean is
4209 * mean/partition_samples
4211 for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
4213 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
4214 #ifdef DEBUG_VERBOSE
4215 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
4217 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
4220 best_partition_bits = 0xffffffff;
4221 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4222 if(rice_parameter_search_dist) {
4223 if(rice_parameter < rice_parameter_search_dist)
4224 min_rice_parameter = 0;
4226 min_rice_parameter = rice_parameter - rice_parameter_search_dist;
4227 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
4228 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
4229 #ifdef DEBUG_VERBOSE
4230 fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
4232 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
4236 min_rice_parameter = max_rice_parameter = rice_parameter;
4238 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4240 #ifdef EXACT_RICE_BITS_CALCULATION
4241 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
4243 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
4245 if(partition_bits < best_partition_bits) {
4246 best_rice_parameter = rice_parameter;
4247 best_partition_bits = partition_bits;
4249 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4252 if(search_for_escapes) {
4253 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;
4254 if(partition_bits <= best_partition_bits) {
4255 raw_bits[partition] = raw_bits_per_partition[partition];
4256 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
4257 best_partition_bits = partition_bits;
4260 parameters[partition] = best_rice_parameter;
4261 bits_ += best_partition_bits;
4262 residual_sample += partition_samples;
4270 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
4275 for(i = 0; i < samples && !(x&1); i++)
4282 for(shift = 0; !(x&1); shift++)
4287 for(i = 0; i < samples; i++)
4288 signal[i] >>= shift;
4294 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4298 for(channel = 0; channel < channels; channel++)
4299 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
4301 fifo->tail += wide_samples;
4303 FLAC__ASSERT(fifo->tail <= fifo->size);
4306 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4309 unsigned sample, wide_sample;
4310 unsigned tail = fifo->tail;
4312 sample = input_offset * channels;
4313 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
4314 for(channel = 0; channel < channels; channel++)
4315 fifo->data[channel][tail] = input[sample++];
4320 FLAC__ASSERT(fifo->tail <= fifo->size);
4323 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4325 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4326 const size_t encoded_bytes = encoder->private_->verify.output.bytes;
4329 if(encoder->private_->verify.needs_magic_hack) {
4330 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
4331 *bytes = FLAC__STREAM_SYNC_LENGTH;
4332 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
4333 encoder->private_->verify.needs_magic_hack = false;
4336 if(encoded_bytes == 0) {
4338 * If we get here, a FIFO underflow has occurred,
4339 * which means there is a bug somewhere.
4342 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
4344 else if(encoded_bytes < *bytes)
4345 *bytes = encoded_bytes;
4346 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
4347 encoder->private_->verify.output.data += *bytes;
4348 encoder->private_->verify.output.bytes -= *bytes;
4351 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
4354 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
4356 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
4358 const unsigned channels = frame->header.channels;
4359 const unsigned blocksize = frame->header.blocksize;
4360 const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
4364 for(channel = 0; channel < channels; channel++) {
4365 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
4366 unsigned i, sample = 0;
4367 FLAC__int32 expect = 0, got = 0;
4369 for(i = 0; i < blocksize; i++) {
4370 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
4372 expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
4373 got = (FLAC__int32)buffer[channel][i];
4377 FLAC__ASSERT(i < blocksize);
4378 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
4379 encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
4380 encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
4381 encoder->private_->verify.error_stats.channel = channel;
4382 encoder->private_->verify.error_stats.sample = sample;
4383 encoder->private_->verify.error_stats.expected = expect;
4384 encoder->private_->verify.error_stats.got = got;
4385 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
4386 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
4389 /* dequeue the frame from the fifo */
4390 encoder->private_->verify.input_fifo.tail -= blocksize;
4391 FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
4392 for(channel = 0; channel < channels; channel++)
4393 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]));
4394 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4397 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4399 (void)decoder, (void)metadata, (void)client_data;
4402 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4404 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4405 (void)decoder, (void)status;
4406 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4409 FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4413 *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
4415 if (feof(encoder->private_->file))
4416 return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
4417 else if (ferror(encoder->private_->file))
4418 return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
4420 return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
4423 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4427 if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
4428 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4430 return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4433 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4439 offset = ftello(encoder->private_->file);
4442 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4445 *absolute_byte_offset = (FLAC__uint64)offset;
4446 return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4450 #ifdef FLAC__VALGRIND_TESTING
4451 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4453 size_t ret = fwrite(ptr, size, nmemb, stream);
4459 #define local__fwrite fwrite
4462 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
4464 (void)client_data, (void)current_frame;
4466 if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4467 FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
4469 /* We would like to be able to use 'samples > 0' in the
4470 * clause here but currently because of the nature of our
4471 * Ogg writing implementation, 'samples' is always 0 (see
4472 * ogg_encoder_aspect.c). The downside is extra progress
4475 encoder->private_->is_ogg? true :
4480 /* NOTE: We have to add +bytes, +samples, and +1 to the stats
4481 * because at this point in the callback chain, the stats
4482 * have not been updated. Only after we return and control
4483 * gets back to write_frame_() are the stats updated
4485 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);
4487 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4490 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4494 * This will forcibly set stdout to binary mode (for OSes that require it)
4496 FILE *get_binary_stdout_(void)
4498 /* if something breaks here it is probably due to the presence or
4499 * absence of an underscore before the identifiers 'setmode',
4500 * 'fileno', and/or 'O_BINARY'; check your system header files.
4502 #if defined _MSC_VER || defined __MINGW32__
4503 _setmode(_fileno(stdout), _O_BINARY);
4504 #elif defined __CYGWIN__
4505 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4506 setmode(_fileno(stdout), _O_BINARY);
4507 #elif defined __EMX__
4508 setmode(fileno(stdout), O_BINARY);