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,
252 FLAC__bool do_escape_coding,
253 unsigned rice_parameter_search_dist,
254 FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
257 static void precompute_partition_info_sums_(
258 const FLAC__int32 residual[],
259 FLAC__uint64 abs_residual_partition_sums[],
260 unsigned residual_samples,
261 unsigned predictor_order,
262 unsigned min_partition_order,
263 unsigned max_partition_order
266 static void precompute_partition_info_escapes_(
267 const FLAC__int32 residual[],
268 unsigned raw_bits_per_partition[],
269 unsigned residual_samples,
270 unsigned predictor_order,
271 unsigned min_partition_order,
272 unsigned max_partition_order
275 static FLAC__bool set_partitioned_rice_(
276 #ifdef EXACT_RICE_BITS_CALCULATION
277 const FLAC__int32 residual[],
279 const FLAC__uint64 abs_residual_partition_sums[],
280 const unsigned raw_bits_per_partition[],
281 const unsigned residual_samples,
282 const unsigned predictor_order,
283 const unsigned suggested_rice_parameter,
284 const unsigned rice_parameter_search_dist,
285 const unsigned partition_order,
286 const FLAC__bool search_for_escapes,
287 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
291 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
293 /* verify-related routines: */
294 static void append_to_verify_fifo_(
295 verify_input_fifo *fifo,
296 const FLAC__int32 * const input[],
297 unsigned input_offset,
299 unsigned wide_samples
302 static void append_to_verify_fifo_interleaved_(
303 verify_input_fifo *fifo,
304 const FLAC__int32 input[],
305 unsigned input_offset,
307 unsigned wide_samples
310 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
311 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
312 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
313 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
315 static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
316 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
317 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
318 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);
319 static FILE *get_binary_stdout_(void);
322 /***********************************************************************
326 ***********************************************************************/
328 typedef struct FLAC__StreamEncoderPrivate {
329 unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
330 FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
331 FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
332 #ifndef FLAC__INTEGER_ONLY_LIBRARY
333 FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* the floating-point version of the input signal */
334 FLAC__real *real_signal_mid_side[2]; /* the floating-point version of the mid-side input signal (stereo only) */
335 FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
336 FLAC__real *windowed_signal; /* the real_signal[] * current window[] */
338 unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
339 unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
340 FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
341 FLAC__int32 *residual_workspace_mid_side[2][2];
342 FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
343 FLAC__Subframe subframe_workspace_mid_side[2][2];
344 FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
345 FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
346 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
347 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
348 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
349 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
350 unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
351 unsigned best_subframe_mid_side[2];
352 unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
353 unsigned best_subframe_bits_mid_side[2];
354 FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
355 unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
356 FLAC__BitWriter *frame; /* the current frame being worked on */
357 unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
358 unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
359 FLAC__ChannelAssignment last_channel_assignment;
360 FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
361 FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
362 unsigned current_sample_number;
363 unsigned current_frame_number;
364 FLAC__MD5Context md5context;
365 FLAC__CPUInfo cpuinfo;
366 #ifndef FLAC__INTEGER_ONLY_LIBRARY
367 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
369 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
371 #ifndef FLAC__INTEGER_ONLY_LIBRARY
372 void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
373 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[]);
374 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[]);
375 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[]);
377 FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
378 FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
379 FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
380 FLAC__bool disable_constant_subframes;
381 FLAC__bool disable_fixed_subframes;
382 FLAC__bool disable_verbatim_subframes;
386 FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
387 FLAC__StreamEncoderSeekCallback seek_callback;
388 FLAC__StreamEncoderTellCallback tell_callback;
389 FLAC__StreamEncoderWriteCallback write_callback;
390 FLAC__StreamEncoderMetadataCallback metadata_callback;
391 FLAC__StreamEncoderProgressCallback progress_callback;
393 unsigned first_seekpoint_to_check;
394 FILE *file; /* only used when encoding to a file */
395 FLAC__uint64 bytes_written;
396 FLAC__uint64 samples_written;
397 unsigned frames_written;
398 unsigned total_frames_estimate;
399 /* unaligned (original) pointers to allocated data */
400 FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
401 FLAC__int32 *integer_signal_mid_side_unaligned[2];
402 #ifndef FLAC__INTEGER_ONLY_LIBRARY
403 FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS];
404 FLAC__real *real_signal_mid_side_unaligned[2];
405 FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
406 FLAC__real *windowed_signal_unaligned;
408 FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
409 FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
410 FLAC__uint64 *abs_residual_partition_sums_unaligned;
411 unsigned *raw_bits_per_partition_unaligned;
413 * These fields have been moved here from private function local
414 * declarations merely to save stack space during encoding.
416 #ifndef FLAC__INTEGER_ONLY_LIBRARY
417 FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
419 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
421 * The data for the verify section
424 FLAC__StreamDecoder *decoder;
425 EncoderStateHint state_hint;
426 FLAC__bool needs_magic_hack;
427 verify_input_fifo input_fifo;
428 verify_output output;
430 FLAC__uint64 absolute_sample;
431 unsigned frame_number;
434 FLAC__int32 expected;
438 FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
439 } FLAC__StreamEncoderPrivate;
441 /***********************************************************************
443 * Public static class data
445 ***********************************************************************/
447 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
448 "FLAC__STREAM_ENCODER_OK",
449 "FLAC__STREAM_ENCODER_UNINITIALIZED",
450 "FLAC__STREAM_ENCODER_OGG_ERROR",
451 "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
452 "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
453 "FLAC__STREAM_ENCODER_CLIENT_ERROR",
454 "FLAC__STREAM_ENCODER_IO_ERROR",
455 "FLAC__STREAM_ENCODER_FRAMING_ERROR",
456 "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
459 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
460 "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
461 "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
462 "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
463 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
464 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
465 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
466 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
467 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
468 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
469 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
470 "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
471 "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
472 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
473 "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
476 FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
477 "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
478 "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
479 "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
480 "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
483 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
484 "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
485 "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
488 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
489 "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
490 "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
491 "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
494 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
495 "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
496 "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
497 "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
500 /* Number of samples that will be overread to watch for end of stream. By
501 * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
502 * always try to read blocksize+1 samples before encoding a block, so that
503 * even if the stream has a total sample count that is an integral multiple
504 * of the blocksize, we will still notice when we are encoding the last
505 * block. This is needed, for example, to correctly set the end-of-stream
506 * marker in Ogg FLAC.
508 * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
509 * not really any reason to change it.
511 static const unsigned OVERREAD_ = 1;
513 /***********************************************************************
515 * Class constructor/destructor
518 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
520 FLAC__StreamEncoder *encoder;
523 FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
525 encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
530 encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
531 if(encoder->protected_ == 0) {
536 encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
537 if(encoder->private_ == 0) {
538 free(encoder->protected_);
543 encoder->private_->frame = FLAC__bitwriter_new();
544 if(encoder->private_->frame == 0) {
545 free(encoder->private_);
546 free(encoder->protected_);
551 encoder->private_->file = 0;
553 set_defaults_(encoder);
555 encoder->private_->is_being_deleted = false;
557 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
558 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
559 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
561 for(i = 0; i < 2; i++) {
562 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
563 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
565 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
566 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
567 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
569 for(i = 0; i < 2; i++) {
570 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
571 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
574 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
575 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
576 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
578 for(i = 0; i < 2; i++) {
579 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
580 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
582 for(i = 0; i < 2; i++)
583 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
585 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
590 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
594 FLAC__ASSERT(0 != encoder);
595 FLAC__ASSERT(0 != encoder->protected_);
596 FLAC__ASSERT(0 != encoder->private_);
597 FLAC__ASSERT(0 != encoder->private_->frame);
599 encoder->private_->is_being_deleted = true;
601 (void)FLAC__stream_encoder_finish(encoder);
603 if(0 != encoder->private_->verify.decoder)
604 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
606 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
607 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
608 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
610 for(i = 0; i < 2; i++) {
611 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
612 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
614 for(i = 0; i < 2; i++)
615 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
617 FLAC__bitwriter_delete(encoder->private_->frame);
618 free(encoder->private_);
619 free(encoder->protected_);
623 /***********************************************************************
625 * Public class methods
627 ***********************************************************************/
629 static FLAC__StreamEncoderInitStatus init_stream_internal_(
630 FLAC__StreamEncoder *encoder,
631 FLAC__StreamEncoderReadCallback read_callback,
632 FLAC__StreamEncoderWriteCallback write_callback,
633 FLAC__StreamEncoderSeekCallback seek_callback,
634 FLAC__StreamEncoderTellCallback tell_callback,
635 FLAC__StreamEncoderMetadataCallback metadata_callback,
641 FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
643 FLAC__ASSERT(0 != encoder);
645 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
646 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
650 return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
653 if(0 == write_callback || (seek_callback && 0 == tell_callback))
654 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
656 if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
657 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
659 if(encoder->protected_->channels != 2) {
660 encoder->protected_->do_mid_side_stereo = false;
661 encoder->protected_->loose_mid_side_stereo = false;
663 else if(!encoder->protected_->do_mid_side_stereo)
664 encoder->protected_->loose_mid_side_stereo = false;
666 if(encoder->protected_->bits_per_sample >= 32)
667 encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
669 if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
670 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
672 if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
673 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
675 if(encoder->protected_->blocksize == 0) {
676 if(encoder->protected_->max_lpc_order == 0)
677 encoder->protected_->blocksize = 1152;
679 encoder->protected_->blocksize = 4096;
682 if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
683 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
685 if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
686 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
688 if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
689 return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
691 if(encoder->protected_->qlp_coeff_precision == 0) {
692 if(encoder->protected_->bits_per_sample < 16) {
693 /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
694 /* @@@ until then we'll make a guess */
695 encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
697 else if(encoder->protected_->bits_per_sample == 16) {
698 if(encoder->protected_->blocksize <= 192)
699 encoder->protected_->qlp_coeff_precision = 7;
700 else if(encoder->protected_->blocksize <= 384)
701 encoder->protected_->qlp_coeff_precision = 8;
702 else if(encoder->protected_->blocksize <= 576)
703 encoder->protected_->qlp_coeff_precision = 9;
704 else if(encoder->protected_->blocksize <= 1152)
705 encoder->protected_->qlp_coeff_precision = 10;
706 else if(encoder->protected_->blocksize <= 2304)
707 encoder->protected_->qlp_coeff_precision = 11;
708 else if(encoder->protected_->blocksize <= 4608)
709 encoder->protected_->qlp_coeff_precision = 12;
711 encoder->protected_->qlp_coeff_precision = 13;
714 if(encoder->protected_->blocksize <= 384)
715 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
716 else if(encoder->protected_->blocksize <= 1152)
717 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
719 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
721 FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
723 else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
724 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
726 if(encoder->protected_->streamable_subset) {
728 encoder->protected_->blocksize != 192 &&
729 encoder->protected_->blocksize != 576 &&
730 encoder->protected_->blocksize != 1152 &&
731 encoder->protected_->blocksize != 2304 &&
732 encoder->protected_->blocksize != 4608 &&
733 encoder->protected_->blocksize != 256 &&
734 encoder->protected_->blocksize != 512 &&
735 encoder->protected_->blocksize != 1024 &&
736 encoder->protected_->blocksize != 2048 &&
737 encoder->protected_->blocksize != 4096 &&
738 encoder->protected_->blocksize != 8192 &&
739 encoder->protected_->blocksize != 16384
741 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
742 if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
743 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
745 encoder->protected_->bits_per_sample != 8 &&
746 encoder->protected_->bits_per_sample != 12 &&
747 encoder->protected_->bits_per_sample != 16 &&
748 encoder->protected_->bits_per_sample != 20 &&
749 encoder->protected_->bits_per_sample != 24
751 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
752 if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
753 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
755 encoder->protected_->sample_rate <= 48000 &&
757 encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
758 encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
761 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
765 if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
766 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
767 if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
768 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
771 /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
772 if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
774 for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
775 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
776 FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
778 encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
779 encoder->protected_->metadata[0] = vc;
785 /* keep track of any SEEKTABLE block */
786 if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
788 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
789 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
790 encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
791 break; /* take only the first one */
796 /* validate metadata */
797 if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
798 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
799 metadata_has_seektable = false;
800 metadata_has_vorbis_comment = false;
801 metadata_picture_has_type1 = false;
802 metadata_picture_has_type2 = false;
803 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
804 const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
805 if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
806 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
807 else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
808 if(metadata_has_seektable) /* only one is allowed */
809 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
810 metadata_has_seektable = true;
811 if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
812 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
814 else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
815 if(metadata_has_vorbis_comment) /* only one is allowed */
816 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
817 metadata_has_vorbis_comment = true;
819 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
820 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
821 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
823 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
824 if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
825 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
826 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
827 if(metadata_picture_has_type1) /* there should only be 1 per stream */
828 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
829 metadata_picture_has_type1 = true;
830 /* standard icon must be 32x32 pixel PNG */
832 m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
834 (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
835 m->data.picture.width != 32 ||
836 m->data.picture.height != 32
839 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
841 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
842 if(metadata_picture_has_type2) /* there should only be 1 per stream */
843 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
844 metadata_picture_has_type2 = true;
849 encoder->private_->input_capacity = 0;
850 for(i = 0; i < encoder->protected_->channels; i++) {
851 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
852 #ifndef FLAC__INTEGER_ONLY_LIBRARY
853 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
856 for(i = 0; i < 2; i++) {
857 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
858 #ifndef FLAC__INTEGER_ONLY_LIBRARY
859 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
862 #ifndef FLAC__INTEGER_ONLY_LIBRARY
863 for(i = 0; i < encoder->protected_->num_apodizations; i++)
864 encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
865 encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
867 for(i = 0; i < encoder->protected_->channels; i++) {
868 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
869 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
870 encoder->private_->best_subframe[i] = 0;
872 for(i = 0; i < 2; i++) {
873 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
874 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
875 encoder->private_->best_subframe_mid_side[i] = 0;
877 encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
878 encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
879 #ifndef FLAC__INTEGER_ONLY_LIBRARY
880 encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
882 /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
883 /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply÷ by hand */
884 FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
885 FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
886 FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
887 FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
888 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);
890 if(encoder->private_->loose_mid_side_stereo_frames == 0)
891 encoder->private_->loose_mid_side_stereo_frames = 1;
892 encoder->private_->loose_mid_side_stereo_frame_count = 0;
893 encoder->private_->current_sample_number = 0;
894 encoder->private_->current_frame_number = 0;
896 encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
897 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? */
898 encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
901 * get the CPU info and set the function pointers
903 FLAC__cpu_info(&encoder->private_->cpuinfo);
904 /* first default to the non-asm routines */
905 #ifndef FLAC__INTEGER_ONLY_LIBRARY
906 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
908 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
909 #ifndef FLAC__INTEGER_ONLY_LIBRARY
910 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
911 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
912 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
914 /* now override with asm where appropriate */
915 #ifndef FLAC__INTEGER_ONLY_LIBRARY
916 # ifndef FLAC__NO_ASM
917 if(encoder->private_->cpuinfo.use_asm) {
918 # ifdef FLAC__CPU_IA32
919 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
920 # ifdef FLAC__HAS_NASM
921 if(encoder->private_->cpuinfo.data.ia32.sse) {
922 if(encoder->protected_->max_lpc_order < 4)
923 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
924 else if(encoder->protected_->max_lpc_order < 8)
925 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
926 else if(encoder->protected_->max_lpc_order < 12)
927 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
929 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
931 else if(encoder->private_->cpuinfo.data.ia32._3dnow)
932 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
934 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
935 if(encoder->private_->cpuinfo.data.ia32.mmx) {
936 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
937 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
940 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
941 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
943 if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
944 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
945 # endif /* FLAC__HAS_NASM */
946 # endif /* FLAC__CPU_IA32 */
948 # endif /* !FLAC__NO_ASM */
949 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
950 /* finally override based on wide-ness if necessary */
951 if(encoder->private_->use_wide_by_block) {
952 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
955 /* set state to OK; from here on, errors are fatal and we'll override the state then */
956 encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
959 encoder->private_->is_ogg = is_ogg;
960 if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
961 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
962 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
966 encoder->private_->read_callback = read_callback;
967 encoder->private_->write_callback = write_callback;
968 encoder->private_->seek_callback = seek_callback;
969 encoder->private_->tell_callback = tell_callback;
970 encoder->private_->metadata_callback = metadata_callback;
971 encoder->private_->client_data = client_data;
973 if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
974 /* the above function sets the state for us in case of an error */
975 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
978 if(!FLAC__bitwriter_init(encoder->private_->frame)) {
979 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
980 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
984 * Set up the verify stuff if necessary
986 if(encoder->protected_->verify) {
988 * First, set up the fifo which will hold the
989 * original signal to compare against
991 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
992 for(i = 0; i < encoder->protected_->channels; i++) {
993 if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder->private_->verify.input_fifo.size))) {
994 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
995 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
998 encoder->private_->verify.input_fifo.tail = 0;
1001 * Now set up a stream decoder for verification
1003 encoder->private_->verify.decoder = FLAC__stream_decoder_new();
1004 if(0 == encoder->private_->verify.decoder) {
1005 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1006 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1009 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) {
1010 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1011 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1014 encoder->private_->verify.error_stats.absolute_sample = 0;
1015 encoder->private_->verify.error_stats.frame_number = 0;
1016 encoder->private_->verify.error_stats.channel = 0;
1017 encoder->private_->verify.error_stats.sample = 0;
1018 encoder->private_->verify.error_stats.expected = 0;
1019 encoder->private_->verify.error_stats.got = 0;
1022 * These must be done before we write any metadata, because that
1023 * calls the write_callback, which uses these values.
1025 encoder->private_->first_seekpoint_to_check = 0;
1026 encoder->private_->samples_written = 0;
1027 encoder->protected_->streaminfo_offset = 0;
1028 encoder->protected_->seektable_offset = 0;
1029 encoder->protected_->audio_offset = 0;
1032 * write the stream header
1034 if(encoder->protected_->verify)
1035 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1036 if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1037 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1038 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1040 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1041 /* the above function sets the state for us in case of an error */
1042 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1046 * write the STREAMINFO metadata block
1048 if(encoder->protected_->verify)
1049 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1050 encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1051 encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1052 encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1053 encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1054 encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1055 encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1056 encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1057 encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1058 encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1059 encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1060 encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1061 memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1062 FLAC__MD5Init(&encoder->private_->md5context);
1063 if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1064 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1065 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1067 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1068 /* the above function sets the state for us in case of an error */
1069 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1073 * Now that the STREAMINFO block is written, we can init this to an
1074 * absurdly-high value...
1076 encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1077 /* ... and clear this to 0 */
1078 encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1081 * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1082 * if not, we will write an empty one (FLAC__add_metadata_block()
1083 * automatically supplies the vendor string).
1085 * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1086 * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
1087 * true it will have already insured that the metadata list is properly
1090 if(!metadata_has_vorbis_comment) {
1091 FLAC__StreamMetadata vorbis_comment;
1092 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1093 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1094 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1095 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1096 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1097 vorbis_comment.data.vorbis_comment.num_comments = 0;
1098 vorbis_comment.data.vorbis_comment.comments = 0;
1099 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1100 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1101 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1103 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1104 /* the above function sets the state for us in case of an error */
1105 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1110 * write the user's metadata blocks
1112 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1113 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1114 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1115 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1116 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1118 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1119 /* the above function sets the state for us in case of an error */
1120 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1124 /* now that all the metadata is written, we save the stream offset */
1125 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 */
1126 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1127 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1130 if(encoder->protected_->verify)
1131 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1133 return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1136 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1137 FLAC__StreamEncoder *encoder,
1138 FLAC__StreamEncoderWriteCallback write_callback,
1139 FLAC__StreamEncoderSeekCallback seek_callback,
1140 FLAC__StreamEncoderTellCallback tell_callback,
1141 FLAC__StreamEncoderMetadataCallback metadata_callback,
1145 return init_stream_internal_(
1147 /*read_callback=*/0,
1157 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1158 FLAC__StreamEncoder *encoder,
1159 FLAC__StreamEncoderReadCallback read_callback,
1160 FLAC__StreamEncoderWriteCallback write_callback,
1161 FLAC__StreamEncoderSeekCallback seek_callback,
1162 FLAC__StreamEncoderTellCallback tell_callback,
1163 FLAC__StreamEncoderMetadataCallback metadata_callback,
1167 return init_stream_internal_(
1179 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1180 FLAC__StreamEncoder *encoder,
1182 FLAC__StreamEncoderProgressCallback progress_callback,
1187 FLAC__StreamEncoderInitStatus init_status;
1189 FLAC__ASSERT(0 != encoder);
1190 FLAC__ASSERT(0 != file);
1192 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1193 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1195 /* double protection */
1197 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1198 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1202 * To make sure that our file does not go unclosed after an error, we
1203 * must assign the FILE pointer before any further error can occur in
1207 file = get_binary_stdout_(); /* just to be safe */
1209 encoder->private_->file = file;
1211 encoder->private_->progress_callback = progress_callback;
1212 encoder->private_->bytes_written = 0;
1213 encoder->private_->samples_written = 0;
1214 encoder->private_->frames_written = 0;
1216 init_status = init_stream_internal_(
1218 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1219 file_write_callback_,
1220 encoder->private_->file == stdout? 0 : file_seek_callback_,
1221 encoder->private_->file == stdout? 0 : file_tell_callback_,
1222 /*metadata_callback=*/0,
1226 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1227 /* the above function sets the state for us in case of an error */
1232 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1234 FLAC__ASSERT(blocksize != 0);
1235 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1241 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1242 FLAC__StreamEncoder *encoder,
1244 FLAC__StreamEncoderProgressCallback progress_callback,
1248 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1251 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1252 FLAC__StreamEncoder *encoder,
1254 FLAC__StreamEncoderProgressCallback progress_callback,
1258 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1261 static FLAC__StreamEncoderInitStatus init_file_internal_(
1262 FLAC__StreamEncoder *encoder,
1263 const char *filename,
1264 FLAC__StreamEncoderProgressCallback progress_callback,
1271 FLAC__ASSERT(0 != encoder);
1274 * To make sure that our file does not go unclosed after an error, we
1275 * have to do the same entrance checks here that are later performed
1276 * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1278 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1279 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1281 file = filename? fopen(filename, "w+b") : stdout;
1284 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1285 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1288 return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1291 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1292 FLAC__StreamEncoder *encoder,
1293 const char *filename,
1294 FLAC__StreamEncoderProgressCallback progress_callback,
1298 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1301 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1302 FLAC__StreamEncoder *encoder,
1303 const char *filename,
1304 FLAC__StreamEncoderProgressCallback progress_callback,
1308 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1311 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1313 FLAC__bool error = false;
1315 FLAC__ASSERT(0 != encoder);
1316 FLAC__ASSERT(0 != encoder->private_);
1317 FLAC__ASSERT(0 != encoder->protected_);
1319 if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1322 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1323 if(encoder->private_->current_sample_number != 0) {
1324 const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1325 encoder->protected_->blocksize = encoder->private_->current_sample_number;
1326 if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1331 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1333 if(!encoder->private_->is_being_deleted) {
1334 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1335 if(encoder->private_->seek_callback) {
1337 if(encoder->private_->is_ogg)
1338 update_ogg_metadata_(encoder);
1341 update_metadata_(encoder);
1343 /* check if an error occurred while updating metadata */
1344 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1347 if(encoder->private_->metadata_callback)
1348 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1351 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1353 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1358 if(0 != encoder->private_->file) {
1359 if(encoder->private_->file != stdout)
1360 fclose(encoder->private_->file);
1361 encoder->private_->file = 0;
1365 if(encoder->private_->is_ogg)
1366 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1370 set_defaults_(encoder);
1373 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1378 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1380 FLAC__ASSERT(0 != encoder);
1381 FLAC__ASSERT(0 != encoder->private_);
1382 FLAC__ASSERT(0 != encoder->protected_);
1383 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1386 /* can't check encoder->private_->is_ogg since that's not set until init time */
1387 FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1395 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1397 FLAC__ASSERT(0 != encoder);
1398 FLAC__ASSERT(0 != encoder->private_);
1399 FLAC__ASSERT(0 != encoder->protected_);
1400 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1402 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1403 encoder->protected_->verify = value;
1408 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1410 FLAC__ASSERT(0 != encoder);
1411 FLAC__ASSERT(0 != encoder->private_);
1412 FLAC__ASSERT(0 != encoder->protected_);
1413 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1415 encoder->protected_->streamable_subset = value;
1419 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1421 FLAC__ASSERT(0 != encoder);
1422 FLAC__ASSERT(0 != encoder->private_);
1423 FLAC__ASSERT(0 != encoder->protected_);
1424 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1426 encoder->protected_->channels = value;
1430 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1432 FLAC__ASSERT(0 != encoder);
1433 FLAC__ASSERT(0 != encoder->private_);
1434 FLAC__ASSERT(0 != encoder->protected_);
1435 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1437 encoder->protected_->bits_per_sample = value;
1441 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1443 FLAC__ASSERT(0 != encoder);
1444 FLAC__ASSERT(0 != encoder->private_);
1445 FLAC__ASSERT(0 != encoder->protected_);
1446 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1448 encoder->protected_->sample_rate = value;
1452 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1454 FLAC__bool ok = true;
1455 FLAC__ASSERT(0 != encoder);
1456 FLAC__ASSERT(0 != encoder->private_);
1457 FLAC__ASSERT(0 != encoder->protected_);
1458 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1460 if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1461 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1462 ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
1463 ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
1466 ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
1467 /* but it's too hard to specify the string in a locale-specific way */
1469 encoder->protected_->num_apodizations = 1;
1470 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1471 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1473 ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
1474 ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
1475 ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1476 ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
1477 ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
1478 ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1479 ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1480 ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
1484 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1486 FLAC__ASSERT(0 != encoder);
1487 FLAC__ASSERT(0 != encoder->private_);
1488 FLAC__ASSERT(0 != encoder->protected_);
1489 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1491 encoder->protected_->blocksize = value;
1495 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1497 FLAC__ASSERT(0 != encoder);
1498 FLAC__ASSERT(0 != encoder->private_);
1499 FLAC__ASSERT(0 != encoder->protected_);
1500 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1502 encoder->protected_->do_mid_side_stereo = value;
1506 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1508 FLAC__ASSERT(0 != encoder);
1509 FLAC__ASSERT(0 != encoder->private_);
1510 FLAC__ASSERT(0 != encoder->protected_);
1511 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1513 encoder->protected_->loose_mid_side_stereo = value;
1517 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1519 FLAC__ASSERT(0 != encoder);
1520 FLAC__ASSERT(0 != encoder->private_);
1521 FLAC__ASSERT(0 != encoder->protected_);
1522 FLAC__ASSERT(0 != specification);
1523 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1525 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1526 (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1528 encoder->protected_->num_apodizations = 0;
1530 const char *s = strchr(specification, ';');
1531 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1532 if (n==8 && 0 == strncmp("bartlett" , specification, n))
1533 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1534 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1535 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1536 else if(n==8 && 0 == strncmp("blackman" , specification, n))
1537 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1538 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1539 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1540 else if(n==6 && 0 == strncmp("connes" , specification, n))
1541 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1542 else if(n==7 && 0 == strncmp("flattop" , specification, n))
1543 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1544 else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
1545 FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1546 if (stddev > 0.0 && stddev <= 0.5) {
1547 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1548 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1551 else if(n==7 && 0 == strncmp("hamming" , specification, n))
1552 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1553 else if(n==4 && 0 == strncmp("hann" , specification, n))
1554 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1555 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1556 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1557 else if(n==7 && 0 == strncmp("nuttall" , specification, n))
1558 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1559 else if(n==9 && 0 == strncmp("rectangle" , specification, n))
1560 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1561 else if(n==8 && 0 == strncmp("triangle" , specification, n))
1562 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1563 else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
1564 FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1565 if (p >= 0.0 && p <= 1.0) {
1566 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1567 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1570 else if(n==5 && 0 == strncmp("welch" , specification, n))
1571 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1572 if (encoder->protected_->num_apodizations == 32)
1575 specification = s+1;
1579 if(encoder->protected_->num_apodizations == 0) {
1580 encoder->protected_->num_apodizations = 1;
1581 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1582 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1588 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1590 FLAC__ASSERT(0 != encoder);
1591 FLAC__ASSERT(0 != encoder->private_);
1592 FLAC__ASSERT(0 != encoder->protected_);
1593 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1595 encoder->protected_->max_lpc_order = value;
1599 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1601 FLAC__ASSERT(0 != encoder);
1602 FLAC__ASSERT(0 != encoder->private_);
1603 FLAC__ASSERT(0 != encoder->protected_);
1604 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1606 encoder->protected_->qlp_coeff_precision = value;
1610 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1612 FLAC__ASSERT(0 != encoder);
1613 FLAC__ASSERT(0 != encoder->private_);
1614 FLAC__ASSERT(0 != encoder->protected_);
1615 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1617 encoder->protected_->do_qlp_coeff_prec_search = value;
1621 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1623 FLAC__ASSERT(0 != encoder);
1624 FLAC__ASSERT(0 != encoder->private_);
1625 FLAC__ASSERT(0 != encoder->protected_);
1626 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1629 /*@@@ deprecated: */
1630 encoder->protected_->do_escape_coding = value;
1637 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1639 FLAC__ASSERT(0 != encoder);
1640 FLAC__ASSERT(0 != encoder->private_);
1641 FLAC__ASSERT(0 != encoder->protected_);
1642 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1644 encoder->protected_->do_exhaustive_model_search = value;
1648 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1650 FLAC__ASSERT(0 != encoder);
1651 FLAC__ASSERT(0 != encoder->private_);
1652 FLAC__ASSERT(0 != encoder->protected_);
1653 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1655 encoder->protected_->min_residual_partition_order = value;
1659 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1661 FLAC__ASSERT(0 != encoder);
1662 FLAC__ASSERT(0 != encoder->private_);
1663 FLAC__ASSERT(0 != encoder->protected_);
1664 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1666 encoder->protected_->max_residual_partition_order = value;
1670 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1672 FLAC__ASSERT(0 != encoder);
1673 FLAC__ASSERT(0 != encoder->private_);
1674 FLAC__ASSERT(0 != encoder->protected_);
1675 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1678 /*@@@ deprecated: */
1679 encoder->protected_->rice_parameter_search_dist = value;
1686 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1688 FLAC__ASSERT(0 != encoder);
1689 FLAC__ASSERT(0 != encoder->private_);
1690 FLAC__ASSERT(0 != encoder->protected_);
1691 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1693 encoder->protected_->total_samples_estimate = value;
1697 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1699 FLAC__ASSERT(0 != encoder);
1700 FLAC__ASSERT(0 != encoder->private_);
1701 FLAC__ASSERT(0 != encoder->protected_);
1702 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1708 /* realloc() does not do exactly what we want so... */
1709 if(encoder->protected_->metadata) {
1710 free(encoder->protected_->metadata);
1711 encoder->protected_->metadata = 0;
1712 encoder->protected_->num_metadata_blocks = 0;
1715 FLAC__StreamMetadata **m;
1716 if(0 == (m = (FLAC__StreamMetadata**)malloc(sizeof(m[0]) * num_blocks)))
1718 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1719 encoder->protected_->metadata = m;
1720 encoder->protected_->num_metadata_blocks = num_blocks;
1723 if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1730 * These three functions are not static, but not publically exposed in
1731 * include/FLAC/ either. They are used by the test suite.
1733 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1735 FLAC__ASSERT(0 != encoder);
1736 FLAC__ASSERT(0 != encoder->private_);
1737 FLAC__ASSERT(0 != encoder->protected_);
1738 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1740 encoder->private_->disable_constant_subframes = value;
1744 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1746 FLAC__ASSERT(0 != encoder);
1747 FLAC__ASSERT(0 != encoder->private_);
1748 FLAC__ASSERT(0 != encoder->protected_);
1749 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1751 encoder->private_->disable_fixed_subframes = value;
1755 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1757 FLAC__ASSERT(0 != encoder);
1758 FLAC__ASSERT(0 != encoder->private_);
1759 FLAC__ASSERT(0 != encoder->protected_);
1760 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1762 encoder->private_->disable_verbatim_subframes = value;
1766 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1768 FLAC__ASSERT(0 != encoder);
1769 FLAC__ASSERT(0 != encoder->private_);
1770 FLAC__ASSERT(0 != encoder->protected_);
1771 return encoder->protected_->state;
1774 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1776 FLAC__ASSERT(0 != encoder);
1777 FLAC__ASSERT(0 != encoder->private_);
1778 FLAC__ASSERT(0 != encoder->protected_);
1779 if(encoder->protected_->verify)
1780 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1782 return FLAC__STREAM_DECODER_UNINITIALIZED;
1785 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1787 FLAC__ASSERT(0 != encoder);
1788 FLAC__ASSERT(0 != encoder->private_);
1789 FLAC__ASSERT(0 != encoder->protected_);
1790 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1791 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1793 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1796 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)
1798 FLAC__ASSERT(0 != encoder);
1799 FLAC__ASSERT(0 != encoder->private_);
1800 FLAC__ASSERT(0 != encoder->protected_);
1801 if(0 != absolute_sample)
1802 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1803 if(0 != frame_number)
1804 *frame_number = encoder->private_->verify.error_stats.frame_number;
1806 *channel = encoder->private_->verify.error_stats.channel;
1808 *sample = encoder->private_->verify.error_stats.sample;
1810 *expected = encoder->private_->verify.error_stats.expected;
1812 *got = encoder->private_->verify.error_stats.got;
1815 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1817 FLAC__ASSERT(0 != encoder);
1818 FLAC__ASSERT(0 != encoder->private_);
1819 FLAC__ASSERT(0 != encoder->protected_);
1820 return encoder->protected_->verify;
1823 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1825 FLAC__ASSERT(0 != encoder);
1826 FLAC__ASSERT(0 != encoder->private_);
1827 FLAC__ASSERT(0 != encoder->protected_);
1828 return encoder->protected_->streamable_subset;
1831 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1833 FLAC__ASSERT(0 != encoder);
1834 FLAC__ASSERT(0 != encoder->private_);
1835 FLAC__ASSERT(0 != encoder->protected_);
1836 return encoder->protected_->channels;
1839 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1841 FLAC__ASSERT(0 != encoder);
1842 FLAC__ASSERT(0 != encoder->private_);
1843 FLAC__ASSERT(0 != encoder->protected_);
1844 return encoder->protected_->bits_per_sample;
1847 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1849 FLAC__ASSERT(0 != encoder);
1850 FLAC__ASSERT(0 != encoder->private_);
1851 FLAC__ASSERT(0 != encoder->protected_);
1852 return encoder->protected_->sample_rate;
1855 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1857 FLAC__ASSERT(0 != encoder);
1858 FLAC__ASSERT(0 != encoder->private_);
1859 FLAC__ASSERT(0 != encoder->protected_);
1860 return encoder->protected_->blocksize;
1863 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1865 FLAC__ASSERT(0 != encoder);
1866 FLAC__ASSERT(0 != encoder->private_);
1867 FLAC__ASSERT(0 != encoder->protected_);
1868 return encoder->protected_->do_mid_side_stereo;
1871 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1873 FLAC__ASSERT(0 != encoder);
1874 FLAC__ASSERT(0 != encoder->private_);
1875 FLAC__ASSERT(0 != encoder->protected_);
1876 return encoder->protected_->loose_mid_side_stereo;
1879 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1881 FLAC__ASSERT(0 != encoder);
1882 FLAC__ASSERT(0 != encoder->private_);
1883 FLAC__ASSERT(0 != encoder->protected_);
1884 return encoder->protected_->max_lpc_order;
1887 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1889 FLAC__ASSERT(0 != encoder);
1890 FLAC__ASSERT(0 != encoder->private_);
1891 FLAC__ASSERT(0 != encoder->protected_);
1892 return encoder->protected_->qlp_coeff_precision;
1895 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1897 FLAC__ASSERT(0 != encoder);
1898 FLAC__ASSERT(0 != encoder->private_);
1899 FLAC__ASSERT(0 != encoder->protected_);
1900 return encoder->protected_->do_qlp_coeff_prec_search;
1903 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1905 FLAC__ASSERT(0 != encoder);
1906 FLAC__ASSERT(0 != encoder->private_);
1907 FLAC__ASSERT(0 != encoder->protected_);
1908 return encoder->protected_->do_escape_coding;
1911 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1913 FLAC__ASSERT(0 != encoder);
1914 FLAC__ASSERT(0 != encoder->private_);
1915 FLAC__ASSERT(0 != encoder->protected_);
1916 return encoder->protected_->do_exhaustive_model_search;
1919 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1921 FLAC__ASSERT(0 != encoder);
1922 FLAC__ASSERT(0 != encoder->private_);
1923 FLAC__ASSERT(0 != encoder->protected_);
1924 return encoder->protected_->min_residual_partition_order;
1927 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1929 FLAC__ASSERT(0 != encoder);
1930 FLAC__ASSERT(0 != encoder->private_);
1931 FLAC__ASSERT(0 != encoder->protected_);
1932 return encoder->protected_->max_residual_partition_order;
1935 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1937 FLAC__ASSERT(0 != encoder);
1938 FLAC__ASSERT(0 != encoder->private_);
1939 FLAC__ASSERT(0 != encoder->protected_);
1940 return encoder->protected_->rice_parameter_search_dist;
1943 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1945 FLAC__ASSERT(0 != encoder);
1946 FLAC__ASSERT(0 != encoder->private_);
1947 FLAC__ASSERT(0 != encoder->protected_);
1948 return encoder->protected_->total_samples_estimate;
1951 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1953 unsigned i, j, channel;
1954 FLAC__int32 x, mid, side;
1955 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1957 FLAC__ASSERT(0 != encoder);
1958 FLAC__ASSERT(0 != encoder->private_);
1959 FLAC__ASSERT(0 != encoder->protected_);
1960 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1964 * we have several flavors of the same basic loop, optimized for
1965 * different conditions:
1967 if(encoder->protected_->max_lpc_order > 0) {
1968 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1970 * stereo coding: unroll channel loop
1971 * with LPC: calculate floating point version of signal
1974 if(encoder->protected_->verify)
1975 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
1977 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
1978 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1979 x = mid = side = buffer[0][j];
1980 encoder->private_->integer_signal[0][i] = x;
1981 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1982 encoder->private_->real_signal[0][i] = (FLAC__real)x;
1985 encoder->private_->integer_signal[1][i] = x;
1986 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1987 encoder->private_->real_signal[1][i] = (FLAC__real)x;
1991 mid >>= 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
1992 encoder->private_->integer_signal_mid_side[1][i] = side;
1993 encoder->private_->integer_signal_mid_side[0][i] = mid;
1994 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1995 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
1996 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
1998 encoder->private_->current_sample_number++;
2000 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2002 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2004 /* move unprocessed overread samples to beginnings of arrays */
2005 FLAC__ASSERT(i == blocksize+OVERREAD_);
2006 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2008 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2009 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2010 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2011 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2012 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2013 encoder->private_->real_signal[0][0] = encoder->private_->real_signal[0][i];
2014 encoder->private_->real_signal[1][0] = encoder->private_->real_signal[1][i];
2015 encoder->private_->real_signal_mid_side[0][0] = encoder->private_->real_signal_mid_side[0][i];
2016 encoder->private_->real_signal_mid_side[1][0] = encoder->private_->real_signal_mid_side[1][i];
2018 encoder->private_->current_sample_number = 1;
2020 } while(j < samples);
2024 * independent channel coding: buffer each channel in inner loop
2025 * with LPC: calculate floating point version of signal
2028 if(encoder->protected_->verify)
2029 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2031 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2032 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2033 for(channel = 0; channel < channels; channel++) {
2034 x = buffer[channel][j];
2035 encoder->private_->integer_signal[channel][i] = x;
2036 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2037 encoder->private_->real_signal[channel][i] = (FLAC__real)x;
2040 encoder->private_->current_sample_number++;
2042 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2044 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2046 /* move unprocessed overread samples to beginnings of arrays */
2047 FLAC__ASSERT(i == blocksize+OVERREAD_);
2048 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2050 for(channel = 0; channel < channels; channel++) {
2051 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2052 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2053 encoder->private_->real_signal[channel][0] = encoder->private_->real_signal[channel][i];
2056 encoder->private_->current_sample_number = 1;
2058 } while(j < samples);
2062 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2064 * stereo coding: unroll channel loop
2065 * without LPC: no need to calculate floating point version of signal
2068 if(encoder->protected_->verify)
2069 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2071 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2072 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2073 encoder->private_->integer_signal[0][i] = mid = side = buffer[0][j];
2075 encoder->private_->integer_signal[1][i] = x;
2078 mid >>= 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
2079 encoder->private_->integer_signal_mid_side[1][i] = side;
2080 encoder->private_->integer_signal_mid_side[0][i] = mid;
2081 encoder->private_->current_sample_number++;
2083 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2085 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2087 /* move unprocessed overread samples to beginnings of arrays */
2088 FLAC__ASSERT(i == blocksize+OVERREAD_);
2089 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2091 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2092 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2093 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2094 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2095 encoder->private_->current_sample_number = 1;
2097 } while(j < samples);
2101 * independent channel coding: buffer each channel in inner loop
2102 * without LPC: no need to calculate floating point version of signal
2105 if(encoder->protected_->verify)
2106 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2108 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2109 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2110 for(channel = 0; channel < channels; channel++)
2111 encoder->private_->integer_signal[channel][i] = buffer[channel][j];
2112 encoder->private_->current_sample_number++;
2114 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2116 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2118 /* move unprocessed overread samples to beginnings of arrays */
2119 FLAC__ASSERT(i == blocksize+OVERREAD_);
2120 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2122 for(channel = 0; channel < channels; channel++)
2123 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2124 encoder->private_->current_sample_number = 1;
2126 } while(j < samples);
2133 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2135 unsigned i, j, k, channel;
2136 FLAC__int32 x, mid, side;
2137 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2139 FLAC__ASSERT(0 != encoder);
2140 FLAC__ASSERT(0 != encoder->private_);
2141 FLAC__ASSERT(0 != encoder->protected_);
2142 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2146 * we have several flavors of the same basic loop, optimized for
2147 * different conditions:
2149 if(encoder->protected_->max_lpc_order > 0) {
2150 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2152 * stereo coding: unroll channel loop
2153 * with LPC: calculate floating point version of signal
2156 if(encoder->protected_->verify)
2157 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2159 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2160 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2161 x = mid = side = buffer[k++];
2162 encoder->private_->integer_signal[0][i] = x;
2163 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2164 encoder->private_->real_signal[0][i] = (FLAC__real)x;
2167 encoder->private_->integer_signal[1][i] = x;
2168 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2169 encoder->private_->real_signal[1][i] = (FLAC__real)x;
2173 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2174 encoder->private_->integer_signal_mid_side[1][i] = side;
2175 encoder->private_->integer_signal_mid_side[0][i] = mid;
2176 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2177 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
2178 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
2180 encoder->private_->current_sample_number++;
2182 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2184 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2186 /* move unprocessed overread samples to beginnings of arrays */
2187 FLAC__ASSERT(i == blocksize+OVERREAD_);
2188 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2190 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2191 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2192 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2193 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2194 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2195 encoder->private_->real_signal[0][0] = encoder->private_->real_signal[0][i];
2196 encoder->private_->real_signal[1][0] = encoder->private_->real_signal[1][i];
2197 encoder->private_->real_signal_mid_side[0][0] = encoder->private_->real_signal_mid_side[0][i];
2198 encoder->private_->real_signal_mid_side[1][0] = encoder->private_->real_signal_mid_side[1][i];
2200 encoder->private_->current_sample_number = 1;
2202 } while(j < samples);
2206 * independent channel coding: buffer each channel in inner loop
2207 * with LPC: calculate floating point version of signal
2210 if(encoder->protected_->verify)
2211 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2213 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2214 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2215 for(channel = 0; channel < channels; channel++) {
2217 encoder->private_->integer_signal[channel][i] = x;
2218 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2219 encoder->private_->real_signal[channel][i] = (FLAC__real)x;
2222 encoder->private_->current_sample_number++;
2224 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2226 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2228 /* move unprocessed overread samples to beginnings of arrays */
2229 FLAC__ASSERT(i == blocksize+OVERREAD_);
2230 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2232 for(channel = 0; channel < channels; channel++) {
2233 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2234 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2235 encoder->private_->real_signal[channel][0] = encoder->private_->real_signal[channel][i];
2238 encoder->private_->current_sample_number = 1;
2240 } while(j < samples);
2244 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2246 * stereo coding: unroll channel loop
2247 * without LPC: no need to calculate floating point version of signal
2250 if(encoder->protected_->verify)
2251 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2253 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2254 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2255 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2257 encoder->private_->integer_signal[1][i] = x;
2260 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2261 encoder->private_->integer_signal_mid_side[1][i] = side;
2262 encoder->private_->integer_signal_mid_side[0][i] = mid;
2263 encoder->private_->current_sample_number++;
2265 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2267 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2269 /* move unprocessed overread samples to beginnings of arrays */
2270 FLAC__ASSERT(i == blocksize+OVERREAD_);
2271 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2273 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2274 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2275 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2276 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2277 encoder->private_->current_sample_number = 1;
2279 } while(j < samples);
2283 * independent channel coding: buffer each channel in inner loop
2284 * without LPC: no need to calculate floating point version of signal
2287 if(encoder->protected_->verify)
2288 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2290 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2291 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2292 for(channel = 0; channel < channels; channel++)
2293 encoder->private_->integer_signal[channel][i] = buffer[k++];
2294 encoder->private_->current_sample_number++;
2296 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2298 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2300 /* move unprocessed overread samples to beginnings of arrays */
2301 FLAC__ASSERT(i == blocksize+OVERREAD_);
2302 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2304 for(channel = 0; channel < channels; channel++)
2305 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2306 encoder->private_->current_sample_number = 1;
2308 } while(j < samples);
2315 /***********************************************************************
2317 * Private class methods
2319 ***********************************************************************/
2321 void set_defaults_(FLAC__StreamEncoder *encoder)
2323 FLAC__ASSERT(0 != encoder);
2325 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2326 encoder->protected_->verify = true;
2328 encoder->protected_->verify = false;
2330 encoder->protected_->streamable_subset = true;
2331 encoder->protected_->do_mid_side_stereo = false;
2332 encoder->protected_->loose_mid_side_stereo = false;
2333 encoder->protected_->channels = 2;
2334 encoder->protected_->bits_per_sample = 16;
2335 encoder->protected_->sample_rate = 44100;
2336 encoder->protected_->blocksize = 0;
2337 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2338 encoder->protected_->num_apodizations = 1;
2339 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2340 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2342 encoder->protected_->max_lpc_order = 0;
2343 encoder->protected_->qlp_coeff_precision = 0;
2344 encoder->protected_->do_qlp_coeff_prec_search = false;
2345 encoder->protected_->do_exhaustive_model_search = false;
2346 encoder->protected_->do_escape_coding = false;
2347 encoder->protected_->min_residual_partition_order = 0;
2348 encoder->protected_->max_residual_partition_order = 0;
2349 encoder->protected_->rice_parameter_search_dist = 0;
2350 encoder->protected_->total_samples_estimate = 0;
2351 encoder->protected_->metadata = 0;
2352 encoder->protected_->num_metadata_blocks = 0;
2354 encoder->private_->seek_table = 0;
2355 encoder->private_->disable_constant_subframes = false;
2356 encoder->private_->disable_fixed_subframes = false;
2357 encoder->private_->disable_verbatim_subframes = false;
2359 encoder->private_->is_ogg = false;
2361 encoder->private_->read_callback = 0;
2362 encoder->private_->write_callback = 0;
2363 encoder->private_->seek_callback = 0;
2364 encoder->private_->tell_callback = 0;
2365 encoder->private_->metadata_callback = 0;
2366 encoder->private_->progress_callback = 0;
2367 encoder->private_->client_data = 0;
2370 FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2374 void free_(FLAC__StreamEncoder *encoder)
2376 unsigned i, channel;
2378 FLAC__ASSERT(0 != encoder);
2379 if(encoder->protected_->metadata) {
2380 free(encoder->protected_->metadata);
2381 encoder->protected_->metadata = 0;
2382 encoder->protected_->num_metadata_blocks = 0;
2384 for(i = 0; i < encoder->protected_->channels; i++) {
2385 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2386 free(encoder->private_->integer_signal_unaligned[i]);
2387 encoder->private_->integer_signal_unaligned[i] = 0;
2389 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2390 if(0 != encoder->private_->real_signal_unaligned[i]) {
2391 free(encoder->private_->real_signal_unaligned[i]);
2392 encoder->private_->real_signal_unaligned[i] = 0;
2396 for(i = 0; i < 2; i++) {
2397 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2398 free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2399 encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2401 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2402 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2403 free(encoder->private_->real_signal_mid_side_unaligned[i]);
2404 encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2408 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2409 for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2410 if(0 != encoder->private_->window_unaligned[i]) {
2411 free(encoder->private_->window_unaligned[i]);
2412 encoder->private_->window_unaligned[i] = 0;
2415 if(0 != encoder->private_->windowed_signal_unaligned) {
2416 free(encoder->private_->windowed_signal_unaligned);
2417 encoder->private_->windowed_signal_unaligned = 0;
2420 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2421 for(i = 0; i < 2; i++) {
2422 if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2423 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2424 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2428 for(channel = 0; channel < 2; channel++) {
2429 for(i = 0; i < 2; i++) {
2430 if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2431 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2432 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2436 if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2437 free(encoder->private_->abs_residual_partition_sums_unaligned);
2438 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2440 if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2441 free(encoder->private_->raw_bits_per_partition_unaligned);
2442 encoder->private_->raw_bits_per_partition_unaligned = 0;
2444 if(encoder->protected_->verify) {
2445 for(i = 0; i < encoder->protected_->channels; i++) {
2446 if(0 != encoder->private_->verify.input_fifo.data[i]) {
2447 free(encoder->private_->verify.input_fifo.data[i]);
2448 encoder->private_->verify.input_fifo.data[i] = 0;
2452 FLAC__bitwriter_free(encoder->private_->frame);
2455 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2458 unsigned i, channel;
2460 FLAC__ASSERT(new_blocksize > 0);
2461 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2462 FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2464 /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2465 if(new_blocksize <= encoder->private_->input_capacity)
2470 /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
2471 * requires that the input arrays (in our case the integer signals)
2472 * have a buffer of up to 3 zeroes in front (at negative indices) for
2473 * alignment purposes; we use 4 in front to keep the data well-aligned.
2476 for(i = 0; ok && i < encoder->protected_->channels; i++) {
2477 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2478 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2479 encoder->private_->integer_signal[i] += 4;
2480 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2481 if(encoder->protected_->max_lpc_order > 0)
2482 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2485 for(i = 0; ok && i < 2; i++) {
2486 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]);
2487 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2488 encoder->private_->integer_signal_mid_side[i] += 4;
2489 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2490 if(encoder->protected_->max_lpc_order > 0)
2491 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]);
2494 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2495 if(ok && encoder->protected_->max_lpc_order > 0) {
2496 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2497 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2498 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2501 for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2502 for(i = 0; ok && i < 2; i++) {
2503 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2506 for(channel = 0; ok && channel < 2; channel++) {
2507 for(i = 0; ok && i < 2; i++) {
2508 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]);
2511 /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2512 /*@@@ 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) */
2513 ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2514 if(encoder->protected_->do_escape_coding)
2515 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2517 /* now adjust the windows if the blocksize has changed */
2518 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2519 if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2520 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2521 switch(encoder->protected_->apodizations[i].type) {
2522 case FLAC__APODIZATION_BARTLETT:
2523 FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2525 case FLAC__APODIZATION_BARTLETT_HANN:
2526 FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2528 case FLAC__APODIZATION_BLACKMAN:
2529 FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2531 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2532 FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2534 case FLAC__APODIZATION_CONNES:
2535 FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2537 case FLAC__APODIZATION_FLATTOP:
2538 FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2540 case FLAC__APODIZATION_GAUSS:
2541 FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2543 case FLAC__APODIZATION_HAMMING:
2544 FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2546 case FLAC__APODIZATION_HANN:
2547 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2549 case FLAC__APODIZATION_KAISER_BESSEL:
2550 FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2552 case FLAC__APODIZATION_NUTTALL:
2553 FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2555 case FLAC__APODIZATION_RECTANGLE:
2556 FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2558 case FLAC__APODIZATION_TRIANGLE:
2559 FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2561 case FLAC__APODIZATION_TUKEY:
2562 FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2564 case FLAC__APODIZATION_WELCH:
2565 FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2569 /* double protection */
2570 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2578 encoder->private_->input_capacity = new_blocksize;
2580 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2585 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2587 const FLAC__byte *buffer;
2590 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2592 if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2593 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2597 if(encoder->protected_->verify) {
2598 encoder->private_->verify.output.data = buffer;
2599 encoder->private_->verify.output.bytes = bytes;
2600 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2601 encoder->private_->verify.needs_magic_hack = true;
2604 if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2605 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2606 FLAC__bitwriter_clear(encoder->private_->frame);
2607 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2608 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2614 if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2615 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2616 FLAC__bitwriter_clear(encoder->private_->frame);
2617 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2621 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2622 FLAC__bitwriter_clear(encoder->private_->frame);
2625 encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2626 encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2632 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2634 FLAC__StreamEncoderWriteStatus status;
2635 FLAC__uint64 output_position = 0;
2637 /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2638 if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2639 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2640 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2644 * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2647 FLAC__MetadataType type = (buffer[0] & 0x7f);
2648 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2649 encoder->protected_->streaminfo_offset = output_position;
2650 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2651 encoder->protected_->seektable_offset = output_position;
2655 * Mark the current seek point if hit (if audio_offset == 0 that
2656 * means we're still writing metadata and haven't hit the first
2659 if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2660 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2661 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2662 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2663 FLAC__uint64 test_sample;
2665 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2666 test_sample = encoder->private_->seek_table->points[i].sample_number;
2667 if(test_sample > frame_last_sample) {
2670 else if(test_sample >= frame_first_sample) {
2671 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2672 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2673 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2674 encoder->private_->first_seekpoint_to_check++;
2675 /* DO NOT: "break;" and here's why:
2676 * The seektable template may contain more than one target
2677 * sample for any given frame; we will keep looping, generating
2678 * duplicate seekpoints for them, and we'll clean it up later,
2679 * just before writing the seektable back to the metadata.
2683 encoder->private_->first_seekpoint_to_check++;
2689 if(encoder->private_->is_ogg) {
2690 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2691 &encoder->protected_->ogg_encoder_aspect,
2695 encoder->private_->current_frame_number,
2697 (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2699 encoder->private_->client_data
2704 status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2706 if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2707 encoder->private_->bytes_written += bytes;
2708 encoder->private_->samples_written += samples;
2709 /* we keep a high watermark on the number of frames written because
2710 * when the encoder goes back to write metadata, 'current_frame'
2711 * will drop back to 0.
2713 encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2716 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2721 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2722 void update_metadata_(const FLAC__StreamEncoder *encoder)
2724 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2725 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2726 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2727 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2728 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2729 const unsigned bps = metadata->data.stream_info.bits_per_sample;
2730 FLAC__StreamEncoderSeekStatus seek_status;
2732 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2734 /* All this is based on intimate knowledge of the stream header
2735 * layout, but a change to the header format that would break this
2736 * would also break all streams encoded in the previous format.
2740 * Write MD5 signature
2743 const unsigned md5_offset =
2744 FLAC__STREAM_METADATA_HEADER_LENGTH +
2746 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2747 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2748 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2749 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2750 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2751 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2752 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2753 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2756 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2757 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2758 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2761 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2762 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2768 * Write total samples
2771 const unsigned total_samples_byte_offset =
2772 FLAC__STREAM_METADATA_HEADER_LENGTH +
2774 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2775 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2776 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2777 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2778 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2779 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2780 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2784 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2785 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2786 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2787 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2788 b[4] = (FLAC__byte)(samples & 0xFF);
2789 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) {
2790 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2791 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2794 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2795 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2801 * Write min/max framesize
2804 const unsigned min_framesize_offset =
2805 FLAC__STREAM_METADATA_HEADER_LENGTH +
2807 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2808 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2811 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2812 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2813 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2814 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2815 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2816 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2817 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) {
2818 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2819 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2822 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2823 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2831 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2834 FLAC__format_seektable_sort(encoder->private_->seek_table);
2836 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2838 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) {
2839 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2840 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2844 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2847 xx = encoder->private_->seek_table->points[i].sample_number;
2848 b[7] = (FLAC__byte)xx; xx >>= 8;
2849 b[6] = (FLAC__byte)xx; xx >>= 8;
2850 b[5] = (FLAC__byte)xx; xx >>= 8;
2851 b[4] = (FLAC__byte)xx; xx >>= 8;
2852 b[3] = (FLAC__byte)xx; xx >>= 8;
2853 b[2] = (FLAC__byte)xx; xx >>= 8;
2854 b[1] = (FLAC__byte)xx; xx >>= 8;
2855 b[0] = (FLAC__byte)xx; xx >>= 8;
2856 xx = encoder->private_->seek_table->points[i].stream_offset;
2857 b[15] = (FLAC__byte)xx; xx >>= 8;
2858 b[14] = (FLAC__byte)xx; xx >>= 8;
2859 b[13] = (FLAC__byte)xx; xx >>= 8;
2860 b[12] = (FLAC__byte)xx; xx >>= 8;
2861 b[11] = (FLAC__byte)xx; xx >>= 8;
2862 b[10] = (FLAC__byte)xx; xx >>= 8;
2863 b[9] = (FLAC__byte)xx; xx >>= 8;
2864 b[8] = (FLAC__byte)xx; xx >>= 8;
2865 x = encoder->private_->seek_table->points[i].frame_samples;
2866 b[17] = (FLAC__byte)x; x >>= 8;
2867 b[16] = (FLAC__byte)x; x >>= 8;
2868 if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2869 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2877 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2878 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2880 /* the # of bytes in the 1st packet that precede the STREAMINFO */
2881 static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2882 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2883 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2884 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2885 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2886 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2887 FLAC__STREAM_SYNC_LENGTH
2889 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2890 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2891 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2892 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2893 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2896 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2897 FLAC__ASSERT(0 != encoder->private_->seek_callback);
2899 /* Pre-check that client supports seeking, since we don't want the
2900 * ogg_helper code to ever have to deal with this condition.
2902 if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2905 /* All this is based on intimate knowledge of the stream header
2906 * layout, but a change to the header format that would break this
2907 * would also break all streams encoded in the previous format.
2911 ** Write STREAMINFO stats
2913 simple_ogg_page__init(&page);
2914 if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2915 simple_ogg_page__clear(&page);
2916 return; /* state already set */
2920 * Write MD5 signature
2923 const unsigned md5_offset =
2924 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2925 FLAC__STREAM_METADATA_HEADER_LENGTH +
2927 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2928 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2929 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2930 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2931 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2932 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2933 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2934 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2937 if(md5_offset + 16 > (unsigned)page.body_len) {
2938 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2939 simple_ogg_page__clear(&page);
2942 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2946 * Write total samples
2949 const unsigned total_samples_byte_offset =
2950 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2951 FLAC__STREAM_METADATA_HEADER_LENGTH +
2953 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2954 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2955 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2956 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2957 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2958 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2959 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2963 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2964 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2965 simple_ogg_page__clear(&page);
2968 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2969 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2970 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2971 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2972 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2973 b[4] = (FLAC__byte)(samples & 0xFF);
2974 memcpy(page.body + total_samples_byte_offset, b, 5);
2978 * Write min/max framesize
2981 const unsigned min_framesize_offset =
2982 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2983 FLAC__STREAM_METADATA_HEADER_LENGTH +
2985 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2986 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2989 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2990 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2991 simple_ogg_page__clear(&page);
2994 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2995 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2996 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2997 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2998 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2999 b[5] = (FLAC__byte)(max_framesize & 0xFF);
3000 memcpy(page.body + min_framesize_offset, b, 6);
3002 if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
3003 simple_ogg_page__clear(&page);
3004 return; /* state already set */
3006 simple_ogg_page__clear(&page);
3011 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
3015 FLAC__format_seektable_sort(encoder->private_->seek_table);
3017 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
3019 simple_ogg_page__init(&page);
3020 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
3021 simple_ogg_page__clear(&page);
3022 return; /* state already set */
3025 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
3026 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
3027 simple_ogg_page__clear(&page);
3031 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
3034 xx = encoder->private_->seek_table->points[i].sample_number;
3035 b[7] = (FLAC__byte)xx; xx >>= 8;
3036 b[6] = (FLAC__byte)xx; xx >>= 8;
3037 b[5] = (FLAC__byte)xx; xx >>= 8;
3038 b[4] = (FLAC__byte)xx; xx >>= 8;
3039 b[3] = (FLAC__byte)xx; xx >>= 8;
3040 b[2] = (FLAC__byte)xx; xx >>= 8;
3041 b[1] = (FLAC__byte)xx; xx >>= 8;
3042 b[0] = (FLAC__byte)xx; xx >>= 8;
3043 xx = encoder->private_->seek_table->points[i].stream_offset;
3044 b[15] = (FLAC__byte)xx; xx >>= 8;
3045 b[14] = (FLAC__byte)xx; xx >>= 8;
3046 b[13] = (FLAC__byte)xx; xx >>= 8;
3047 b[12] = (FLAC__byte)xx; xx >>= 8;
3048 b[11] = (FLAC__byte)xx; xx >>= 8;
3049 b[10] = (FLAC__byte)xx; xx >>= 8;
3050 b[9] = (FLAC__byte)xx; xx >>= 8;
3051 b[8] = (FLAC__byte)xx; xx >>= 8;
3052 x = encoder->private_->seek_table->points[i].frame_samples;
3053 b[17] = (FLAC__byte)x; x >>= 8;
3054 b[16] = (FLAC__byte)x; x >>= 8;
3058 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
3059 simple_ogg_page__clear(&page);
3060 return; /* state already set */
3062 simple_ogg_page__clear(&page);
3067 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
3070 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
3073 * Accumulate raw signal to the MD5 signature
3075 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)) {
3076 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3081 * Process the frame header and subframes into the frame bitbuffer
3083 if(!process_subframes_(encoder, is_fractional_block)) {
3084 /* the above function sets the state for us in case of an error */
3089 * Zero-pad the frame to a byte_boundary
3091 if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
3092 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3097 * CRC-16 the whole thing
3099 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
3101 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
3102 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
3104 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3111 if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
3112 /* the above function sets the state for us in case of an error */
3117 * Get ready for the next frame
3119 encoder->private_->current_sample_number = 0;
3120 encoder->private_->current_frame_number++;
3121 encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
3126 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
3128 FLAC__FrameHeader frame_header;
3129 unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
3130 FLAC__bool do_independent, do_mid_side;
3133 * Calculate the min,max Rice partition orders
3135 if(is_fractional_block) {
3136 max_partition_order = 0;
3139 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
3140 max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
3142 min_partition_order = min(min_partition_order, max_partition_order);
3147 frame_header.blocksize = encoder->protected_->blocksize;
3148 frame_header.sample_rate = encoder->protected_->sample_rate;
3149 frame_header.channels = encoder->protected_->channels;
3150 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
3151 frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
3152 frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
3153 frame_header.number.frame_number = encoder->private_->current_frame_number;
3156 * Figure out what channel assignments to try
3158 if(encoder->protected_->do_mid_side_stereo) {
3159 if(encoder->protected_->loose_mid_side_stereo) {
3160 if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
3161 do_independent = true;
3165 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
3166 do_mid_side = !do_independent;
3170 do_independent = true;
3175 do_independent = true;
3176 do_mid_side = false;
3179 FLAC__ASSERT(do_independent || do_mid_side);
3182 * Check for wasted bits; set effective bps for each subframe
3184 if(do_independent) {
3185 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3186 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
3187 encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
3188 encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
3192 FLAC__ASSERT(encoder->protected_->channels == 2);
3193 for(channel = 0; channel < 2; channel++) {
3194 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
3195 encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
3196 encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
3201 * First do a normal encoding pass of each independent channel
3203 if(do_independent) {
3204 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3208 min_partition_order,
3209 max_partition_order,
3211 encoder->private_->subframe_bps[channel],
3212 encoder->private_->integer_signal[channel],
3213 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3214 encoder->private_->real_signal[channel],
3216 encoder->private_->subframe_workspace_ptr[channel],
3217 encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3218 encoder->private_->residual_workspace[channel],
3219 encoder->private_->best_subframe+channel,
3220 encoder->private_->best_subframe_bits+channel
3228 * Now do mid and side channels if requested
3231 FLAC__ASSERT(encoder->protected_->channels == 2);
3233 for(channel = 0; channel < 2; channel++) {
3237 min_partition_order,
3238 max_partition_order,
3240 encoder->private_->subframe_bps_mid_side[channel],
3241 encoder->private_->integer_signal_mid_side[channel],
3242 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3243 encoder->private_->real_signal_mid_side[channel],
3245 encoder->private_->subframe_workspace_ptr_mid_side[channel],
3246 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3247 encoder->private_->residual_workspace_mid_side[channel],
3248 encoder->private_->best_subframe_mid_side+channel,
3249 encoder->private_->best_subframe_bits_mid_side+channel
3257 * Compose the frame bitbuffer
3260 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3261 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3262 FLAC__ChannelAssignment channel_assignment;
3264 FLAC__ASSERT(encoder->protected_->channels == 2);
3266 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3267 channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3270 unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3274 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3275 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
3276 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
3277 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
3278 FLAC__ASSERT(do_independent && do_mid_side);
3280 /* We have to figure out which channel assignent results in the smallest frame */
3281 bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
3282 bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
3283 bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
3284 bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3286 channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3287 min_bits = bits[channel_assignment];
3288 for(ca = 1; ca <= 3; ca++) {
3289 if(bits[ca] < min_bits) {
3290 min_bits = bits[ca];
3291 channel_assignment = (FLAC__ChannelAssignment)ca;
3296 frame_header.channel_assignment = channel_assignment;
3298 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3299 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3303 switch(channel_assignment) {
3304 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3305 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3306 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3308 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3309 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3310 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3312 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3313 left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3314 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3316 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3317 left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3318 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3324 switch(channel_assignment) {
3325 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3326 left_bps = encoder->private_->subframe_bps [0];
3327 right_bps = encoder->private_->subframe_bps [1];
3329 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3330 left_bps = encoder->private_->subframe_bps [0];
3331 right_bps = encoder->private_->subframe_bps_mid_side[1];
3333 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3334 left_bps = encoder->private_->subframe_bps_mid_side[1];
3335 right_bps = encoder->private_->subframe_bps [1];
3337 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3338 left_bps = encoder->private_->subframe_bps_mid_side[0];
3339 right_bps = encoder->private_->subframe_bps_mid_side[1];
3345 /* note that encoder_add_subframe_ sets the state for us in case of an error */
3346 if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3348 if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3352 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3353 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3357 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3358 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)) {
3359 /* the above function sets the state for us in case of an error */
3365 if(encoder->protected_->loose_mid_side_stereo) {
3366 encoder->private_->loose_mid_side_stereo_frame_count++;
3367 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3368 encoder->private_->loose_mid_side_stereo_frame_count = 0;
3371 encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3376 FLAC__bool process_subframe_(
3377 FLAC__StreamEncoder *encoder,
3378 unsigned min_partition_order,
3379 unsigned max_partition_order,
3380 const FLAC__FrameHeader *frame_header,
3381 unsigned subframe_bps,
3382 const FLAC__int32 integer_signal[],
3383 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3384 const FLAC__real real_signal[],
3386 FLAC__Subframe *subframe[2],
3387 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3388 FLAC__int32 *residual[2],
3389 unsigned *best_subframe,
3393 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3394 FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3396 FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3398 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3399 FLAC__double lpc_residual_bits_per_sample;
3400 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 */
3401 FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3402 unsigned min_lpc_order, max_lpc_order, lpc_order;
3403 unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3405 unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3406 unsigned rice_parameter;
3407 unsigned _candidate_bits, _best_bits;
3408 unsigned _best_subframe;
3410 FLAC__ASSERT(frame_header->blocksize > 0);
3412 /* verbatim subframe is the baseline against which we measure other compressed subframes */
3414 if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3415 _best_bits = UINT_MAX;
3417 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3419 if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3420 unsigned signal_is_constant = false;
3421 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);
3422 /* check for constant subframe */
3424 !encoder->private_->disable_constant_subframes &&
3425 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3426 fixed_residual_bits_per_sample[1] == 0.0
3428 fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3431 /* the above means it's possible all samples are the same value; now double-check it: */
3433 signal_is_constant = true;
3434 for(i = 1; i < frame_header->blocksize; i++) {
3435 if(integer_signal[0] != integer_signal[i]) {
3436 signal_is_constant = false;
3441 if(signal_is_constant) {
3442 _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3443 if(_candidate_bits < _best_bits) {
3444 _best_subframe = !_best_subframe;
3445 _best_bits = _candidate_bits;
3449 if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3451 if(encoder->protected_->do_exhaustive_model_search) {
3452 min_fixed_order = 0;
3453 max_fixed_order = FLAC__MAX_FIXED_ORDER;
3456 min_fixed_order = max_fixed_order = guess_fixed_order;
3458 if(max_fixed_order >= frame_header->blocksize)
3459 max_fixed_order = frame_header->blocksize - 1;
3460 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3461 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3462 if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3463 continue; /* don't even try */
3464 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 */
3466 if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3467 continue; /* don't even try */
3468 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 */
3470 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3471 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3472 #ifdef DEBUG_VERBOSE
3473 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3475 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3478 evaluate_fixed_subframe_(
3481 residual[!_best_subframe],
3482 encoder->private_->abs_residual_partition_sums,
3483 encoder->private_->raw_bits_per_partition,
3484 frame_header->blocksize,
3488 min_partition_order,
3489 max_partition_order,
3490 encoder->protected_->do_escape_coding,
3491 encoder->protected_->rice_parameter_search_dist,
3492 subframe[!_best_subframe],
3493 partitioned_rice_contents[!_best_subframe]
3495 if(_candidate_bits < _best_bits) {
3496 _best_subframe = !_best_subframe;
3497 _best_bits = _candidate_bits;
3502 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3504 if(encoder->protected_->max_lpc_order > 0) {
3505 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3506 max_lpc_order = frame_header->blocksize-1;
3508 max_lpc_order = encoder->protected_->max_lpc_order;
3509 if(max_lpc_order > 0) {
3511 for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3512 FLAC__lpc_window_data(real_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3513 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3514 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3515 if(autoc[0] != 0.0) {
3516 FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3517 if(encoder->protected_->do_exhaustive_model_search) {
3521 const unsigned guess_lpc_order =
3522 FLAC__lpc_compute_best_order(
3525 frame_header->blocksize,
3527 encoder->protected_->do_qlp_coeff_prec_search?
3528 FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
3529 encoder->protected_->qlp_coeff_precision
3532 min_lpc_order = max_lpc_order = guess_lpc_order;
3534 if(max_lpc_order >= frame_header->blocksize)
3535 max_lpc_order = frame_header->blocksize - 1;
3536 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
3537 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
3538 if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
3539 continue; /* don't even try */
3540 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
3541 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3542 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3543 #ifdef DEBUG_VERBOSE
3544 fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3546 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3548 if(encoder->protected_->do_qlp_coeff_prec_search) {
3549 min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
3550 /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
3551 if(subframe_bps <= 17) {
3552 max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
3553 max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
3556 max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
3559 min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
3561 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
3563 evaluate_lpc_subframe_(
3566 residual[!_best_subframe],
3567 encoder->private_->abs_residual_partition_sums,
3568 encoder->private_->raw_bits_per_partition,
3569 encoder->private_->lp_coeff[lpc_order-1],
3570 frame_header->blocksize,
3573 qlp_coeff_precision,
3575 min_partition_order,
3576 max_partition_order,
3577 encoder->protected_->do_escape_coding,
3578 encoder->protected_->rice_parameter_search_dist,
3579 subframe[!_best_subframe],
3580 partitioned_rice_contents[!_best_subframe]
3582 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
3583 if(_candidate_bits < _best_bits) {
3584 _best_subframe = !_best_subframe;
3585 _best_bits = _candidate_bits;
3594 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3598 /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3599 if(_best_bits == UINT_MAX) {
3600 FLAC__ASSERT(_best_subframe == 0);
3601 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3604 *best_subframe = _best_subframe;
3605 *best_bits = _best_bits;
3610 FLAC__bool add_subframe_(
3611 FLAC__StreamEncoder *encoder,
3613 unsigned subframe_bps,
3614 const FLAC__Subframe *subframe,
3615 FLAC__BitWriter *frame
3618 switch(subframe->type) {
3619 case FLAC__SUBFRAME_TYPE_CONSTANT:
3620 if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3621 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3625 case FLAC__SUBFRAME_TYPE_FIXED:
3626 if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3627 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3631 case FLAC__SUBFRAME_TYPE_LPC:
3632 if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3633 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3637 case FLAC__SUBFRAME_TYPE_VERBATIM:
3638 if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3639 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3650 #define SPOTCHECK_ESTIMATE 0
3651 #if SPOTCHECK_ESTIMATE
3652 static void spotcheck_subframe_estimate_(
3653 FLAC__StreamEncoder *encoder,
3655 unsigned subframe_bps,
3656 const FLAC__Subframe *subframe,
3661 FLAC__BitWriter *frame = FLAC__bitwriter_new();
3663 fprintf(stderr, "EST: can't allocate frame\n");
3666 if(!FLAC__bitwriter_init(frame)) {
3667 fprintf(stderr, "EST: can't init frame\n");
3670 ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
3673 const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
3674 if(estimate != actual)
3675 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);
3677 FLAC__bitwriter_delete(frame);
3681 unsigned evaluate_constant_subframe_(
3682 FLAC__StreamEncoder *encoder,
3683 const FLAC__int32 signal,
3685 unsigned subframe_bps,
3686 FLAC__Subframe *subframe
3690 subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3691 subframe->data.constant.value = signal;
3693 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
3695 #if SPOTCHECK_ESTIMATE
3696 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3698 (void)encoder, (void)blocksize;
3704 unsigned evaluate_fixed_subframe_(
3705 FLAC__StreamEncoder *encoder,
3706 const FLAC__int32 signal[],
3707 FLAC__int32 residual[],
3708 FLAC__uint64 abs_residual_partition_sums[],
3709 unsigned raw_bits_per_partition[],
3711 unsigned subframe_bps,
3713 unsigned rice_parameter,
3714 unsigned min_partition_order,
3715 unsigned max_partition_order,
3716 FLAC__bool do_escape_coding,
3717 unsigned rice_parameter_search_dist,
3718 FLAC__Subframe *subframe,
3719 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3722 unsigned i, residual_bits, estimate;
3723 const unsigned residual_samples = blocksize - order;
3725 FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3727 subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3729 subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3730 subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3731 subframe->data.fixed.residual = residual;
3734 find_best_partition_order_(
3737 abs_residual_partition_sums,
3738 raw_bits_per_partition,
3742 min_partition_order,
3743 max_partition_order,
3745 rice_parameter_search_dist,
3746 &subframe->data.fixed.entropy_coding_method.data.partitioned_rice
3749 subframe->data.fixed.order = order;
3750 for(i = 0; i < order; i++)
3751 subframe->data.fixed.warmup[i] = signal[i];
3753 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
3755 #if SPOTCHECK_ESTIMATE
3756 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3762 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3763 unsigned evaluate_lpc_subframe_(
3764 FLAC__StreamEncoder *encoder,
3765 const FLAC__int32 signal[],
3766 FLAC__int32 residual[],
3767 FLAC__uint64 abs_residual_partition_sums[],
3768 unsigned raw_bits_per_partition[],
3769 const FLAC__real lp_coeff[],
3771 unsigned subframe_bps,
3773 unsigned qlp_coeff_precision,
3774 unsigned rice_parameter,
3775 unsigned min_partition_order,
3776 unsigned max_partition_order,
3777 FLAC__bool do_escape_coding,
3778 unsigned rice_parameter_search_dist,
3779 FLAC__Subframe *subframe,
3780 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3783 FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
3784 unsigned i, residual_bits, estimate;
3785 int quantization, ret;
3786 const unsigned residual_samples = blocksize - order;
3788 /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3789 if(subframe_bps <= 16) {
3790 FLAC__ASSERT(order > 0);
3791 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3792 qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3795 ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3797 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3799 if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3800 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3801 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3803 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3805 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3807 subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3809 subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3810 subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3811 subframe->data.lpc.residual = residual;
3814 find_best_partition_order_(
3817 abs_residual_partition_sums,
3818 raw_bits_per_partition,
3822 min_partition_order,
3823 max_partition_order,
3825 rice_parameter_search_dist,
3826 &subframe->data.lpc.entropy_coding_method.data.partitioned_rice
3829 subframe->data.lpc.order = order;
3830 subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3831 subframe->data.lpc.quantization_level = quantization;
3832 memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3833 for(i = 0; i < order; i++)
3834 subframe->data.lpc.warmup[i] = signal[i];
3836 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;
3838 #if SPOTCHECK_ESTIMATE
3839 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3846 unsigned evaluate_verbatim_subframe_(
3847 FLAC__StreamEncoder *encoder,
3848 const FLAC__int32 signal[],
3850 unsigned subframe_bps,
3851 FLAC__Subframe *subframe
3856 subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3858 subframe->data.verbatim.data = signal;
3860 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
3862 #if SPOTCHECK_ESTIMATE
3863 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3871 unsigned find_best_partition_order_(
3872 FLAC__StreamEncoderPrivate *private_,
3873 const FLAC__int32 residual[],
3874 FLAC__uint64 abs_residual_partition_sums[],
3875 unsigned raw_bits_per_partition[],
3876 unsigned residual_samples,
3877 unsigned predictor_order,
3878 unsigned rice_parameter,
3879 unsigned min_partition_order,
3880 unsigned max_partition_order,
3881 FLAC__bool do_escape_coding,
3882 unsigned rice_parameter_search_dist,
3883 FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
3886 unsigned residual_bits, best_residual_bits = 0;
3887 unsigned best_parameters_index = 0;
3888 const unsigned blocksize = residual_samples + predictor_order;
3890 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3891 min_partition_order = min(min_partition_order, max_partition_order);
3893 precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order);
3895 if(do_escape_coding)
3896 precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3899 int partition_order;
3902 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3904 set_partitioned_rice_(
3905 #ifdef EXACT_RICE_BITS_CALCULATION
3908 abs_residual_partition_sums+sum,
3909 raw_bits_per_partition+sum,
3913 rice_parameter_search_dist,
3914 (unsigned)partition_order,
3916 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3921 FLAC__ASSERT(best_residual_bits != 0);
3924 sum += 1u << partition_order;
3925 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3926 best_residual_bits = residual_bits;
3927 best_parameters_index = !best_parameters_index;
3928 best_partitioned_rice->order = partition_order;
3934 * We are allowed to de-const the pointer based on our special knowledge;
3935 * it is const to the outside world.
3938 FLAC__EntropyCodingMethod_PartitionedRiceContents* best_partitioned_rice_contents = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_partitioned_rice->contents;
3939 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(best_partitioned_rice_contents, max(6, best_partitioned_rice->order));
3940 memcpy(best_partitioned_rice_contents->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
3941 memcpy(best_partitioned_rice_contents->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
3944 return best_residual_bits;
3947 void precompute_partition_info_sums_(
3948 const FLAC__int32 residual[],
3949 FLAC__uint64 abs_residual_partition_sums[],
3950 unsigned residual_samples,
3951 unsigned predictor_order,
3952 unsigned min_partition_order,
3953 unsigned max_partition_order
3956 int partition_order;
3957 unsigned from_partition, to_partition = 0;
3958 const unsigned blocksize = residual_samples + predictor_order;
3960 /* first do max_partition_order */
3961 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3962 FLAC__uint64 abs_residual_partition_sum; /* OPT: can reasonably be FLAC__uint32 for bps <= 17 and maybe higher */
3963 unsigned partition, partition_sample, partition_samples, residual_sample;
3964 const unsigned partitions = 1u << partition_order;
3965 const unsigned default_partition_samples = blocksize >> partition_order;
3967 FLAC__ASSERT(default_partition_samples > predictor_order);
3969 for(partition = residual_sample = 0; partition < partitions; partition++) {
3970 partition_samples = default_partition_samples;
3972 partition_samples -= predictor_order;
3973 abs_residual_partition_sum = 0;
3974 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++, residual_sample++) {
3975 #if defined _MSC_VER
3976 /* OPT: abs() may be faster for some compilers */
3977 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3979 const FLAC__int32 r = residual[residual_sample];
3981 abs_residual_partition_sum -= r;
3983 abs_residual_partition_sum += r;
3986 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3988 to_partition = partitions;
3992 /* now merge partitions for lower orders */
3993 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
3996 const unsigned partitions = 1u << partition_order;
3997 for(i = 0; i < partitions; i++) {
3998 s = abs_residual_partition_sums[from_partition];
4000 abs_residual_partition_sums[to_partition] = s + abs_residual_partition_sums[from_partition];
4007 void precompute_partition_info_escapes_(
4008 const FLAC__int32 residual[],
4009 unsigned raw_bits_per_partition[],
4010 unsigned residual_samples,
4011 unsigned predictor_order,
4012 unsigned min_partition_order,
4013 unsigned max_partition_order
4016 int partition_order;
4017 unsigned from_partition, to_partition = 0;
4018 const unsigned blocksize = residual_samples + predictor_order;
4020 /* first do max_partition_order */
4021 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
4024 unsigned partition, partition_sample, partition_samples, residual_sample;
4025 const unsigned partitions = 1u << partition_order;
4026 const unsigned default_partition_samples = blocksize >> partition_order;
4028 FLAC__ASSERT(default_partition_samples > predictor_order);
4030 for(partition = residual_sample = 0; partition < partitions; partition++) {
4031 partition_samples = default_partition_samples;
4033 partition_samples -= predictor_order;
4035 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
4036 r = residual[residual_sample++];
4037 /* OPT: maybe faster: rmax |= r ^ (r>>31) */
4043 /* now we know all residual values are in the range [-rmax-1,rmax] */
4044 raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
4046 to_partition = partitions;
4047 break; /*@@@ yuck, should remove the 'for' loop instead */
4050 /* now merge partitions for lower orders */
4051 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
4054 const unsigned partitions = 1u << partition_order;
4055 for(i = 0; i < partitions; i++) {
4056 m = raw_bits_per_partition[from_partition];
4058 raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
4065 #ifdef EXACT_RICE_BITS_CALCULATION
4066 static FLaC__INLINE unsigned count_rice_bits_in_partition_(
4067 const unsigned rice_parameter,
4068 const unsigned partition_samples,
4069 const FLAC__int32 *residual
4072 unsigned i, partition_bits =
4073 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN +
4074 (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
4076 for(i = 0; i < partition_samples; i++)
4077 partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
4078 return partition_bits;
4081 static FLaC__INLINE unsigned count_rice_bits_in_partition_(
4082 const unsigned rice_parameter,
4083 const unsigned partition_samples,
4084 const FLAC__uint64 abs_residual_partition_sum
4088 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN +
4089 (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
4092 (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
4093 : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
4095 - (partition_samples >> 1)
4096 /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
4097 * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
4098 * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
4099 * So the subtraction term tries to guess how many extra bits were contributed.
4100 * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
4106 FLAC__bool set_partitioned_rice_(
4107 #ifdef EXACT_RICE_BITS_CALCULATION
4108 const FLAC__int32 residual[],
4110 const FLAC__uint64 abs_residual_partition_sums[],
4111 const unsigned raw_bits_per_partition[],
4112 const unsigned residual_samples,
4113 const unsigned predictor_order,
4114 const unsigned suggested_rice_parameter,
4115 const unsigned rice_parameter_search_dist,
4116 const unsigned partition_order,
4117 const FLAC__bool search_for_escapes,
4118 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
4122 unsigned rice_parameter, partition_bits;
4123 unsigned best_partition_bits, best_rice_parameter = 0;
4124 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
4125 unsigned *parameters, *raw_bits;
4126 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4127 unsigned min_rice_parameter, max_rice_parameter;
4129 (void)rice_parameter_search_dist;
4132 FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
4134 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
4135 parameters = partitioned_rice_contents->parameters;
4136 raw_bits = partitioned_rice_contents->raw_bits;
4138 if(partition_order == 0) {
4139 best_partition_bits = 0xffffffff;
4140 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4141 if(rice_parameter_search_dist) {
4142 if(suggested_rice_parameter < rice_parameter_search_dist)
4143 min_rice_parameter = 0;
4145 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
4146 max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
4147 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
4148 #ifdef DEBUG_VERBOSE
4149 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
4151 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
4155 min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
4157 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4159 rice_parameter = suggested_rice_parameter;
4161 #ifdef EXACT_RICE_BITS_CALCULATION
4162 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
4164 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
4166 if(partition_bits < best_partition_bits) {
4167 best_rice_parameter = rice_parameter;
4168 best_partition_bits = partition_bits;
4170 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4173 if(search_for_escapes) {
4174 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;
4175 if(partition_bits <= best_partition_bits) {
4176 raw_bits[0] = raw_bits_per_partition[0];
4177 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
4178 best_partition_bits = partition_bits;
4181 parameters[0] = best_rice_parameter;
4182 bits_ += best_partition_bits;
4185 unsigned partition, residual_sample;
4186 unsigned partition_samples;
4187 FLAC__uint64 mean, k;
4188 const unsigned partitions = 1u << partition_order;
4189 for(partition = residual_sample = 0; partition < partitions; partition++) {
4190 partition_samples = (residual_samples+predictor_order) >> partition_order;
4191 if(partition == 0) {
4192 if(partition_samples <= predictor_order)
4195 partition_samples -= predictor_order;
4197 mean = abs_residual_partition_sums[partition];
4198 /* we are basically calculating the size in bits of the
4199 * average residual magnitude in the partition:
4200 * rice_parameter = floor(log2(mean/partition_samples))
4201 * 'mean' is not a good name for the variable, it is
4202 * actually the sum of magnitudes of all residual values
4203 * in the partition, so the actual mean is
4204 * mean/partition_samples
4206 for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
4208 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
4209 #ifdef DEBUG_VERBOSE
4210 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
4212 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
4215 best_partition_bits = 0xffffffff;
4216 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4217 if(rice_parameter_search_dist) {
4218 if(rice_parameter < rice_parameter_search_dist)
4219 min_rice_parameter = 0;
4221 min_rice_parameter = rice_parameter - rice_parameter_search_dist;
4222 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
4223 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
4224 #ifdef DEBUG_VERBOSE
4225 fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
4227 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
4231 min_rice_parameter = max_rice_parameter = rice_parameter;
4233 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4235 #ifdef EXACT_RICE_BITS_CALCULATION
4236 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
4238 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
4240 if(partition_bits < best_partition_bits) {
4241 best_rice_parameter = rice_parameter;
4242 best_partition_bits = partition_bits;
4244 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4247 if(search_for_escapes) {
4248 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;
4249 if(partition_bits <= best_partition_bits) {
4250 raw_bits[partition] = raw_bits_per_partition[partition];
4251 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
4252 best_partition_bits = partition_bits;
4255 parameters[partition] = best_rice_parameter;
4256 bits_ += best_partition_bits;
4257 residual_sample += partition_samples;
4265 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
4270 for(i = 0; i < samples && !(x&1); i++)
4277 for(shift = 0; !(x&1); shift++)
4282 for(i = 0; i < samples; i++)
4283 signal[i] >>= shift;
4289 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4293 for(channel = 0; channel < channels; channel++)
4294 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
4296 fifo->tail += wide_samples;
4298 FLAC__ASSERT(fifo->tail <= fifo->size);
4301 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4304 unsigned sample, wide_sample;
4305 unsigned tail = fifo->tail;
4307 sample = input_offset * channels;
4308 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
4309 for(channel = 0; channel < channels; channel++)
4310 fifo->data[channel][tail] = input[sample++];
4315 FLAC__ASSERT(fifo->tail <= fifo->size);
4318 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4320 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4321 const size_t encoded_bytes = encoder->private_->verify.output.bytes;
4324 if(encoder->private_->verify.needs_magic_hack) {
4325 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
4326 *bytes = FLAC__STREAM_SYNC_LENGTH;
4327 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
4328 encoder->private_->verify.needs_magic_hack = false;
4331 if(encoded_bytes == 0) {
4333 * If we get here, a FIFO underflow has occurred,
4334 * which means there is a bug somewhere.
4337 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
4339 else if(encoded_bytes < *bytes)
4340 *bytes = encoded_bytes;
4341 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
4342 encoder->private_->verify.output.data += *bytes;
4343 encoder->private_->verify.output.bytes -= *bytes;
4346 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
4349 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
4351 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
4353 const unsigned channels = frame->header.channels;
4354 const unsigned blocksize = frame->header.blocksize;
4355 const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
4359 for(channel = 0; channel < channels; channel++) {
4360 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
4361 unsigned i, sample = 0;
4362 FLAC__int32 expect = 0, got = 0;
4364 for(i = 0; i < blocksize; i++) {
4365 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
4367 expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
4368 got = (FLAC__int32)buffer[channel][i];
4372 FLAC__ASSERT(i < blocksize);
4373 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
4374 encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
4375 encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
4376 encoder->private_->verify.error_stats.channel = channel;
4377 encoder->private_->verify.error_stats.sample = sample;
4378 encoder->private_->verify.error_stats.expected = expect;
4379 encoder->private_->verify.error_stats.got = got;
4380 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
4381 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
4384 /* dequeue the frame from the fifo */
4385 encoder->private_->verify.input_fifo.tail -= blocksize;
4386 FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
4387 for(channel = 0; channel < channels; channel++)
4388 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]));
4389 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4392 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4394 (void)decoder, (void)metadata, (void)client_data;
4397 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4399 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4400 (void)decoder, (void)status;
4401 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4404 FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4408 *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
4410 if (feof(encoder->private_->file))
4411 return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
4412 else if (ferror(encoder->private_->file))
4413 return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
4415 return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
4418 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4422 if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
4423 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4425 return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4428 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4434 offset = ftello(encoder->private_->file);
4437 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4440 *absolute_byte_offset = (FLAC__uint64)offset;
4441 return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4445 #ifdef FLAC__VALGRIND_TESTING
4446 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4448 size_t ret = fwrite(ptr, size, nmemb, stream);
4454 #define local__fwrite fwrite
4457 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
4459 (void)client_data, (void)current_frame;
4461 if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4462 FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
4464 /* We would like to be able to use 'samples > 0' in the
4465 * clause here but currently because of the nature of our
4466 * Ogg writing implementation, 'samples' is always 0 (see
4467 * ogg_encoder_aspect.c). The downside is extra progress
4470 encoder->private_->is_ogg? true :
4475 /* NOTE: We have to add +bytes, +samples, and +1 to the stats
4476 * because at this point in the callback chain, the stats
4477 * have not been updated. Only after we return and control
4478 * gets back to write_frame_() are the stats updated
4480 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);
4482 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4485 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4489 * This will forcibly set stdout to binary mode (for OSes that require it)
4491 FILE *get_binary_stdout_(void)
4493 /* if something breaks here it is probably due to the presence or
4494 * absence of an underscore before the identifiers 'setmode',
4495 * 'fileno', and/or 'O_BINARY'; check your system header files.
4497 #if defined _MSC_VER || defined __MINGW32__
4498 _setmode(_fileno(stdout), _O_BINARY);
4499 #elif defined __CYGWIN__
4500 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4501 setmode(_fileno(stdout), _O_BINARY);
4502 #elif defined __EMX__
4503 setmode(fileno(stdout), O_BINARY);