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"
81 #define min(x,y) ((x)<(y)?(x):(y))
86 #define max(x,y) ((x)>(y)?(x):(y))
88 /* Exact Rice codeword length calculation is off by default. The simple
89 * (and fast) estimation (of how many bits a residual value will be
90 * encoded with) in this encoder is very good, almost always yielding
91 * compression within 0.1% of exact calculation.
93 #undef EXACT_RICE_BITS_CALCULATION
94 /* Rice parameter searching is off by default. The simple (and fast)
95 * parameter estimation in this encoder is very good, almost always
96 * yielding compression within 0.1% of the optimal parameters.
98 #undef ENABLE_RICE_PARAMETER_SEARCH
102 FLAC__int32 *data[FLAC__MAX_CHANNELS];
103 unsigned size; /* of each data[] in samples */
108 const FLAC__byte *data;
114 ENCODER_IN_MAGIC = 0,
115 ENCODER_IN_METADATA = 1,
119 static struct CompressionLevels {
120 FLAC__bool do_mid_side_stereo;
121 FLAC__bool loose_mid_side_stereo;
122 unsigned max_lpc_order;
123 unsigned qlp_coeff_precision;
124 FLAC__bool do_qlp_coeff_prec_search;
125 FLAC__bool do_escape_coding;
126 FLAC__bool do_exhaustive_model_search;
127 unsigned min_residual_partition_order;
128 unsigned max_residual_partition_order;
129 unsigned rice_parameter_search_dist;
130 } compression_levels_[] = {
131 { false, false, 0, 0, false, false, false, 0, 3, 0 },
132 { true , true , 0, 0, false, false, false, 0, 3, 0 },
133 { true , false, 0, 0, false, false, false, 0, 3, 0 },
134 { false, false, 6, 0, false, false, false, 0, 4, 0 },
135 { true , true , 8, 0, false, false, false, 0, 4, 0 },
136 { true , false, 8, 0, false, false, false, 0, 5, 0 },
137 { true , false, 8, 0, false, false, false, 0, 6, 0 },
138 { true , false, 8, 0, false, false, true , 0, 6, 0 },
139 { true , false, 12, 0, false, false, true , 0, 6, 0 }
143 /***********************************************************************
145 * Private class method prototypes
147 ***********************************************************************/
149 static void set_defaults_(FLAC__StreamEncoder *encoder);
150 static void free_(FLAC__StreamEncoder *encoder);
151 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
152 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
153 static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
154 static void update_metadata_(const FLAC__StreamEncoder *encoder);
156 static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
158 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
159 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
161 static FLAC__bool process_subframe_(
162 FLAC__StreamEncoder *encoder,
163 unsigned min_partition_order,
164 unsigned max_partition_order,
165 const FLAC__FrameHeader *frame_header,
166 unsigned subframe_bps,
167 const FLAC__int32 integer_signal[],
168 #ifndef FLAC__INTEGER_ONLY_LIBRARY
169 const FLAC__real real_signal[],
171 FLAC__Subframe *subframe[2],
172 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
173 FLAC__int32 *residual[2],
174 unsigned *best_subframe,
178 static FLAC__bool add_subframe_(
179 FLAC__StreamEncoder *encoder,
181 unsigned subframe_bps,
182 const FLAC__Subframe *subframe,
183 FLAC__BitWriter *frame
186 static unsigned evaluate_constant_subframe_(
187 FLAC__StreamEncoder *encoder,
188 const FLAC__int32 signal,
190 unsigned subframe_bps,
191 FLAC__Subframe *subframe
194 static unsigned evaluate_fixed_subframe_(
195 FLAC__StreamEncoder *encoder,
196 const FLAC__int32 signal[],
197 FLAC__int32 residual[],
198 FLAC__uint64 abs_residual_partition_sums[],
199 unsigned raw_bits_per_partition[],
201 unsigned subframe_bps,
203 unsigned rice_parameter,
204 unsigned min_partition_order,
205 unsigned max_partition_order,
206 FLAC__bool do_escape_coding,
207 unsigned rice_parameter_search_dist,
208 FLAC__Subframe *subframe,
209 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
212 #ifndef FLAC__INTEGER_ONLY_LIBRARY
213 static unsigned evaluate_lpc_subframe_(
214 FLAC__StreamEncoder *encoder,
215 const FLAC__int32 signal[],
216 FLAC__int32 residual[],
217 FLAC__uint64 abs_residual_partition_sums[],
218 unsigned raw_bits_per_partition[],
219 const FLAC__real lp_coeff[],
221 unsigned subframe_bps,
223 unsigned qlp_coeff_precision,
224 unsigned rice_parameter,
225 unsigned min_partition_order,
226 unsigned max_partition_order,
227 FLAC__bool do_escape_coding,
228 unsigned rice_parameter_search_dist,
229 FLAC__Subframe *subframe,
230 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
234 static unsigned evaluate_verbatim_subframe_(
235 FLAC__StreamEncoder *encoder,
236 const FLAC__int32 signal[],
238 unsigned subframe_bps,
239 FLAC__Subframe *subframe
242 static unsigned find_best_partition_order_(
243 struct FLAC__StreamEncoderPrivate *private_,
244 const FLAC__int32 residual[],
245 FLAC__uint64 abs_residual_partition_sums[],
246 unsigned raw_bits_per_partition[],
247 unsigned residual_samples,
248 unsigned predictor_order,
249 unsigned rice_parameter,
250 unsigned min_partition_order,
251 unsigned max_partition_order,
253 FLAC__bool do_escape_coding,
254 unsigned rice_parameter_search_dist,
255 FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
258 static void precompute_partition_info_sums_(
259 const FLAC__int32 residual[],
260 FLAC__uint64 abs_residual_partition_sums[],
261 unsigned residual_samples,
262 unsigned predictor_order,
263 unsigned min_partition_order,
264 unsigned max_partition_order,
268 static void precompute_partition_info_escapes_(
269 const FLAC__int32 residual[],
270 unsigned raw_bits_per_partition[],
271 unsigned residual_samples,
272 unsigned predictor_order,
273 unsigned min_partition_order,
274 unsigned max_partition_order
277 static FLAC__bool set_partitioned_rice_(
278 #ifdef EXACT_RICE_BITS_CALCULATION
279 const FLAC__int32 residual[],
281 const FLAC__uint64 abs_residual_partition_sums[],
282 const unsigned raw_bits_per_partition[],
283 const unsigned residual_samples,
284 const unsigned predictor_order,
285 const unsigned suggested_rice_parameter,
286 const unsigned rice_parameter_search_dist,
287 const unsigned partition_order,
288 const FLAC__bool search_for_escapes,
289 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
293 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
295 /* verify-related routines: */
296 static void append_to_verify_fifo_(
297 verify_input_fifo *fifo,
298 const FLAC__int32 * const input[],
299 unsigned input_offset,
301 unsigned wide_samples
304 static void append_to_verify_fifo_interleaved_(
305 verify_input_fifo *fifo,
306 const FLAC__int32 input[],
307 unsigned input_offset,
309 unsigned wide_samples
312 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
313 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
314 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
315 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
317 static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
318 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
319 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
320 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);
321 static FILE *get_binary_stdout_(void);
324 /***********************************************************************
328 ***********************************************************************/
330 typedef struct FLAC__StreamEncoderPrivate {
331 unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
332 FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
333 FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
334 #ifndef FLAC__INTEGER_ONLY_LIBRARY
335 FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* the floating-point version of the input signal */
336 FLAC__real *real_signal_mid_side[2]; /* the floating-point version of the mid-side input signal (stereo only) */
337 FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
338 FLAC__real *windowed_signal; /* the real_signal[] * current window[] */
340 unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
341 unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
342 FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
343 FLAC__int32 *residual_workspace_mid_side[2][2];
344 FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
345 FLAC__Subframe subframe_workspace_mid_side[2][2];
346 FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
347 FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
348 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
349 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
350 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
351 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
352 unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
353 unsigned best_subframe_mid_side[2];
354 unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
355 unsigned best_subframe_bits_mid_side[2];
356 FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
357 unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
358 FLAC__BitWriter *frame; /* the current frame being worked on */
359 unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
360 unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
361 FLAC__ChannelAssignment last_channel_assignment;
362 FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
363 FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
364 unsigned current_sample_number;
365 unsigned current_frame_number;
366 FLAC__MD5Context md5context;
367 FLAC__CPUInfo cpuinfo;
368 #ifndef FLAC__INTEGER_ONLY_LIBRARY
369 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
371 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
373 #ifndef FLAC__INTEGER_ONLY_LIBRARY
374 void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
375 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[]);
376 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[]);
377 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[]);
379 FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
380 FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
381 FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
382 FLAC__bool disable_constant_subframes;
383 FLAC__bool disable_fixed_subframes;
384 FLAC__bool disable_verbatim_subframes;
388 FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
389 FLAC__StreamEncoderSeekCallback seek_callback;
390 FLAC__StreamEncoderTellCallback tell_callback;
391 FLAC__StreamEncoderWriteCallback write_callback;
392 FLAC__StreamEncoderMetadataCallback metadata_callback;
393 FLAC__StreamEncoderProgressCallback progress_callback;
395 unsigned first_seekpoint_to_check;
396 FILE *file; /* only used when encoding to a file */
397 FLAC__uint64 bytes_written;
398 FLAC__uint64 samples_written;
399 unsigned frames_written;
400 unsigned total_frames_estimate;
401 /* unaligned (original) pointers to allocated data */
402 FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
403 FLAC__int32 *integer_signal_mid_side_unaligned[2];
404 #ifndef FLAC__INTEGER_ONLY_LIBRARY
405 FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS];
406 FLAC__real *real_signal_mid_side_unaligned[2];
407 FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
408 FLAC__real *windowed_signal_unaligned;
410 FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
411 FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
412 FLAC__uint64 *abs_residual_partition_sums_unaligned;
413 unsigned *raw_bits_per_partition_unaligned;
415 * These fields have been moved here from private function local
416 * declarations merely to save stack space during encoding.
418 #ifndef FLAC__INTEGER_ONLY_LIBRARY
419 FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
421 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
423 * The data for the verify section
426 FLAC__StreamDecoder *decoder;
427 EncoderStateHint state_hint;
428 FLAC__bool needs_magic_hack;
429 verify_input_fifo input_fifo;
430 verify_output output;
432 FLAC__uint64 absolute_sample;
433 unsigned frame_number;
436 FLAC__int32 expected;
440 FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
441 } FLAC__StreamEncoderPrivate;
443 /***********************************************************************
445 * Public static class data
447 ***********************************************************************/
449 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
450 "FLAC__STREAM_ENCODER_OK",
451 "FLAC__STREAM_ENCODER_UNINITIALIZED",
452 "FLAC__STREAM_ENCODER_OGG_ERROR",
453 "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
454 "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
455 "FLAC__STREAM_ENCODER_CLIENT_ERROR",
456 "FLAC__STREAM_ENCODER_IO_ERROR",
457 "FLAC__STREAM_ENCODER_FRAMING_ERROR",
458 "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
461 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
462 "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
463 "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
464 "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
465 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
466 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
467 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
468 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
469 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
470 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
471 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
472 "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
473 "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
474 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
475 "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
478 FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
479 "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
480 "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
481 "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
482 "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
485 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
486 "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
487 "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
490 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
491 "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
492 "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
493 "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
496 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
497 "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
498 "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
499 "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
502 /* Number of samples that will be overread to watch for end of stream. By
503 * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
504 * always try to read blocksize+1 samples before encoding a block, so that
505 * even if the stream has a total sample count that is an integral multiple
506 * of the blocksize, we will still notice when we are encoding the last
507 * block. This is needed, for example, to correctly set the end-of-stream
508 * marker in Ogg FLAC.
510 * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
511 * not really any reason to change it.
513 static const unsigned OVERREAD_ = 1;
515 /***********************************************************************
517 * Class constructor/destructor
520 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
522 FLAC__StreamEncoder *encoder;
525 FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
527 encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
532 encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
533 if(encoder->protected_ == 0) {
538 encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
539 if(encoder->private_ == 0) {
540 free(encoder->protected_);
545 encoder->private_->frame = FLAC__bitwriter_new();
546 if(encoder->private_->frame == 0) {
547 free(encoder->private_);
548 free(encoder->protected_);
553 encoder->private_->file = 0;
555 set_defaults_(encoder);
557 encoder->private_->is_being_deleted = false;
559 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
560 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
561 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
563 for(i = 0; i < 2; i++) {
564 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
565 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
567 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
568 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
569 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
571 for(i = 0; i < 2; i++) {
572 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
573 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
576 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
577 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
578 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
580 for(i = 0; i < 2; i++) {
581 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
582 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
584 for(i = 0; i < 2; i++)
585 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
587 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
592 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
596 FLAC__ASSERT(0 != encoder);
597 FLAC__ASSERT(0 != encoder->protected_);
598 FLAC__ASSERT(0 != encoder->private_);
599 FLAC__ASSERT(0 != encoder->private_->frame);
601 encoder->private_->is_being_deleted = true;
603 (void)FLAC__stream_encoder_finish(encoder);
605 if(0 != encoder->private_->verify.decoder)
606 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
608 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
609 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
610 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
612 for(i = 0; i < 2; i++) {
613 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
614 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
616 for(i = 0; i < 2; i++)
617 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
619 FLAC__bitwriter_delete(encoder->private_->frame);
620 free(encoder->private_);
621 free(encoder->protected_);
625 /***********************************************************************
627 * Public class methods
629 ***********************************************************************/
631 static FLAC__StreamEncoderInitStatus init_stream_internal_(
632 FLAC__StreamEncoder *encoder,
633 FLAC__StreamEncoderReadCallback read_callback,
634 FLAC__StreamEncoderWriteCallback write_callback,
635 FLAC__StreamEncoderSeekCallback seek_callback,
636 FLAC__StreamEncoderTellCallback tell_callback,
637 FLAC__StreamEncoderMetadataCallback metadata_callback,
643 FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
645 FLAC__ASSERT(0 != encoder);
647 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
648 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
652 return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
655 if(0 == write_callback || (seek_callback && 0 == tell_callback))
656 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
658 if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
659 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
661 if(encoder->protected_->channels != 2) {
662 encoder->protected_->do_mid_side_stereo = false;
663 encoder->protected_->loose_mid_side_stereo = false;
665 else if(!encoder->protected_->do_mid_side_stereo)
666 encoder->protected_->loose_mid_side_stereo = false;
668 if(encoder->protected_->bits_per_sample >= 32)
669 encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
671 if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
672 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
674 if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
675 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
677 if(encoder->protected_->blocksize == 0) {
678 if(encoder->protected_->max_lpc_order == 0)
679 encoder->protected_->blocksize = 1152;
681 encoder->protected_->blocksize = 4096;
684 if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
685 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
687 if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
688 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
690 if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
691 return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
693 if(encoder->protected_->qlp_coeff_precision == 0) {
694 if(encoder->protected_->bits_per_sample < 16) {
695 /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
696 /* @@@ until then we'll make a guess */
697 encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
699 else if(encoder->protected_->bits_per_sample == 16) {
700 if(encoder->protected_->blocksize <= 192)
701 encoder->protected_->qlp_coeff_precision = 7;
702 else if(encoder->protected_->blocksize <= 384)
703 encoder->protected_->qlp_coeff_precision = 8;
704 else if(encoder->protected_->blocksize <= 576)
705 encoder->protected_->qlp_coeff_precision = 9;
706 else if(encoder->protected_->blocksize <= 1152)
707 encoder->protected_->qlp_coeff_precision = 10;
708 else if(encoder->protected_->blocksize <= 2304)
709 encoder->protected_->qlp_coeff_precision = 11;
710 else if(encoder->protected_->blocksize <= 4608)
711 encoder->protected_->qlp_coeff_precision = 12;
713 encoder->protected_->qlp_coeff_precision = 13;
716 if(encoder->protected_->blocksize <= 384)
717 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
718 else if(encoder->protected_->blocksize <= 1152)
719 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
721 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
723 FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
725 else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
726 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
728 if(encoder->protected_->streamable_subset) {
730 encoder->protected_->blocksize != 192 &&
731 encoder->protected_->blocksize != 576 &&
732 encoder->protected_->blocksize != 1152 &&
733 encoder->protected_->blocksize != 2304 &&
734 encoder->protected_->blocksize != 4608 &&
735 encoder->protected_->blocksize != 256 &&
736 encoder->protected_->blocksize != 512 &&
737 encoder->protected_->blocksize != 1024 &&
738 encoder->protected_->blocksize != 2048 &&
739 encoder->protected_->blocksize != 4096 &&
740 encoder->protected_->blocksize != 8192 &&
741 encoder->protected_->blocksize != 16384
743 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
744 if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
745 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
747 encoder->protected_->bits_per_sample != 8 &&
748 encoder->protected_->bits_per_sample != 12 &&
749 encoder->protected_->bits_per_sample != 16 &&
750 encoder->protected_->bits_per_sample != 20 &&
751 encoder->protected_->bits_per_sample != 24
753 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
754 if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
755 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
757 encoder->protected_->sample_rate <= 48000 &&
759 encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
760 encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
763 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
767 if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
768 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
769 if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
770 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
773 /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
774 if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
776 for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
777 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
778 FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
780 encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
781 encoder->protected_->metadata[0] = vc;
787 /* keep track of any SEEKTABLE block */
788 if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
790 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
791 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
792 encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
793 break; /* take only the first one */
798 /* validate metadata */
799 if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
800 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
801 metadata_has_seektable = false;
802 metadata_has_vorbis_comment = false;
803 metadata_picture_has_type1 = false;
804 metadata_picture_has_type2 = false;
805 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
806 const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
807 if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
808 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
809 else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
810 if(metadata_has_seektable) /* only one is allowed */
811 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
812 metadata_has_seektable = true;
813 if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
814 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
816 else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
817 if(metadata_has_vorbis_comment) /* only one is allowed */
818 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
819 metadata_has_vorbis_comment = true;
821 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
822 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
823 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
825 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
826 if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
827 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
828 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
829 if(metadata_picture_has_type1) /* there should only be 1 per stream */
830 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
831 metadata_picture_has_type1 = true;
832 /* standard icon must be 32x32 pixel PNG */
834 m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
836 (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
837 m->data.picture.width != 32 ||
838 m->data.picture.height != 32
841 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
843 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
844 if(metadata_picture_has_type2) /* there should only be 1 per stream */
845 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
846 metadata_picture_has_type2 = true;
851 encoder->private_->input_capacity = 0;
852 for(i = 0; i < encoder->protected_->channels; i++) {
853 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
854 #ifndef FLAC__INTEGER_ONLY_LIBRARY
855 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
858 for(i = 0; i < 2; i++) {
859 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
860 #ifndef FLAC__INTEGER_ONLY_LIBRARY
861 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
864 #ifndef FLAC__INTEGER_ONLY_LIBRARY
865 for(i = 0; i < encoder->protected_->num_apodizations; i++)
866 encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
867 encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
869 for(i = 0; i < encoder->protected_->channels; i++) {
870 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
871 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
872 encoder->private_->best_subframe[i] = 0;
874 for(i = 0; i < 2; i++) {
875 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
876 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
877 encoder->private_->best_subframe_mid_side[i] = 0;
879 encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
880 encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
881 #ifndef FLAC__INTEGER_ONLY_LIBRARY
882 encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
884 /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
885 /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply÷ by hand */
886 FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
887 FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
888 FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
889 FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
890 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);
892 if(encoder->private_->loose_mid_side_stereo_frames == 0)
893 encoder->private_->loose_mid_side_stereo_frames = 1;
894 encoder->private_->loose_mid_side_stereo_frame_count = 0;
895 encoder->private_->current_sample_number = 0;
896 encoder->private_->current_frame_number = 0;
898 encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
899 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? */
900 encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
903 * get the CPU info and set the function pointers
905 FLAC__cpu_info(&encoder->private_->cpuinfo);
906 /* first default to the non-asm routines */
907 #ifndef FLAC__INTEGER_ONLY_LIBRARY
908 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
910 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
911 #ifndef FLAC__INTEGER_ONLY_LIBRARY
912 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
913 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
914 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
916 /* now override with asm where appropriate */
917 #ifndef FLAC__INTEGER_ONLY_LIBRARY
918 # ifndef FLAC__NO_ASM
919 if(encoder->private_->cpuinfo.use_asm) {
920 # ifdef FLAC__CPU_IA32
921 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
922 # ifdef FLAC__HAS_NASM
923 if(encoder->private_->cpuinfo.data.ia32.sse) {
924 if(encoder->protected_->max_lpc_order < 4)
925 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
926 else if(encoder->protected_->max_lpc_order < 8)
927 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
928 else if(encoder->protected_->max_lpc_order < 12)
929 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
931 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
933 else if(encoder->private_->cpuinfo.data.ia32._3dnow)
934 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
936 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
937 if(encoder->private_->cpuinfo.data.ia32.mmx) {
938 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
939 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
942 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
943 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
945 if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
946 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
947 # endif /* FLAC__HAS_NASM */
948 # endif /* FLAC__CPU_IA32 */
950 # endif /* !FLAC__NO_ASM */
951 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
952 /* finally override based on wide-ness if necessary */
953 if(encoder->private_->use_wide_by_block) {
954 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
957 /* set state to OK; from here on, errors are fatal and we'll override the state then */
958 encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
961 encoder->private_->is_ogg = is_ogg;
962 if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
963 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
964 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
968 encoder->private_->read_callback = read_callback;
969 encoder->private_->write_callback = write_callback;
970 encoder->private_->seek_callback = seek_callback;
971 encoder->private_->tell_callback = tell_callback;
972 encoder->private_->metadata_callback = metadata_callback;
973 encoder->private_->client_data = client_data;
975 if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
976 /* the above function sets the state for us in case of an error */
977 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
980 if(!FLAC__bitwriter_init(encoder->private_->frame)) {
981 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
982 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
986 * Set up the verify stuff if necessary
988 if(encoder->protected_->verify) {
990 * First, set up the fifo which will hold the
991 * original signal to compare against
993 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
994 for(i = 0; i < encoder->protected_->channels; i++) {
995 if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder->private_->verify.input_fifo.size))) {
996 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
997 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1000 encoder->private_->verify.input_fifo.tail = 0;
1003 * Now set up a stream decoder for verification
1005 encoder->private_->verify.decoder = FLAC__stream_decoder_new();
1006 if(0 == encoder->private_->verify.decoder) {
1007 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1008 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1011 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) {
1012 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1013 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1016 encoder->private_->verify.error_stats.absolute_sample = 0;
1017 encoder->private_->verify.error_stats.frame_number = 0;
1018 encoder->private_->verify.error_stats.channel = 0;
1019 encoder->private_->verify.error_stats.sample = 0;
1020 encoder->private_->verify.error_stats.expected = 0;
1021 encoder->private_->verify.error_stats.got = 0;
1024 * These must be done before we write any metadata, because that
1025 * calls the write_callback, which uses these values.
1027 encoder->private_->first_seekpoint_to_check = 0;
1028 encoder->private_->samples_written = 0;
1029 encoder->protected_->streaminfo_offset = 0;
1030 encoder->protected_->seektable_offset = 0;
1031 encoder->protected_->audio_offset = 0;
1034 * write the stream header
1036 if(encoder->protected_->verify)
1037 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1038 if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1039 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1040 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1042 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1043 /* the above function sets the state for us in case of an error */
1044 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1048 * write the STREAMINFO metadata block
1050 if(encoder->protected_->verify)
1051 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1052 encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1053 encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1054 encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1055 encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1056 encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1057 encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1058 encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1059 encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1060 encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1061 encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1062 encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1063 memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1064 FLAC__MD5Init(&encoder->private_->md5context);
1065 if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1066 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1067 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1069 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1070 /* the above function sets the state for us in case of an error */
1071 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1075 * Now that the STREAMINFO block is written, we can init this to an
1076 * absurdly-high value...
1078 encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1079 /* ... and clear this to 0 */
1080 encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1083 * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1084 * if not, we will write an empty one (FLAC__add_metadata_block()
1085 * automatically supplies the vendor string).
1087 * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1088 * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
1089 * true it will have already insured that the metadata list is properly
1092 if(!metadata_has_vorbis_comment) {
1093 FLAC__StreamMetadata vorbis_comment;
1094 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1095 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1096 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1097 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1098 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1099 vorbis_comment.data.vorbis_comment.num_comments = 0;
1100 vorbis_comment.data.vorbis_comment.comments = 0;
1101 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1102 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1103 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1105 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1106 /* the above function sets the state for us in case of an error */
1107 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1112 * write the user's metadata blocks
1114 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1115 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1116 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1117 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1118 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1120 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1121 /* the above function sets the state for us in case of an error */
1122 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1126 /* now that all the metadata is written, we save the stream offset */
1127 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 */
1128 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1129 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1132 if(encoder->protected_->verify)
1133 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1135 return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1138 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1139 FLAC__StreamEncoder *encoder,
1140 FLAC__StreamEncoderWriteCallback write_callback,
1141 FLAC__StreamEncoderSeekCallback seek_callback,
1142 FLAC__StreamEncoderTellCallback tell_callback,
1143 FLAC__StreamEncoderMetadataCallback metadata_callback,
1147 return init_stream_internal_(
1149 /*read_callback=*/0,
1159 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1160 FLAC__StreamEncoder *encoder,
1161 FLAC__StreamEncoderReadCallback read_callback,
1162 FLAC__StreamEncoderWriteCallback write_callback,
1163 FLAC__StreamEncoderSeekCallback seek_callback,
1164 FLAC__StreamEncoderTellCallback tell_callback,
1165 FLAC__StreamEncoderMetadataCallback metadata_callback,
1169 return init_stream_internal_(
1181 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1182 FLAC__StreamEncoder *encoder,
1184 FLAC__StreamEncoderProgressCallback progress_callback,
1189 FLAC__StreamEncoderInitStatus init_status;
1191 FLAC__ASSERT(0 != encoder);
1192 FLAC__ASSERT(0 != file);
1194 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1195 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1197 /* double protection */
1199 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1200 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1204 * To make sure that our file does not go unclosed after an error, we
1205 * must assign the FILE pointer before any further error can occur in
1209 file = get_binary_stdout_(); /* just to be safe */
1211 encoder->private_->file = file;
1213 encoder->private_->progress_callback = progress_callback;
1214 encoder->private_->bytes_written = 0;
1215 encoder->private_->samples_written = 0;
1216 encoder->private_->frames_written = 0;
1218 init_status = init_stream_internal_(
1220 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1221 file_write_callback_,
1222 encoder->private_->file == stdout? 0 : file_seek_callback_,
1223 encoder->private_->file == stdout? 0 : file_tell_callback_,
1224 /*metadata_callback=*/0,
1228 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1229 /* the above function sets the state for us in case of an error */
1234 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1236 FLAC__ASSERT(blocksize != 0);
1237 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1243 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1244 FLAC__StreamEncoder *encoder,
1246 FLAC__StreamEncoderProgressCallback progress_callback,
1250 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1253 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1254 FLAC__StreamEncoder *encoder,
1256 FLAC__StreamEncoderProgressCallback progress_callback,
1260 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1263 static FLAC__StreamEncoderInitStatus init_file_internal_(
1264 FLAC__StreamEncoder *encoder,
1265 const char *filename,
1266 FLAC__StreamEncoderProgressCallback progress_callback,
1273 FLAC__ASSERT(0 != encoder);
1276 * To make sure that our file does not go unclosed after an error, we
1277 * have to do the same entrance checks here that are later performed
1278 * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1280 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1281 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1283 file = filename? fopen(filename, "w+b") : stdout;
1286 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1287 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1290 return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1293 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1294 FLAC__StreamEncoder *encoder,
1295 const char *filename,
1296 FLAC__StreamEncoderProgressCallback progress_callback,
1300 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1303 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1304 FLAC__StreamEncoder *encoder,
1305 const char *filename,
1306 FLAC__StreamEncoderProgressCallback progress_callback,
1310 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1313 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1315 FLAC__bool error = false;
1317 FLAC__ASSERT(0 != encoder);
1318 FLAC__ASSERT(0 != encoder->private_);
1319 FLAC__ASSERT(0 != encoder->protected_);
1321 if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1324 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1325 if(encoder->private_->current_sample_number != 0) {
1326 const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1327 encoder->protected_->blocksize = encoder->private_->current_sample_number;
1328 if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1333 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1335 if(!encoder->private_->is_being_deleted) {
1336 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1337 if(encoder->private_->seek_callback) {
1339 if(encoder->private_->is_ogg)
1340 update_ogg_metadata_(encoder);
1343 update_metadata_(encoder);
1345 /* check if an error occurred while updating metadata */
1346 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1349 if(encoder->private_->metadata_callback)
1350 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1353 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1355 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1360 if(0 != encoder->private_->file) {
1361 if(encoder->private_->file != stdout)
1362 fclose(encoder->private_->file);
1363 encoder->private_->file = 0;
1367 if(encoder->private_->is_ogg)
1368 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1372 set_defaults_(encoder);
1375 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1380 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1382 FLAC__ASSERT(0 != encoder);
1383 FLAC__ASSERT(0 != encoder->private_);
1384 FLAC__ASSERT(0 != encoder->protected_);
1385 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1388 /* can't check encoder->private_->is_ogg since that's not set until init time */
1389 FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1397 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1399 FLAC__ASSERT(0 != encoder);
1400 FLAC__ASSERT(0 != encoder->private_);
1401 FLAC__ASSERT(0 != encoder->protected_);
1402 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1404 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1405 encoder->protected_->verify = value;
1410 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1412 FLAC__ASSERT(0 != encoder);
1413 FLAC__ASSERT(0 != encoder->private_);
1414 FLAC__ASSERT(0 != encoder->protected_);
1415 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1417 encoder->protected_->streamable_subset = value;
1421 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1423 FLAC__ASSERT(0 != encoder);
1424 FLAC__ASSERT(0 != encoder->private_);
1425 FLAC__ASSERT(0 != encoder->protected_);
1426 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1428 encoder->protected_->channels = value;
1432 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1434 FLAC__ASSERT(0 != encoder);
1435 FLAC__ASSERT(0 != encoder->private_);
1436 FLAC__ASSERT(0 != encoder->protected_);
1437 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1439 encoder->protected_->bits_per_sample = value;
1443 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1445 FLAC__ASSERT(0 != encoder);
1446 FLAC__ASSERT(0 != encoder->private_);
1447 FLAC__ASSERT(0 != encoder->protected_);
1448 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1450 encoder->protected_->sample_rate = value;
1454 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1456 FLAC__bool ok = true;
1457 FLAC__ASSERT(0 != encoder);
1458 FLAC__ASSERT(0 != encoder->private_);
1459 FLAC__ASSERT(0 != encoder->protected_);
1460 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1462 if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1463 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1464 ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
1465 ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
1468 ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
1469 /* but it's too hard to specify the string in a locale-specific way */
1471 encoder->protected_->num_apodizations = 1;
1472 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1473 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1475 ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
1476 ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
1477 ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1478 ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
1479 ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
1480 ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1481 ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1482 ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
1486 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1488 FLAC__ASSERT(0 != encoder);
1489 FLAC__ASSERT(0 != encoder->private_);
1490 FLAC__ASSERT(0 != encoder->protected_);
1491 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1493 encoder->protected_->blocksize = value;
1497 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1499 FLAC__ASSERT(0 != encoder);
1500 FLAC__ASSERT(0 != encoder->private_);
1501 FLAC__ASSERT(0 != encoder->protected_);
1502 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1504 encoder->protected_->do_mid_side_stereo = value;
1508 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1510 FLAC__ASSERT(0 != encoder);
1511 FLAC__ASSERT(0 != encoder->private_);
1512 FLAC__ASSERT(0 != encoder->protected_);
1513 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1515 encoder->protected_->loose_mid_side_stereo = value;
1519 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1521 FLAC__ASSERT(0 != encoder);
1522 FLAC__ASSERT(0 != encoder->private_);
1523 FLAC__ASSERT(0 != encoder->protected_);
1524 FLAC__ASSERT(0 != specification);
1525 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1527 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1528 (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1530 encoder->protected_->num_apodizations = 0;
1532 const char *s = strchr(specification, ';');
1533 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1534 if (n==8 && 0 == strncmp("bartlett" , specification, n))
1535 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1536 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1537 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1538 else if(n==8 && 0 == strncmp("blackman" , specification, n))
1539 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1540 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1541 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1542 else if(n==6 && 0 == strncmp("connes" , specification, n))
1543 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1544 else if(n==7 && 0 == strncmp("flattop" , specification, n))
1545 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1546 else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
1547 FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1548 if (stddev > 0.0 && stddev <= 0.5) {
1549 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1550 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1553 else if(n==7 && 0 == strncmp("hamming" , specification, n))
1554 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1555 else if(n==4 && 0 == strncmp("hann" , specification, n))
1556 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1557 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1558 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1559 else if(n==7 && 0 == strncmp("nuttall" , specification, n))
1560 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1561 else if(n==9 && 0 == strncmp("rectangle" , specification, n))
1562 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1563 else if(n==8 && 0 == strncmp("triangle" , specification, n))
1564 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1565 else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
1566 FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1567 if (p >= 0.0 && p <= 1.0) {
1568 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1569 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1572 else if(n==5 && 0 == strncmp("welch" , specification, n))
1573 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1574 if (encoder->protected_->num_apodizations == 32)
1577 specification = s+1;
1581 if(encoder->protected_->num_apodizations == 0) {
1582 encoder->protected_->num_apodizations = 1;
1583 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1584 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1590 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1592 FLAC__ASSERT(0 != encoder);
1593 FLAC__ASSERT(0 != encoder->private_);
1594 FLAC__ASSERT(0 != encoder->protected_);
1595 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1597 encoder->protected_->max_lpc_order = value;
1601 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1603 FLAC__ASSERT(0 != encoder);
1604 FLAC__ASSERT(0 != encoder->private_);
1605 FLAC__ASSERT(0 != encoder->protected_);
1606 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1608 encoder->protected_->qlp_coeff_precision = value;
1612 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1614 FLAC__ASSERT(0 != encoder);
1615 FLAC__ASSERT(0 != encoder->private_);
1616 FLAC__ASSERT(0 != encoder->protected_);
1617 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1619 encoder->protected_->do_qlp_coeff_prec_search = value;
1623 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1625 FLAC__ASSERT(0 != encoder);
1626 FLAC__ASSERT(0 != encoder->private_);
1627 FLAC__ASSERT(0 != encoder->protected_);
1628 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1631 /*@@@ deprecated: */
1632 encoder->protected_->do_escape_coding = value;
1639 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1641 FLAC__ASSERT(0 != encoder);
1642 FLAC__ASSERT(0 != encoder->private_);
1643 FLAC__ASSERT(0 != encoder->protected_);
1644 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1646 encoder->protected_->do_exhaustive_model_search = value;
1650 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1652 FLAC__ASSERT(0 != encoder);
1653 FLAC__ASSERT(0 != encoder->private_);
1654 FLAC__ASSERT(0 != encoder->protected_);
1655 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1657 encoder->protected_->min_residual_partition_order = value;
1661 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1663 FLAC__ASSERT(0 != encoder);
1664 FLAC__ASSERT(0 != encoder->private_);
1665 FLAC__ASSERT(0 != encoder->protected_);
1666 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1668 encoder->protected_->max_residual_partition_order = value;
1672 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1674 FLAC__ASSERT(0 != encoder);
1675 FLAC__ASSERT(0 != encoder->private_);
1676 FLAC__ASSERT(0 != encoder->protected_);
1677 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1680 /*@@@ deprecated: */
1681 encoder->protected_->rice_parameter_search_dist = value;
1688 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1690 FLAC__ASSERT(0 != encoder);
1691 FLAC__ASSERT(0 != encoder->private_);
1692 FLAC__ASSERT(0 != encoder->protected_);
1693 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1695 encoder->protected_->total_samples_estimate = value;
1699 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1701 FLAC__ASSERT(0 != encoder);
1702 FLAC__ASSERT(0 != encoder->private_);
1703 FLAC__ASSERT(0 != encoder->protected_);
1704 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1710 /* realloc() does not do exactly what we want so... */
1711 if(encoder->protected_->metadata) {
1712 free(encoder->protected_->metadata);
1713 encoder->protected_->metadata = 0;
1714 encoder->protected_->num_metadata_blocks = 0;
1717 FLAC__StreamMetadata **m;
1718 if(0 == (m = (FLAC__StreamMetadata**)malloc(sizeof(m[0]) * num_blocks)))
1720 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1721 encoder->protected_->metadata = m;
1722 encoder->protected_->num_metadata_blocks = num_blocks;
1725 if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1732 * These three functions are not static, but not publically exposed in
1733 * include/FLAC/ either. They are used by the test suite.
1735 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1737 FLAC__ASSERT(0 != encoder);
1738 FLAC__ASSERT(0 != encoder->private_);
1739 FLAC__ASSERT(0 != encoder->protected_);
1740 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1742 encoder->private_->disable_constant_subframes = value;
1746 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1748 FLAC__ASSERT(0 != encoder);
1749 FLAC__ASSERT(0 != encoder->private_);
1750 FLAC__ASSERT(0 != encoder->protected_);
1751 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1753 encoder->private_->disable_fixed_subframes = value;
1757 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1759 FLAC__ASSERT(0 != encoder);
1760 FLAC__ASSERT(0 != encoder->private_);
1761 FLAC__ASSERT(0 != encoder->protected_);
1762 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1764 encoder->private_->disable_verbatim_subframes = value;
1768 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1770 FLAC__ASSERT(0 != encoder);
1771 FLAC__ASSERT(0 != encoder->private_);
1772 FLAC__ASSERT(0 != encoder->protected_);
1773 return encoder->protected_->state;
1776 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1778 FLAC__ASSERT(0 != encoder);
1779 FLAC__ASSERT(0 != encoder->private_);
1780 FLAC__ASSERT(0 != encoder->protected_);
1781 if(encoder->protected_->verify)
1782 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1784 return FLAC__STREAM_DECODER_UNINITIALIZED;
1787 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1789 FLAC__ASSERT(0 != encoder);
1790 FLAC__ASSERT(0 != encoder->private_);
1791 FLAC__ASSERT(0 != encoder->protected_);
1792 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1793 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1795 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1798 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)
1800 FLAC__ASSERT(0 != encoder);
1801 FLAC__ASSERT(0 != encoder->private_);
1802 FLAC__ASSERT(0 != encoder->protected_);
1803 if(0 != absolute_sample)
1804 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1805 if(0 != frame_number)
1806 *frame_number = encoder->private_->verify.error_stats.frame_number;
1808 *channel = encoder->private_->verify.error_stats.channel;
1810 *sample = encoder->private_->verify.error_stats.sample;
1812 *expected = encoder->private_->verify.error_stats.expected;
1814 *got = encoder->private_->verify.error_stats.got;
1817 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1819 FLAC__ASSERT(0 != encoder);
1820 FLAC__ASSERT(0 != encoder->private_);
1821 FLAC__ASSERT(0 != encoder->protected_);
1822 return encoder->protected_->verify;
1825 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1827 FLAC__ASSERT(0 != encoder);
1828 FLAC__ASSERT(0 != encoder->private_);
1829 FLAC__ASSERT(0 != encoder->protected_);
1830 return encoder->protected_->streamable_subset;
1833 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1835 FLAC__ASSERT(0 != encoder);
1836 FLAC__ASSERT(0 != encoder->private_);
1837 FLAC__ASSERT(0 != encoder->protected_);
1838 return encoder->protected_->channels;
1841 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1843 FLAC__ASSERT(0 != encoder);
1844 FLAC__ASSERT(0 != encoder->private_);
1845 FLAC__ASSERT(0 != encoder->protected_);
1846 return encoder->protected_->bits_per_sample;
1849 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1851 FLAC__ASSERT(0 != encoder);
1852 FLAC__ASSERT(0 != encoder->private_);
1853 FLAC__ASSERT(0 != encoder->protected_);
1854 return encoder->protected_->sample_rate;
1857 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1859 FLAC__ASSERT(0 != encoder);
1860 FLAC__ASSERT(0 != encoder->private_);
1861 FLAC__ASSERT(0 != encoder->protected_);
1862 return encoder->protected_->blocksize;
1865 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1867 FLAC__ASSERT(0 != encoder);
1868 FLAC__ASSERT(0 != encoder->private_);
1869 FLAC__ASSERT(0 != encoder->protected_);
1870 return encoder->protected_->do_mid_side_stereo;
1873 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1875 FLAC__ASSERT(0 != encoder);
1876 FLAC__ASSERT(0 != encoder->private_);
1877 FLAC__ASSERT(0 != encoder->protected_);
1878 return encoder->protected_->loose_mid_side_stereo;
1881 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1883 FLAC__ASSERT(0 != encoder);
1884 FLAC__ASSERT(0 != encoder->private_);
1885 FLAC__ASSERT(0 != encoder->protected_);
1886 return encoder->protected_->max_lpc_order;
1889 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1891 FLAC__ASSERT(0 != encoder);
1892 FLAC__ASSERT(0 != encoder->private_);
1893 FLAC__ASSERT(0 != encoder->protected_);
1894 return encoder->protected_->qlp_coeff_precision;
1897 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1899 FLAC__ASSERT(0 != encoder);
1900 FLAC__ASSERT(0 != encoder->private_);
1901 FLAC__ASSERT(0 != encoder->protected_);
1902 return encoder->protected_->do_qlp_coeff_prec_search;
1905 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1907 FLAC__ASSERT(0 != encoder);
1908 FLAC__ASSERT(0 != encoder->private_);
1909 FLAC__ASSERT(0 != encoder->protected_);
1910 return encoder->protected_->do_escape_coding;
1913 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1915 FLAC__ASSERT(0 != encoder);
1916 FLAC__ASSERT(0 != encoder->private_);
1917 FLAC__ASSERT(0 != encoder->protected_);
1918 return encoder->protected_->do_exhaustive_model_search;
1921 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1923 FLAC__ASSERT(0 != encoder);
1924 FLAC__ASSERT(0 != encoder->private_);
1925 FLAC__ASSERT(0 != encoder->protected_);
1926 return encoder->protected_->min_residual_partition_order;
1929 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1931 FLAC__ASSERT(0 != encoder);
1932 FLAC__ASSERT(0 != encoder->private_);
1933 FLAC__ASSERT(0 != encoder->protected_);
1934 return encoder->protected_->max_residual_partition_order;
1937 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1939 FLAC__ASSERT(0 != encoder);
1940 FLAC__ASSERT(0 != encoder->private_);
1941 FLAC__ASSERT(0 != encoder->protected_);
1942 return encoder->protected_->rice_parameter_search_dist;
1945 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1947 FLAC__ASSERT(0 != encoder);
1948 FLAC__ASSERT(0 != encoder->private_);
1949 FLAC__ASSERT(0 != encoder->protected_);
1950 return encoder->protected_->total_samples_estimate;
1953 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1955 unsigned i, j, channel;
1956 FLAC__int32 x, mid, side;
1957 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1959 FLAC__ASSERT(0 != encoder);
1960 FLAC__ASSERT(0 != encoder->private_);
1961 FLAC__ASSERT(0 != encoder->protected_);
1962 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1966 * we have several flavors of the same basic loop, optimized for
1967 * different conditions:
1969 if(encoder->protected_->max_lpc_order > 0) {
1970 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1972 * stereo coding: unroll channel loop
1973 * with LPC: calculate floating point version of signal
1976 if(encoder->protected_->verify)
1977 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
1979 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
1980 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1981 x = mid = side = buffer[0][j];
1982 encoder->private_->integer_signal[0][i] = x;
1983 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1984 encoder->private_->real_signal[0][i] = (FLAC__real)x;
1987 encoder->private_->integer_signal[1][i] = x;
1988 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1989 encoder->private_->real_signal[1][i] = (FLAC__real)x;
1993 mid >>= 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
1994 encoder->private_->integer_signal_mid_side[1][i] = side;
1995 encoder->private_->integer_signal_mid_side[0][i] = mid;
1996 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1997 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
1998 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
2000 encoder->private_->current_sample_number++;
2002 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2004 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2006 /* move unprocessed overread samples to beginnings of arrays */
2007 FLAC__ASSERT(i == blocksize+OVERREAD_);
2008 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2010 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2011 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2012 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2013 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2014 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2015 encoder->private_->real_signal[0][0] = encoder->private_->real_signal[0][i];
2016 encoder->private_->real_signal[1][0] = encoder->private_->real_signal[1][i];
2017 encoder->private_->real_signal_mid_side[0][0] = encoder->private_->real_signal_mid_side[0][i];
2018 encoder->private_->real_signal_mid_side[1][0] = encoder->private_->real_signal_mid_side[1][i];
2020 encoder->private_->current_sample_number = 1;
2022 } while(j < samples);
2026 * independent channel coding: buffer each channel in inner loop
2027 * with LPC: calculate floating point version of signal
2030 if(encoder->protected_->verify)
2031 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2033 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2034 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2035 for(channel = 0; channel < channels; channel++) {
2036 x = buffer[channel][j];
2037 encoder->private_->integer_signal[channel][i] = x;
2038 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2039 encoder->private_->real_signal[channel][i] = (FLAC__real)x;
2042 encoder->private_->current_sample_number++;
2044 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2046 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2048 /* move unprocessed overread samples to beginnings of arrays */
2049 FLAC__ASSERT(i == blocksize+OVERREAD_);
2050 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2052 for(channel = 0; channel < channels; channel++) {
2053 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2054 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2055 encoder->private_->real_signal[channel][0] = encoder->private_->real_signal[channel][i];
2058 encoder->private_->current_sample_number = 1;
2060 } while(j < samples);
2064 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2066 * stereo coding: unroll channel loop
2067 * without LPC: no need to calculate floating point version of signal
2070 if(encoder->protected_->verify)
2071 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2073 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2074 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2075 encoder->private_->integer_signal[0][i] = mid = side = buffer[0][j];
2077 encoder->private_->integer_signal[1][i] = x;
2080 mid >>= 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
2081 encoder->private_->integer_signal_mid_side[1][i] = side;
2082 encoder->private_->integer_signal_mid_side[0][i] = mid;
2083 encoder->private_->current_sample_number++;
2085 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2087 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2089 /* move unprocessed overread samples to beginnings of arrays */
2090 FLAC__ASSERT(i == blocksize+OVERREAD_);
2091 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2093 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2094 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2095 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2096 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2097 encoder->private_->current_sample_number = 1;
2099 } while(j < samples);
2103 * independent channel coding: buffer each channel in inner loop
2104 * without LPC: no need to calculate floating point version of signal
2107 if(encoder->protected_->verify)
2108 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2110 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2111 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2112 for(channel = 0; channel < channels; channel++)
2113 encoder->private_->integer_signal[channel][i] = buffer[channel][j];
2114 encoder->private_->current_sample_number++;
2116 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2118 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2120 /* move unprocessed overread samples to beginnings of arrays */
2121 FLAC__ASSERT(i == blocksize+OVERREAD_);
2122 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2124 for(channel = 0; channel < channels; channel++)
2125 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2126 encoder->private_->current_sample_number = 1;
2128 } while(j < samples);
2135 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2137 unsigned i, j, k, channel;
2138 FLAC__int32 x, mid, side;
2139 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2141 FLAC__ASSERT(0 != encoder);
2142 FLAC__ASSERT(0 != encoder->private_);
2143 FLAC__ASSERT(0 != encoder->protected_);
2144 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2148 * we have several flavors of the same basic loop, optimized for
2149 * different conditions:
2151 if(encoder->protected_->max_lpc_order > 0) {
2152 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2154 * stereo coding: unroll channel loop
2155 * with LPC: calculate floating point version of signal
2158 if(encoder->protected_->verify)
2159 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2161 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2162 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2163 x = mid = side = buffer[k++];
2164 encoder->private_->integer_signal[0][i] = x;
2165 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2166 encoder->private_->real_signal[0][i] = (FLAC__real)x;
2169 encoder->private_->integer_signal[1][i] = x;
2170 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2171 encoder->private_->real_signal[1][i] = (FLAC__real)x;
2175 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2176 encoder->private_->integer_signal_mid_side[1][i] = side;
2177 encoder->private_->integer_signal_mid_side[0][i] = mid;
2178 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2179 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
2180 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
2182 encoder->private_->current_sample_number++;
2184 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2186 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2188 /* move unprocessed overread samples to beginnings of arrays */
2189 FLAC__ASSERT(i == blocksize+OVERREAD_);
2190 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2192 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2193 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2194 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2195 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2196 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2197 encoder->private_->real_signal[0][0] = encoder->private_->real_signal[0][i];
2198 encoder->private_->real_signal[1][0] = encoder->private_->real_signal[1][i];
2199 encoder->private_->real_signal_mid_side[0][0] = encoder->private_->real_signal_mid_side[0][i];
2200 encoder->private_->real_signal_mid_side[1][0] = encoder->private_->real_signal_mid_side[1][i];
2202 encoder->private_->current_sample_number = 1;
2204 } while(j < samples);
2208 * independent channel coding: buffer each channel in inner loop
2209 * with LPC: calculate floating point version of signal
2212 if(encoder->protected_->verify)
2213 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2215 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2216 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2217 for(channel = 0; channel < channels; channel++) {
2219 encoder->private_->integer_signal[channel][i] = x;
2220 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2221 encoder->private_->real_signal[channel][i] = (FLAC__real)x;
2224 encoder->private_->current_sample_number++;
2226 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2228 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2230 /* move unprocessed overread samples to beginnings of arrays */
2231 FLAC__ASSERT(i == blocksize+OVERREAD_);
2232 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2234 for(channel = 0; channel < channels; channel++) {
2235 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2236 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2237 encoder->private_->real_signal[channel][0] = encoder->private_->real_signal[channel][i];
2240 encoder->private_->current_sample_number = 1;
2242 } while(j < samples);
2246 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2248 * stereo coding: unroll channel loop
2249 * without LPC: no need to calculate floating point version of signal
2252 if(encoder->protected_->verify)
2253 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2255 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2256 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2257 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2259 encoder->private_->integer_signal[1][i] = x;
2262 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2263 encoder->private_->integer_signal_mid_side[1][i] = side;
2264 encoder->private_->integer_signal_mid_side[0][i] = mid;
2265 encoder->private_->current_sample_number++;
2267 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2269 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2271 /* move unprocessed overread samples to beginnings of arrays */
2272 FLAC__ASSERT(i == blocksize+OVERREAD_);
2273 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2275 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2276 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2277 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2278 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2279 encoder->private_->current_sample_number = 1;
2281 } while(j < samples);
2285 * independent channel coding: buffer each channel in inner loop
2286 * without LPC: no need to calculate floating point version of signal
2289 if(encoder->protected_->verify)
2290 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2292 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2293 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2294 for(channel = 0; channel < channels; channel++)
2295 encoder->private_->integer_signal[channel][i] = buffer[k++];
2296 encoder->private_->current_sample_number++;
2298 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2300 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2302 /* move unprocessed overread samples to beginnings of arrays */
2303 FLAC__ASSERT(i == blocksize+OVERREAD_);
2304 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2306 for(channel = 0; channel < channels; channel++)
2307 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2308 encoder->private_->current_sample_number = 1;
2310 } while(j < samples);
2317 /***********************************************************************
2319 * Private class methods
2321 ***********************************************************************/
2323 void set_defaults_(FLAC__StreamEncoder *encoder)
2325 FLAC__ASSERT(0 != encoder);
2327 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2328 encoder->protected_->verify = true;
2330 encoder->protected_->verify = false;
2332 encoder->protected_->streamable_subset = true;
2333 encoder->protected_->do_mid_side_stereo = false;
2334 encoder->protected_->loose_mid_side_stereo = false;
2335 encoder->protected_->channels = 2;
2336 encoder->protected_->bits_per_sample = 16;
2337 encoder->protected_->sample_rate = 44100;
2338 encoder->protected_->blocksize = 0;
2339 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2340 encoder->protected_->num_apodizations = 1;
2341 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2342 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2344 encoder->protected_->max_lpc_order = 0;
2345 encoder->protected_->qlp_coeff_precision = 0;
2346 encoder->protected_->do_qlp_coeff_prec_search = false;
2347 encoder->protected_->do_exhaustive_model_search = false;
2348 encoder->protected_->do_escape_coding = false;
2349 encoder->protected_->min_residual_partition_order = 0;
2350 encoder->protected_->max_residual_partition_order = 0;
2351 encoder->protected_->rice_parameter_search_dist = 0;
2352 encoder->protected_->total_samples_estimate = 0;
2353 encoder->protected_->metadata = 0;
2354 encoder->protected_->num_metadata_blocks = 0;
2356 encoder->private_->seek_table = 0;
2357 encoder->private_->disable_constant_subframes = false;
2358 encoder->private_->disable_fixed_subframes = false;
2359 encoder->private_->disable_verbatim_subframes = false;
2361 encoder->private_->is_ogg = false;
2363 encoder->private_->read_callback = 0;
2364 encoder->private_->write_callback = 0;
2365 encoder->private_->seek_callback = 0;
2366 encoder->private_->tell_callback = 0;
2367 encoder->private_->metadata_callback = 0;
2368 encoder->private_->progress_callback = 0;
2369 encoder->private_->client_data = 0;
2372 FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2376 void free_(FLAC__StreamEncoder *encoder)
2378 unsigned i, channel;
2380 FLAC__ASSERT(0 != encoder);
2381 if(encoder->protected_->metadata) {
2382 free(encoder->protected_->metadata);
2383 encoder->protected_->metadata = 0;
2384 encoder->protected_->num_metadata_blocks = 0;
2386 for(i = 0; i < encoder->protected_->channels; i++) {
2387 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2388 free(encoder->private_->integer_signal_unaligned[i]);
2389 encoder->private_->integer_signal_unaligned[i] = 0;
2391 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2392 if(0 != encoder->private_->real_signal_unaligned[i]) {
2393 free(encoder->private_->real_signal_unaligned[i]);
2394 encoder->private_->real_signal_unaligned[i] = 0;
2398 for(i = 0; i < 2; i++) {
2399 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2400 free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2401 encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2403 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2404 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2405 free(encoder->private_->real_signal_mid_side_unaligned[i]);
2406 encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2410 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2411 for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2412 if(0 != encoder->private_->window_unaligned[i]) {
2413 free(encoder->private_->window_unaligned[i]);
2414 encoder->private_->window_unaligned[i] = 0;
2417 if(0 != encoder->private_->windowed_signal_unaligned) {
2418 free(encoder->private_->windowed_signal_unaligned);
2419 encoder->private_->windowed_signal_unaligned = 0;
2422 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2423 for(i = 0; i < 2; i++) {
2424 if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2425 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2426 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2430 for(channel = 0; channel < 2; channel++) {
2431 for(i = 0; i < 2; i++) {
2432 if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2433 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2434 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2438 if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2439 free(encoder->private_->abs_residual_partition_sums_unaligned);
2440 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2442 if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2443 free(encoder->private_->raw_bits_per_partition_unaligned);
2444 encoder->private_->raw_bits_per_partition_unaligned = 0;
2446 if(encoder->protected_->verify) {
2447 for(i = 0; i < encoder->protected_->channels; i++) {
2448 if(0 != encoder->private_->verify.input_fifo.data[i]) {
2449 free(encoder->private_->verify.input_fifo.data[i]);
2450 encoder->private_->verify.input_fifo.data[i] = 0;
2454 FLAC__bitwriter_free(encoder->private_->frame);
2457 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2460 unsigned i, channel;
2462 FLAC__ASSERT(new_blocksize > 0);
2463 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2464 FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2466 /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2467 if(new_blocksize <= encoder->private_->input_capacity)
2472 /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
2473 * requires that the input arrays (in our case the integer signals)
2474 * have a buffer of up to 3 zeroes in front (at negative indices) for
2475 * alignment purposes; we use 4 in front to keep the data well-aligned.
2478 for(i = 0; ok && i < encoder->protected_->channels; i++) {
2479 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2480 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2481 encoder->private_->integer_signal[i] += 4;
2482 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2483 if(encoder->protected_->max_lpc_order > 0)
2484 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2487 for(i = 0; ok && i < 2; i++) {
2488 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]);
2489 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2490 encoder->private_->integer_signal_mid_side[i] += 4;
2491 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2492 if(encoder->protected_->max_lpc_order > 0)
2493 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]);
2496 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2497 if(ok && encoder->protected_->max_lpc_order > 0) {
2498 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2499 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2500 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2503 for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2504 for(i = 0; ok && i < 2; i++) {
2505 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2508 for(channel = 0; ok && channel < 2; channel++) {
2509 for(i = 0; ok && i < 2; i++) {
2510 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]);
2513 /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2514 /*@@@ 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) */
2515 ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2516 if(encoder->protected_->do_escape_coding)
2517 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2519 /* now adjust the windows if the blocksize has changed */
2520 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2521 if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2522 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2523 switch(encoder->protected_->apodizations[i].type) {
2524 case FLAC__APODIZATION_BARTLETT:
2525 FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2527 case FLAC__APODIZATION_BARTLETT_HANN:
2528 FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2530 case FLAC__APODIZATION_BLACKMAN:
2531 FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2533 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2534 FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2536 case FLAC__APODIZATION_CONNES:
2537 FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2539 case FLAC__APODIZATION_FLATTOP:
2540 FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2542 case FLAC__APODIZATION_GAUSS:
2543 FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2545 case FLAC__APODIZATION_HAMMING:
2546 FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2548 case FLAC__APODIZATION_HANN:
2549 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2551 case FLAC__APODIZATION_KAISER_BESSEL:
2552 FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2554 case FLAC__APODIZATION_NUTTALL:
2555 FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2557 case FLAC__APODIZATION_RECTANGLE:
2558 FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2560 case FLAC__APODIZATION_TRIANGLE:
2561 FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2563 case FLAC__APODIZATION_TUKEY:
2564 FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2566 case FLAC__APODIZATION_WELCH:
2567 FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2571 /* double protection */
2572 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2580 encoder->private_->input_capacity = new_blocksize;
2582 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2587 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2589 const FLAC__byte *buffer;
2592 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2594 if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2595 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2599 if(encoder->protected_->verify) {
2600 encoder->private_->verify.output.data = buffer;
2601 encoder->private_->verify.output.bytes = bytes;
2602 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2603 encoder->private_->verify.needs_magic_hack = true;
2606 if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2607 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2608 FLAC__bitwriter_clear(encoder->private_->frame);
2609 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2610 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2616 if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2617 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2618 FLAC__bitwriter_clear(encoder->private_->frame);
2619 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2623 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2624 FLAC__bitwriter_clear(encoder->private_->frame);
2627 encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2628 encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2634 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2636 FLAC__StreamEncoderWriteStatus status;
2637 FLAC__uint64 output_position = 0;
2639 /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2640 if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2641 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2642 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2646 * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2649 FLAC__MetadataType type = (buffer[0] & 0x7f);
2650 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2651 encoder->protected_->streaminfo_offset = output_position;
2652 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2653 encoder->protected_->seektable_offset = output_position;
2657 * Mark the current seek point if hit (if audio_offset == 0 that
2658 * means we're still writing metadata and haven't hit the first
2661 if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2662 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2663 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2664 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2665 FLAC__uint64 test_sample;
2667 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2668 test_sample = encoder->private_->seek_table->points[i].sample_number;
2669 if(test_sample > frame_last_sample) {
2672 else if(test_sample >= frame_first_sample) {
2673 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2674 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2675 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2676 encoder->private_->first_seekpoint_to_check++;
2677 /* DO NOT: "break;" and here's why:
2678 * The seektable template may contain more than one target
2679 * sample for any given frame; we will keep looping, generating
2680 * duplicate seekpoints for them, and we'll clean it up later,
2681 * just before writing the seektable back to the metadata.
2685 encoder->private_->first_seekpoint_to_check++;
2691 if(encoder->private_->is_ogg) {
2692 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2693 &encoder->protected_->ogg_encoder_aspect,
2697 encoder->private_->current_frame_number,
2699 (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2701 encoder->private_->client_data
2706 status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2708 if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2709 encoder->private_->bytes_written += bytes;
2710 encoder->private_->samples_written += samples;
2711 /* we keep a high watermark on the number of frames written because
2712 * when the encoder goes back to write metadata, 'current_frame'
2713 * will drop back to 0.
2715 encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2718 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2723 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2724 void update_metadata_(const FLAC__StreamEncoder *encoder)
2726 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2727 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2728 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2729 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2730 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2731 const unsigned bps = metadata->data.stream_info.bits_per_sample;
2732 FLAC__StreamEncoderSeekStatus seek_status;
2734 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2736 /* All this is based on intimate knowledge of the stream header
2737 * layout, but a change to the header format that would break this
2738 * would also break all streams encoded in the previous format.
2742 * Write MD5 signature
2745 const unsigned md5_offset =
2746 FLAC__STREAM_METADATA_HEADER_LENGTH +
2748 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2749 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2750 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2751 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2752 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2753 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2754 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2755 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2758 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2759 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2760 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2763 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2764 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2770 * Write total samples
2773 const unsigned total_samples_byte_offset =
2774 FLAC__STREAM_METADATA_HEADER_LENGTH +
2776 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2777 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2778 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2779 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2780 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2781 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2782 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2786 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2787 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2788 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2789 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2790 b[4] = (FLAC__byte)(samples & 0xFF);
2791 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) {
2792 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2793 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2796 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2797 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2803 * Write min/max framesize
2806 const unsigned min_framesize_offset =
2807 FLAC__STREAM_METADATA_HEADER_LENGTH +
2809 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2810 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2813 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2814 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2815 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2816 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2817 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2818 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2819 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) {
2820 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2821 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2824 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2825 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2833 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2836 FLAC__format_seektable_sort(encoder->private_->seek_table);
2838 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2840 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) {
2841 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2842 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2846 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2849 xx = encoder->private_->seek_table->points[i].sample_number;
2850 b[7] = (FLAC__byte)xx; xx >>= 8;
2851 b[6] = (FLAC__byte)xx; xx >>= 8;
2852 b[5] = (FLAC__byte)xx; xx >>= 8;
2853 b[4] = (FLAC__byte)xx; xx >>= 8;
2854 b[3] = (FLAC__byte)xx; xx >>= 8;
2855 b[2] = (FLAC__byte)xx; xx >>= 8;
2856 b[1] = (FLAC__byte)xx; xx >>= 8;
2857 b[0] = (FLAC__byte)xx; xx >>= 8;
2858 xx = encoder->private_->seek_table->points[i].stream_offset;
2859 b[15] = (FLAC__byte)xx; xx >>= 8;
2860 b[14] = (FLAC__byte)xx; xx >>= 8;
2861 b[13] = (FLAC__byte)xx; xx >>= 8;
2862 b[12] = (FLAC__byte)xx; xx >>= 8;
2863 b[11] = (FLAC__byte)xx; xx >>= 8;
2864 b[10] = (FLAC__byte)xx; xx >>= 8;
2865 b[9] = (FLAC__byte)xx; xx >>= 8;
2866 b[8] = (FLAC__byte)xx; xx >>= 8;
2867 x = encoder->private_->seek_table->points[i].frame_samples;
2868 b[17] = (FLAC__byte)x; x >>= 8;
2869 b[16] = (FLAC__byte)x; x >>= 8;
2870 if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2871 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2879 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2880 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2882 /* the # of bytes in the 1st packet that precede the STREAMINFO */
2883 static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2884 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2885 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2886 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2887 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2888 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2889 FLAC__STREAM_SYNC_LENGTH
2891 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2892 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2893 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2894 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2895 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2898 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2899 FLAC__ASSERT(0 != encoder->private_->seek_callback);
2901 /* Pre-check that client supports seeking, since we don't want the
2902 * ogg_helper code to ever have to deal with this condition.
2904 if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2907 /* All this is based on intimate knowledge of the stream header
2908 * layout, but a change to the header format that would break this
2909 * would also break all streams encoded in the previous format.
2913 ** Write STREAMINFO stats
2915 simple_ogg_page__init(&page);
2916 if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2917 simple_ogg_page__clear(&page);
2918 return; /* state already set */
2922 * Write MD5 signature
2925 const unsigned md5_offset =
2926 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2927 FLAC__STREAM_METADATA_HEADER_LENGTH +
2929 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2930 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2931 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2932 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2933 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2934 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2935 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2936 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2939 if(md5_offset + 16 > (unsigned)page.body_len) {
2940 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2941 simple_ogg_page__clear(&page);
2944 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2948 * Write total samples
2951 const unsigned total_samples_byte_offset =
2952 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2953 FLAC__STREAM_METADATA_HEADER_LENGTH +
2955 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2956 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2957 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2958 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2959 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2960 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2961 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2965 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2966 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2967 simple_ogg_page__clear(&page);
2970 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2971 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2972 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2973 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2974 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2975 b[4] = (FLAC__byte)(samples & 0xFF);
2976 memcpy(page.body + total_samples_byte_offset, b, 5);
2980 * Write min/max framesize
2983 const unsigned min_framesize_offset =
2984 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2985 FLAC__STREAM_METADATA_HEADER_LENGTH +
2987 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2988 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2991 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2992 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2993 simple_ogg_page__clear(&page);
2996 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2997 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2998 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2999 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
3000 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
3001 b[5] = (FLAC__byte)(max_framesize & 0xFF);
3002 memcpy(page.body + min_framesize_offset, b, 6);
3004 if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
3005 simple_ogg_page__clear(&page);
3006 return; /* state already set */
3008 simple_ogg_page__clear(&page);
3013 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
3017 FLAC__format_seektable_sort(encoder->private_->seek_table);
3019 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
3021 simple_ogg_page__init(&page);
3022 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
3023 simple_ogg_page__clear(&page);
3024 return; /* state already set */
3027 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
3028 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
3029 simple_ogg_page__clear(&page);
3033 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
3036 xx = encoder->private_->seek_table->points[i].sample_number;
3037 b[7] = (FLAC__byte)xx; xx >>= 8;
3038 b[6] = (FLAC__byte)xx; xx >>= 8;
3039 b[5] = (FLAC__byte)xx; xx >>= 8;
3040 b[4] = (FLAC__byte)xx; xx >>= 8;
3041 b[3] = (FLAC__byte)xx; xx >>= 8;
3042 b[2] = (FLAC__byte)xx; xx >>= 8;
3043 b[1] = (FLAC__byte)xx; xx >>= 8;
3044 b[0] = (FLAC__byte)xx; xx >>= 8;
3045 xx = encoder->private_->seek_table->points[i].stream_offset;
3046 b[15] = (FLAC__byte)xx; xx >>= 8;
3047 b[14] = (FLAC__byte)xx; xx >>= 8;
3048 b[13] = (FLAC__byte)xx; xx >>= 8;
3049 b[12] = (FLAC__byte)xx; xx >>= 8;
3050 b[11] = (FLAC__byte)xx; xx >>= 8;
3051 b[10] = (FLAC__byte)xx; xx >>= 8;
3052 b[9] = (FLAC__byte)xx; xx >>= 8;
3053 b[8] = (FLAC__byte)xx; xx >>= 8;
3054 x = encoder->private_->seek_table->points[i].frame_samples;
3055 b[17] = (FLAC__byte)x; x >>= 8;
3056 b[16] = (FLAC__byte)x; x >>= 8;
3060 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
3061 simple_ogg_page__clear(&page);
3062 return; /* state already set */
3064 simple_ogg_page__clear(&page);
3069 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
3072 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
3075 * Accumulate raw signal to the MD5 signature
3077 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)) {
3078 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3083 * Process the frame header and subframes into the frame bitbuffer
3085 if(!process_subframes_(encoder, is_fractional_block)) {
3086 /* the above function sets the state for us in case of an error */
3091 * Zero-pad the frame to a byte_boundary
3093 if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
3094 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3099 * CRC-16 the whole thing
3101 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
3103 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
3104 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
3106 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3113 if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
3114 /* the above function sets the state for us in case of an error */
3119 * Get ready for the next frame
3121 encoder->private_->current_sample_number = 0;
3122 encoder->private_->current_frame_number++;
3123 encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
3128 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
3130 FLAC__FrameHeader frame_header;
3131 unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
3132 FLAC__bool do_independent, do_mid_side;
3135 * Calculate the min,max Rice partition orders
3137 if(is_fractional_block) {
3138 max_partition_order = 0;
3141 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
3142 max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
3144 min_partition_order = min(min_partition_order, max_partition_order);
3149 frame_header.blocksize = encoder->protected_->blocksize;
3150 frame_header.sample_rate = encoder->protected_->sample_rate;
3151 frame_header.channels = encoder->protected_->channels;
3152 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
3153 frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
3154 frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
3155 frame_header.number.frame_number = encoder->private_->current_frame_number;
3158 * Figure out what channel assignments to try
3160 if(encoder->protected_->do_mid_side_stereo) {
3161 if(encoder->protected_->loose_mid_side_stereo) {
3162 if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
3163 do_independent = true;
3167 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
3168 do_mid_side = !do_independent;
3172 do_independent = true;
3177 do_independent = true;
3178 do_mid_side = false;
3181 FLAC__ASSERT(do_independent || do_mid_side);
3184 * Check for wasted bits; set effective bps for each subframe
3186 if(do_independent) {
3187 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3188 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
3189 encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
3190 encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
3194 FLAC__ASSERT(encoder->protected_->channels == 2);
3195 for(channel = 0; channel < 2; channel++) {
3196 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
3197 encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
3198 encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
3203 * First do a normal encoding pass of each independent channel
3205 if(do_independent) {
3206 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3210 min_partition_order,
3211 max_partition_order,
3213 encoder->private_->subframe_bps[channel],
3214 encoder->private_->integer_signal[channel],
3215 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3216 encoder->private_->real_signal[channel],
3218 encoder->private_->subframe_workspace_ptr[channel],
3219 encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3220 encoder->private_->residual_workspace[channel],
3221 encoder->private_->best_subframe+channel,
3222 encoder->private_->best_subframe_bits+channel
3230 * Now do mid and side channels if requested
3233 FLAC__ASSERT(encoder->protected_->channels == 2);
3235 for(channel = 0; channel < 2; channel++) {
3239 min_partition_order,
3240 max_partition_order,
3242 encoder->private_->subframe_bps_mid_side[channel],
3243 encoder->private_->integer_signal_mid_side[channel],
3244 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3245 encoder->private_->real_signal_mid_side[channel],
3247 encoder->private_->subframe_workspace_ptr_mid_side[channel],
3248 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3249 encoder->private_->residual_workspace_mid_side[channel],
3250 encoder->private_->best_subframe_mid_side+channel,
3251 encoder->private_->best_subframe_bits_mid_side+channel
3259 * Compose the frame bitbuffer
3262 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3263 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3264 FLAC__ChannelAssignment channel_assignment;
3266 FLAC__ASSERT(encoder->protected_->channels == 2);
3268 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3269 channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3272 unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3276 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3277 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
3278 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
3279 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
3280 FLAC__ASSERT(do_independent && do_mid_side);
3282 /* We have to figure out which channel assignent results in the smallest frame */
3283 bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
3284 bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
3285 bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
3286 bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3288 channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3289 min_bits = bits[channel_assignment];
3290 for(ca = 1; ca <= 3; ca++) {
3291 if(bits[ca] < min_bits) {
3292 min_bits = bits[ca];
3293 channel_assignment = (FLAC__ChannelAssignment)ca;
3298 frame_header.channel_assignment = channel_assignment;
3300 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3301 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3305 switch(channel_assignment) {
3306 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3307 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3308 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3310 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3311 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3312 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3314 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3315 left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3316 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3318 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3319 left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3320 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3326 switch(channel_assignment) {
3327 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3328 left_bps = encoder->private_->subframe_bps [0];
3329 right_bps = encoder->private_->subframe_bps [1];
3331 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3332 left_bps = encoder->private_->subframe_bps [0];
3333 right_bps = encoder->private_->subframe_bps_mid_side[1];
3335 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3336 left_bps = encoder->private_->subframe_bps_mid_side[1];
3337 right_bps = encoder->private_->subframe_bps [1];
3339 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3340 left_bps = encoder->private_->subframe_bps_mid_side[0];
3341 right_bps = encoder->private_->subframe_bps_mid_side[1];
3347 /* note that encoder_add_subframe_ sets the state for us in case of an error */
3348 if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3350 if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3354 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3355 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3359 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3360 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)) {
3361 /* the above function sets the state for us in case of an error */
3367 if(encoder->protected_->loose_mid_side_stereo) {
3368 encoder->private_->loose_mid_side_stereo_frame_count++;
3369 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3370 encoder->private_->loose_mid_side_stereo_frame_count = 0;
3373 encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3378 FLAC__bool process_subframe_(
3379 FLAC__StreamEncoder *encoder,
3380 unsigned min_partition_order,
3381 unsigned max_partition_order,
3382 const FLAC__FrameHeader *frame_header,
3383 unsigned subframe_bps,
3384 const FLAC__int32 integer_signal[],
3385 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3386 const FLAC__real real_signal[],
3388 FLAC__Subframe *subframe[2],
3389 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3390 FLAC__int32 *residual[2],
3391 unsigned *best_subframe,
3395 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3396 FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3398 FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3400 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3401 FLAC__double lpc_residual_bits_per_sample;
3402 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 */
3403 FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3404 unsigned min_lpc_order, max_lpc_order, lpc_order;
3405 unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3407 unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3408 unsigned rice_parameter;
3409 unsigned _candidate_bits, _best_bits;
3410 unsigned _best_subframe;
3412 FLAC__ASSERT(frame_header->blocksize > 0);
3414 /* verbatim subframe is the baseline against which we measure other compressed subframes */
3416 if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3417 _best_bits = UINT_MAX;
3419 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3421 if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3422 unsigned signal_is_constant = false;
3423 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);
3424 /* check for constant subframe */
3426 !encoder->private_->disable_constant_subframes &&
3427 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3428 fixed_residual_bits_per_sample[1] == 0.0
3430 fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3433 /* the above means it's possible all samples are the same value; now double-check it: */
3435 signal_is_constant = true;
3436 for(i = 1; i < frame_header->blocksize; i++) {
3437 if(integer_signal[0] != integer_signal[i]) {
3438 signal_is_constant = false;
3443 if(signal_is_constant) {
3444 _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3445 if(_candidate_bits < _best_bits) {
3446 _best_subframe = !_best_subframe;
3447 _best_bits = _candidate_bits;
3451 if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3453 if(encoder->protected_->do_exhaustive_model_search) {
3454 min_fixed_order = 0;
3455 max_fixed_order = FLAC__MAX_FIXED_ORDER;
3458 min_fixed_order = max_fixed_order = guess_fixed_order;
3460 if(max_fixed_order >= frame_header->blocksize)
3461 max_fixed_order = frame_header->blocksize - 1;
3462 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3463 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3464 if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3465 continue; /* don't even try */
3466 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 */
3468 if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3469 continue; /* don't even try */
3470 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 */
3472 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3473 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3474 #ifdef DEBUG_VERBOSE
3475 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3477 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3480 evaluate_fixed_subframe_(
3483 residual[!_best_subframe],
3484 encoder->private_->abs_residual_partition_sums,
3485 encoder->private_->raw_bits_per_partition,
3486 frame_header->blocksize,
3490 min_partition_order,
3491 max_partition_order,
3492 encoder->protected_->do_escape_coding,
3493 encoder->protected_->rice_parameter_search_dist,
3494 subframe[!_best_subframe],
3495 partitioned_rice_contents[!_best_subframe]
3497 if(_candidate_bits < _best_bits) {
3498 _best_subframe = !_best_subframe;
3499 _best_bits = _candidate_bits;
3504 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3506 if(encoder->protected_->max_lpc_order > 0) {
3507 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3508 max_lpc_order = frame_header->blocksize-1;
3510 max_lpc_order = encoder->protected_->max_lpc_order;
3511 if(max_lpc_order > 0) {
3513 for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3514 FLAC__lpc_window_data(real_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3515 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3516 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3517 if(autoc[0] != 0.0) {
3518 FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3519 if(encoder->protected_->do_exhaustive_model_search) {
3523 const unsigned guess_lpc_order =
3524 FLAC__lpc_compute_best_order(
3527 frame_header->blocksize,
3529 encoder->protected_->do_qlp_coeff_prec_search?
3530 FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
3531 encoder->protected_->qlp_coeff_precision
3534 min_lpc_order = max_lpc_order = guess_lpc_order;
3536 if(max_lpc_order >= frame_header->blocksize)
3537 max_lpc_order = frame_header->blocksize - 1;
3538 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
3539 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
3540 if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
3541 continue; /* don't even try */
3542 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
3543 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3544 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3545 #ifdef DEBUG_VERBOSE
3546 fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3548 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3550 if(encoder->protected_->do_qlp_coeff_prec_search) {
3551 min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
3552 /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
3553 if(subframe_bps <= 17) {
3554 max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
3555 max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
3558 max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
3561 min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
3563 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
3565 evaluate_lpc_subframe_(
3568 residual[!_best_subframe],
3569 encoder->private_->abs_residual_partition_sums,
3570 encoder->private_->raw_bits_per_partition,
3571 encoder->private_->lp_coeff[lpc_order-1],
3572 frame_header->blocksize,
3575 qlp_coeff_precision,
3577 min_partition_order,
3578 max_partition_order,
3579 encoder->protected_->do_escape_coding,
3580 encoder->protected_->rice_parameter_search_dist,
3581 subframe[!_best_subframe],
3582 partitioned_rice_contents[!_best_subframe]
3584 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
3585 if(_candidate_bits < _best_bits) {
3586 _best_subframe = !_best_subframe;
3587 _best_bits = _candidate_bits;
3596 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3600 /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3601 if(_best_bits == UINT_MAX) {
3602 FLAC__ASSERT(_best_subframe == 0);
3603 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3606 *best_subframe = _best_subframe;
3607 *best_bits = _best_bits;
3612 FLAC__bool add_subframe_(
3613 FLAC__StreamEncoder *encoder,
3615 unsigned subframe_bps,
3616 const FLAC__Subframe *subframe,
3617 FLAC__BitWriter *frame
3620 switch(subframe->type) {
3621 case FLAC__SUBFRAME_TYPE_CONSTANT:
3622 if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3623 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3627 case FLAC__SUBFRAME_TYPE_FIXED:
3628 if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3629 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3633 case FLAC__SUBFRAME_TYPE_LPC:
3634 if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3635 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3639 case FLAC__SUBFRAME_TYPE_VERBATIM:
3640 if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3641 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3652 #define SPOTCHECK_ESTIMATE 0
3653 #if SPOTCHECK_ESTIMATE
3654 static void spotcheck_subframe_estimate_(
3655 FLAC__StreamEncoder *encoder,
3657 unsigned subframe_bps,
3658 const FLAC__Subframe *subframe,
3663 FLAC__BitWriter *frame = FLAC__bitwriter_new();
3665 fprintf(stderr, "EST: can't allocate frame\n");
3668 if(!FLAC__bitwriter_init(frame)) {
3669 fprintf(stderr, "EST: can't init frame\n");
3672 ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
3675 const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
3676 if(estimate != actual)
3677 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);
3679 FLAC__bitwriter_delete(frame);
3683 unsigned evaluate_constant_subframe_(
3684 FLAC__StreamEncoder *encoder,
3685 const FLAC__int32 signal,
3687 unsigned subframe_bps,
3688 FLAC__Subframe *subframe
3692 subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3693 subframe->data.constant.value = signal;
3695 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
3697 #if SPOTCHECK_ESTIMATE
3698 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3700 (void)encoder, (void)blocksize;
3706 unsigned evaluate_fixed_subframe_(
3707 FLAC__StreamEncoder *encoder,
3708 const FLAC__int32 signal[],
3709 FLAC__int32 residual[],
3710 FLAC__uint64 abs_residual_partition_sums[],
3711 unsigned raw_bits_per_partition[],
3713 unsigned subframe_bps,
3715 unsigned rice_parameter,
3716 unsigned min_partition_order,
3717 unsigned max_partition_order,
3718 FLAC__bool do_escape_coding,
3719 unsigned rice_parameter_search_dist,
3720 FLAC__Subframe *subframe,
3721 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3724 unsigned i, residual_bits, estimate;
3725 const unsigned residual_samples = blocksize - order;
3727 FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3729 subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3731 subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3732 subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3733 subframe->data.fixed.residual = residual;
3736 find_best_partition_order_(
3739 abs_residual_partition_sums,
3740 raw_bits_per_partition,
3744 min_partition_order,
3745 max_partition_order,
3748 rice_parameter_search_dist,
3749 &subframe->data.fixed.entropy_coding_method.data.partitioned_rice
3752 subframe->data.fixed.order = order;
3753 for(i = 0; i < order; i++)
3754 subframe->data.fixed.warmup[i] = signal[i];
3756 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
3758 #if SPOTCHECK_ESTIMATE
3759 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3765 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3766 unsigned evaluate_lpc_subframe_(
3767 FLAC__StreamEncoder *encoder,
3768 const FLAC__int32 signal[],
3769 FLAC__int32 residual[],
3770 FLAC__uint64 abs_residual_partition_sums[],
3771 unsigned raw_bits_per_partition[],
3772 const FLAC__real lp_coeff[],
3774 unsigned subframe_bps,
3776 unsigned qlp_coeff_precision,
3777 unsigned rice_parameter,
3778 unsigned min_partition_order,
3779 unsigned max_partition_order,
3780 FLAC__bool do_escape_coding,
3781 unsigned rice_parameter_search_dist,
3782 FLAC__Subframe *subframe,
3783 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3786 FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
3787 unsigned i, residual_bits, estimate;
3788 int quantization, ret;
3789 const unsigned residual_samples = blocksize - order;
3791 /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3792 if(subframe_bps <= 16) {
3793 FLAC__ASSERT(order > 0);
3794 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3795 qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3798 ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3800 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3802 if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3803 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3804 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3806 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3808 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3810 subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3812 subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3813 subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3814 subframe->data.lpc.residual = residual;
3817 find_best_partition_order_(
3820 abs_residual_partition_sums,
3821 raw_bits_per_partition,
3825 min_partition_order,
3826 max_partition_order,
3829 rice_parameter_search_dist,
3830 &subframe->data.lpc.entropy_coding_method.data.partitioned_rice
3833 subframe->data.lpc.order = order;
3834 subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3835 subframe->data.lpc.quantization_level = quantization;
3836 memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3837 for(i = 0; i < order; i++)
3838 subframe->data.lpc.warmup[i] = signal[i];
3840 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;
3842 #if SPOTCHECK_ESTIMATE
3843 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3850 unsigned evaluate_verbatim_subframe_(
3851 FLAC__StreamEncoder *encoder,
3852 const FLAC__int32 signal[],
3854 unsigned subframe_bps,
3855 FLAC__Subframe *subframe
3860 subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3862 subframe->data.verbatim.data = signal;
3864 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
3866 #if SPOTCHECK_ESTIMATE
3867 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3875 unsigned find_best_partition_order_(
3876 FLAC__StreamEncoderPrivate *private_,
3877 const FLAC__int32 residual[],
3878 FLAC__uint64 abs_residual_partition_sums[],
3879 unsigned raw_bits_per_partition[],
3880 unsigned residual_samples,
3881 unsigned predictor_order,
3882 unsigned rice_parameter,
3883 unsigned min_partition_order,
3884 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, bps);
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,
3962 int partition_order;
3963 unsigned from_partition, to_partition = 0;
3964 const unsigned blocksize = residual_samples + predictor_order;
3965 const unsigned partitions = 1u << max_partition_order;
3966 const unsigned default_partition_samples = blocksize >> max_partition_order;
3967 unsigned partition, end, residual_sample;
3969 FLAC__ASSERT(default_partition_samples > predictor_order);
3971 /* first do max_partition_order */
3972 if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) { /* very slightly pessimistic but still catches all common cases */
3973 FLAC__uint32 abs_residual_partition_sum;
3975 end = (unsigned)(-(int)predictor_order);
3976 for(partition = residual_sample = 0; partition < partitions; partition++) {
3977 end += default_partition_samples;
3978 abs_residual_partition_sum = 0;
3979 for( ; residual_sample < end; residual_sample++)
3980 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3981 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3984 else { /* have to pessimistically use 64 bits for accumulator */
3985 FLAC__uint64 abs_residual_partition_sum;
3987 end = (unsigned)(-(int)predictor_order);
3988 for(partition = residual_sample = 0; partition < partitions; partition++) {
3989 end += default_partition_samples;
3990 abs_residual_partition_sum = 0;
3991 for( ; residual_sample < end; residual_sample++)
3992 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3993 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3997 /* now merge partitions for lower orders */
3998 for(from_partition = 0, to_partition = partitions, partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
4000 const unsigned partitions = 1u << partition_order;
4001 for(i = 0; i < partitions; i++) {
4002 abs_residual_partition_sums[to_partition++] =
4003 abs_residual_partition_sums[from_partition ] +
4004 abs_residual_partition_sums[from_partition+1];
4005 from_partition += 2;
4010 void precompute_partition_info_escapes_(
4011 const FLAC__int32 residual[],
4012 unsigned raw_bits_per_partition[],
4013 unsigned residual_samples,
4014 unsigned predictor_order,
4015 unsigned min_partition_order,
4016 unsigned max_partition_order
4019 int partition_order;
4020 unsigned from_partition, to_partition = 0;
4021 const unsigned blocksize = residual_samples + predictor_order;
4023 /* first do max_partition_order */
4024 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
4027 unsigned partition, partition_sample, partition_samples, residual_sample;
4028 const unsigned partitions = 1u << partition_order;
4029 const unsigned default_partition_samples = blocksize >> partition_order;
4031 FLAC__ASSERT(default_partition_samples > predictor_order);
4033 for(partition = residual_sample = 0; partition < partitions; partition++) {
4034 partition_samples = default_partition_samples;
4036 partition_samples -= predictor_order;
4038 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
4039 r = residual[residual_sample++];
4040 /* OPT: maybe faster: rmax |= r ^ (r>>31) */
4046 /* now we know all residual values are in the range [-rmax-1,rmax] */
4047 raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
4049 to_partition = partitions;
4050 break; /*@@@ yuck, should remove the 'for' loop instead */
4053 /* now merge partitions for lower orders */
4054 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
4057 const unsigned partitions = 1u << partition_order;
4058 for(i = 0; i < partitions; i++) {
4059 m = raw_bits_per_partition[from_partition];
4061 raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
4068 #ifdef EXACT_RICE_BITS_CALCULATION
4069 static FLaC__INLINE unsigned count_rice_bits_in_partition_(
4070 const unsigned rice_parameter,
4071 const unsigned partition_samples,
4072 const FLAC__int32 *residual
4075 unsigned i, partition_bits =
4076 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN +
4077 (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
4079 for(i = 0; i < partition_samples; i++)
4080 partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
4081 return partition_bits;
4084 static FLaC__INLINE unsigned count_rice_bits_in_partition_(
4085 const unsigned rice_parameter,
4086 const unsigned partition_samples,
4087 const FLAC__uint64 abs_residual_partition_sum
4091 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN +
4092 (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
4095 (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
4096 : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
4098 - (partition_samples >> 1)
4099 /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
4100 * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
4101 * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
4102 * So the subtraction term tries to guess how many extra bits were contributed.
4103 * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
4109 FLAC__bool set_partitioned_rice_(
4110 #ifdef EXACT_RICE_BITS_CALCULATION
4111 const FLAC__int32 residual[],
4113 const FLAC__uint64 abs_residual_partition_sums[],
4114 const unsigned raw_bits_per_partition[],
4115 const unsigned residual_samples,
4116 const unsigned predictor_order,
4117 const unsigned suggested_rice_parameter,
4118 const unsigned rice_parameter_search_dist,
4119 const unsigned partition_order,
4120 const FLAC__bool search_for_escapes,
4121 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
4125 unsigned rice_parameter, partition_bits;
4126 unsigned best_partition_bits, best_rice_parameter = 0;
4127 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
4128 unsigned *parameters, *raw_bits;
4129 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4130 unsigned min_rice_parameter, max_rice_parameter;
4132 (void)rice_parameter_search_dist;
4135 FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
4137 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
4138 parameters = partitioned_rice_contents->parameters;
4139 raw_bits = partitioned_rice_contents->raw_bits;
4141 if(partition_order == 0) {
4142 best_partition_bits = 0xffffffff;
4143 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4144 if(rice_parameter_search_dist) {
4145 if(suggested_rice_parameter < rice_parameter_search_dist)
4146 min_rice_parameter = 0;
4148 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
4149 max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
4150 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
4151 #ifdef DEBUG_VERBOSE
4152 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
4154 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
4158 min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
4160 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4162 rice_parameter = suggested_rice_parameter;
4164 #ifdef EXACT_RICE_BITS_CALCULATION
4165 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
4167 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
4169 if(partition_bits < best_partition_bits) {
4170 best_rice_parameter = rice_parameter;
4171 best_partition_bits = partition_bits;
4173 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4176 if(search_for_escapes) {
4177 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;
4178 if(partition_bits <= best_partition_bits) {
4179 raw_bits[0] = raw_bits_per_partition[0];
4180 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
4181 best_partition_bits = partition_bits;
4184 parameters[0] = best_rice_parameter;
4185 bits_ += best_partition_bits;
4188 unsigned partition, residual_sample;
4189 unsigned partition_samples;
4190 FLAC__uint64 mean, k;
4191 const unsigned partitions = 1u << partition_order;
4192 for(partition = residual_sample = 0; partition < partitions; partition++) {
4193 partition_samples = (residual_samples+predictor_order) >> partition_order;
4194 if(partition == 0) {
4195 if(partition_samples <= predictor_order)
4198 partition_samples -= predictor_order;
4200 mean = abs_residual_partition_sums[partition];
4201 /* we are basically calculating the size in bits of the
4202 * average residual magnitude in the partition:
4203 * rice_parameter = floor(log2(mean/partition_samples))
4204 * 'mean' is not a good name for the variable, it is
4205 * actually the sum of magnitudes of all residual values
4206 * in the partition, so the actual mean is
4207 * mean/partition_samples
4209 for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
4211 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
4212 #ifdef DEBUG_VERBOSE
4213 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
4215 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
4218 best_partition_bits = 0xffffffff;
4219 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4220 if(rice_parameter_search_dist) {
4221 if(rice_parameter < rice_parameter_search_dist)
4222 min_rice_parameter = 0;
4224 min_rice_parameter = rice_parameter - rice_parameter_search_dist;
4225 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
4226 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
4227 #ifdef DEBUG_VERBOSE
4228 fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
4230 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
4234 min_rice_parameter = max_rice_parameter = rice_parameter;
4236 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4238 #ifdef EXACT_RICE_BITS_CALCULATION
4239 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
4241 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
4243 if(partition_bits < best_partition_bits) {
4244 best_rice_parameter = rice_parameter;
4245 best_partition_bits = partition_bits;
4247 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4250 if(search_for_escapes) {
4251 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;
4252 if(partition_bits <= best_partition_bits) {
4253 raw_bits[partition] = raw_bits_per_partition[partition];
4254 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
4255 best_partition_bits = partition_bits;
4258 parameters[partition] = best_rice_parameter;
4259 bits_ += best_partition_bits;
4260 residual_sample += partition_samples;
4268 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
4273 for(i = 0; i < samples && !(x&1); i++)
4280 for(shift = 0; !(x&1); shift++)
4285 for(i = 0; i < samples; i++)
4286 signal[i] >>= shift;
4292 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4296 for(channel = 0; channel < channels; channel++)
4297 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
4299 fifo->tail += wide_samples;
4301 FLAC__ASSERT(fifo->tail <= fifo->size);
4304 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4307 unsigned sample, wide_sample;
4308 unsigned tail = fifo->tail;
4310 sample = input_offset * channels;
4311 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
4312 for(channel = 0; channel < channels; channel++)
4313 fifo->data[channel][tail] = input[sample++];
4318 FLAC__ASSERT(fifo->tail <= fifo->size);
4321 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4323 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4324 const size_t encoded_bytes = encoder->private_->verify.output.bytes;
4327 if(encoder->private_->verify.needs_magic_hack) {
4328 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
4329 *bytes = FLAC__STREAM_SYNC_LENGTH;
4330 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
4331 encoder->private_->verify.needs_magic_hack = false;
4334 if(encoded_bytes == 0) {
4336 * If we get here, a FIFO underflow has occurred,
4337 * which means there is a bug somewhere.
4340 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
4342 else if(encoded_bytes < *bytes)
4343 *bytes = encoded_bytes;
4344 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
4345 encoder->private_->verify.output.data += *bytes;
4346 encoder->private_->verify.output.bytes -= *bytes;
4349 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
4352 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
4354 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
4356 const unsigned channels = frame->header.channels;
4357 const unsigned blocksize = frame->header.blocksize;
4358 const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
4362 for(channel = 0; channel < channels; channel++) {
4363 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
4364 unsigned i, sample = 0;
4365 FLAC__int32 expect = 0, got = 0;
4367 for(i = 0; i < blocksize; i++) {
4368 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
4370 expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
4371 got = (FLAC__int32)buffer[channel][i];
4375 FLAC__ASSERT(i < blocksize);
4376 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
4377 encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
4378 encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
4379 encoder->private_->verify.error_stats.channel = channel;
4380 encoder->private_->verify.error_stats.sample = sample;
4381 encoder->private_->verify.error_stats.expected = expect;
4382 encoder->private_->verify.error_stats.got = got;
4383 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
4384 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
4387 /* dequeue the frame from the fifo */
4388 encoder->private_->verify.input_fifo.tail -= blocksize;
4389 FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
4390 for(channel = 0; channel < channels; channel++)
4391 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]));
4392 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4395 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4397 (void)decoder, (void)metadata, (void)client_data;
4400 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4402 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4403 (void)decoder, (void)status;
4404 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4407 FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4411 *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
4413 if (feof(encoder->private_->file))
4414 return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
4415 else if (ferror(encoder->private_->file))
4416 return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
4418 return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
4421 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4425 if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
4426 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4428 return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4431 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4437 offset = ftello(encoder->private_->file);
4440 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4443 *absolute_byte_offset = (FLAC__uint64)offset;
4444 return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4448 #ifdef FLAC__VALGRIND_TESTING
4449 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4451 size_t ret = fwrite(ptr, size, nmemb, stream);
4457 #define local__fwrite fwrite
4460 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
4462 (void)client_data, (void)current_frame;
4464 if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4465 FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
4467 /* We would like to be able to use 'samples > 0' in the
4468 * clause here but currently because of the nature of our
4469 * Ogg writing implementation, 'samples' is always 0 (see
4470 * ogg_encoder_aspect.c). The downside is extra progress
4473 encoder->private_->is_ogg? true :
4478 /* NOTE: We have to add +bytes, +samples, and +1 to the stats
4479 * because at this point in the callback chain, the stats
4480 * have not been updated. Only after we return and control
4481 * gets back to write_frame_() are the stats updated
4483 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);
4485 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4488 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4492 * This will forcibly set stdout to binary mode (for OSes that require it)
4494 FILE *get_binary_stdout_(void)
4496 /* if something breaks here it is probably due to the presence or
4497 * absence of an underscore before the identifiers 'setmode',
4498 * 'fileno', and/or 'O_BINARY'; check your system header files.
4500 #if defined _MSC_VER || defined __MINGW32__
4501 _setmode(_fileno(stdout), _O_BINARY);
4502 #elif defined __CYGWIN__
4503 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4504 setmode(_fileno(stdout), _O_BINARY);
4505 #elif defined __EMX__
4506 setmode(fileno(stdout), O_BINARY);