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 FLAC__Subframe *subframe[2],
169 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
170 FLAC__int32 *residual[2],
171 unsigned *best_subframe,
175 static FLAC__bool add_subframe_(
176 FLAC__StreamEncoder *encoder,
178 unsigned subframe_bps,
179 const FLAC__Subframe *subframe,
180 FLAC__BitWriter *frame
183 static unsigned evaluate_constant_subframe_(
184 FLAC__StreamEncoder *encoder,
185 const FLAC__int32 signal,
187 unsigned subframe_bps,
188 FLAC__Subframe *subframe
191 static unsigned evaluate_fixed_subframe_(
192 FLAC__StreamEncoder *encoder,
193 const FLAC__int32 signal[],
194 FLAC__int32 residual[],
195 FLAC__uint64 abs_residual_partition_sums[],
196 unsigned raw_bits_per_partition[],
198 unsigned subframe_bps,
200 unsigned rice_parameter,
201 unsigned rice_parameter_limit,
202 unsigned min_partition_order,
203 unsigned max_partition_order,
204 FLAC__bool do_escape_coding,
205 unsigned rice_parameter_search_dist,
206 FLAC__Subframe *subframe,
207 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
210 #ifndef FLAC__INTEGER_ONLY_LIBRARY
211 static unsigned evaluate_lpc_subframe_(
212 FLAC__StreamEncoder *encoder,
213 const FLAC__int32 signal[],
214 FLAC__int32 residual[],
215 FLAC__uint64 abs_residual_partition_sums[],
216 unsigned raw_bits_per_partition[],
217 const FLAC__real lp_coeff[],
219 unsigned subframe_bps,
221 unsigned qlp_coeff_precision,
222 unsigned rice_parameter,
223 unsigned rice_parameter_limit,
224 unsigned min_partition_order,
225 unsigned max_partition_order,
226 FLAC__bool do_escape_coding,
227 unsigned rice_parameter_search_dist,
228 FLAC__Subframe *subframe,
229 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
233 static unsigned evaluate_verbatim_subframe_(
234 FLAC__StreamEncoder *encoder,
235 const FLAC__int32 signal[],
237 unsigned subframe_bps,
238 FLAC__Subframe *subframe
241 static unsigned find_best_partition_order_(
242 struct FLAC__StreamEncoderPrivate *private_,
243 const FLAC__int32 residual[],
244 FLAC__uint64 abs_residual_partition_sums[],
245 unsigned raw_bits_per_partition[],
246 unsigned residual_samples,
247 unsigned predictor_order,
248 unsigned rice_parameter,
249 unsigned rice_parameter_limit,
250 unsigned min_partition_order,
251 unsigned max_partition_order,
253 FLAC__bool do_escape_coding,
254 unsigned rice_parameter_search_dist,
255 FLAC__EntropyCodingMethod *best_ecm
258 static void precompute_partition_info_sums_(
259 const FLAC__int32 residual[],
260 FLAC__uint64 abs_residual_partition_sums[],
261 unsigned residual_samples,
262 unsigned predictor_order,
263 unsigned min_partition_order,
264 unsigned max_partition_order,
268 static void precompute_partition_info_escapes_(
269 const FLAC__int32 residual[],
270 unsigned raw_bits_per_partition[],
271 unsigned residual_samples,
272 unsigned predictor_order,
273 unsigned min_partition_order,
274 unsigned max_partition_order
277 static FLAC__bool set_partitioned_rice_(
278 #ifdef EXACT_RICE_BITS_CALCULATION
279 const FLAC__int32 residual[],
281 const FLAC__uint64 abs_residual_partition_sums[],
282 const unsigned raw_bits_per_partition[],
283 const unsigned residual_samples,
284 const unsigned predictor_order,
285 const unsigned suggested_rice_parameter,
286 const unsigned rice_parameter_limit,
287 const unsigned rice_parameter_search_dist,
288 const unsigned partition_order,
289 const FLAC__bool search_for_escapes,
290 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
294 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
296 /* verify-related routines: */
297 static void append_to_verify_fifo_(
298 verify_input_fifo *fifo,
299 const FLAC__int32 * const input[],
300 unsigned input_offset,
302 unsigned wide_samples
305 static void append_to_verify_fifo_interleaved_(
306 verify_input_fifo *fifo,
307 const FLAC__int32 input[],
308 unsigned input_offset,
310 unsigned wide_samples
313 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
314 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
315 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
316 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
318 static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
319 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
320 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
321 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);
322 static FILE *get_binary_stdout_(void);
325 /***********************************************************************
329 ***********************************************************************/
331 typedef struct FLAC__StreamEncoderPrivate {
332 unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
333 FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
334 FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
335 #ifndef FLAC__INTEGER_ONLY_LIBRARY
336 FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
337 FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
338 FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
339 FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
341 unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
342 unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
343 FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
344 FLAC__int32 *residual_workspace_mid_side[2][2];
345 FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
346 FLAC__Subframe subframe_workspace_mid_side[2][2];
347 FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
348 FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
349 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
350 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
351 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
352 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
353 unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
354 unsigned best_subframe_mid_side[2];
355 unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
356 unsigned best_subframe_bits_mid_side[2];
357 FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
358 unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
359 FLAC__BitWriter *frame; /* the current frame being worked on */
360 unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
361 unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
362 FLAC__ChannelAssignment last_channel_assignment;
363 FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
364 FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
365 unsigned current_sample_number;
366 unsigned current_frame_number;
367 FLAC__MD5Context md5context;
368 FLAC__CPUInfo cpuinfo;
369 #ifndef FLAC__INTEGER_ONLY_LIBRARY
370 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
372 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
374 #ifndef FLAC__INTEGER_ONLY_LIBRARY
375 void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
376 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[]);
377 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[]);
378 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[]);
380 FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
381 FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
382 FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
383 FLAC__bool disable_constant_subframes;
384 FLAC__bool disable_fixed_subframes;
385 FLAC__bool disable_verbatim_subframes;
389 FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
390 FLAC__StreamEncoderSeekCallback seek_callback;
391 FLAC__StreamEncoderTellCallback tell_callback;
392 FLAC__StreamEncoderWriteCallback write_callback;
393 FLAC__StreamEncoderMetadataCallback metadata_callback;
394 FLAC__StreamEncoderProgressCallback progress_callback;
396 unsigned first_seekpoint_to_check;
397 FILE *file; /* only used when encoding to a file */
398 FLAC__uint64 bytes_written;
399 FLAC__uint64 samples_written;
400 unsigned frames_written;
401 unsigned total_frames_estimate;
402 /* unaligned (original) pointers to allocated data */
403 FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
404 FLAC__int32 *integer_signal_mid_side_unaligned[2];
405 #ifndef FLAC__INTEGER_ONLY_LIBRARY
406 FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
407 FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
408 FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
409 FLAC__real *windowed_signal_unaligned;
411 FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
412 FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
413 FLAC__uint64 *abs_residual_partition_sums_unaligned;
414 unsigned *raw_bits_per_partition_unaligned;
416 * These fields have been moved here from private function local
417 * declarations merely to save stack space during encoding.
419 #ifndef FLAC__INTEGER_ONLY_LIBRARY
420 FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
422 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
424 * The data for the verify section
427 FLAC__StreamDecoder *decoder;
428 EncoderStateHint state_hint;
429 FLAC__bool needs_magic_hack;
430 verify_input_fifo input_fifo;
431 verify_output output;
433 FLAC__uint64 absolute_sample;
434 unsigned frame_number;
437 FLAC__int32 expected;
441 FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
442 } FLAC__StreamEncoderPrivate;
444 /***********************************************************************
446 * Public static class data
448 ***********************************************************************/
450 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
451 "FLAC__STREAM_ENCODER_OK",
452 "FLAC__STREAM_ENCODER_UNINITIALIZED",
453 "FLAC__STREAM_ENCODER_OGG_ERROR",
454 "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
455 "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
456 "FLAC__STREAM_ENCODER_CLIENT_ERROR",
457 "FLAC__STREAM_ENCODER_IO_ERROR",
458 "FLAC__STREAM_ENCODER_FRAMING_ERROR",
459 "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
462 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
463 "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
464 "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
465 "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
466 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
467 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
468 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
469 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
470 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
471 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
472 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
473 "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
474 "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
475 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
476 "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
479 FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
480 "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
481 "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
482 "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
483 "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
486 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
487 "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
488 "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
491 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
492 "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
493 "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
494 "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
497 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
498 "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
499 "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
500 "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
503 /* Number of samples that will be overread to watch for end of stream. By
504 * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
505 * always try to read blocksize+1 samples before encoding a block, so that
506 * even if the stream has a total sample count that is an integral multiple
507 * of the blocksize, we will still notice when we are encoding the last
508 * block. This is needed, for example, to correctly set the end-of-stream
509 * marker in Ogg FLAC.
511 * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
512 * not really any reason to change it.
514 static const unsigned OVERREAD_ = 1;
516 /***********************************************************************
518 * Class constructor/destructor
521 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
523 FLAC__StreamEncoder *encoder;
526 FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
528 encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
533 encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
534 if(encoder->protected_ == 0) {
539 encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
540 if(encoder->private_ == 0) {
541 free(encoder->protected_);
546 encoder->private_->frame = FLAC__bitwriter_new();
547 if(encoder->private_->frame == 0) {
548 free(encoder->private_);
549 free(encoder->protected_);
554 encoder->private_->file = 0;
556 set_defaults_(encoder);
558 encoder->private_->is_being_deleted = false;
560 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
561 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
562 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
564 for(i = 0; i < 2; i++) {
565 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
566 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
568 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
569 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
570 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
572 for(i = 0; i < 2; i++) {
573 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
574 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
577 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
578 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
579 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
581 for(i = 0; i < 2; i++) {
582 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
583 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
585 for(i = 0; i < 2; i++)
586 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
588 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
593 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
597 FLAC__ASSERT(0 != encoder);
598 FLAC__ASSERT(0 != encoder->protected_);
599 FLAC__ASSERT(0 != encoder->private_);
600 FLAC__ASSERT(0 != encoder->private_->frame);
602 encoder->private_->is_being_deleted = true;
604 (void)FLAC__stream_encoder_finish(encoder);
606 if(0 != encoder->private_->verify.decoder)
607 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
609 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
610 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
611 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
613 for(i = 0; i < 2; i++) {
614 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
615 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
617 for(i = 0; i < 2; i++)
618 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
620 FLAC__bitwriter_delete(encoder->private_->frame);
621 free(encoder->private_);
622 free(encoder->protected_);
626 /***********************************************************************
628 * Public class methods
630 ***********************************************************************/
632 static FLAC__StreamEncoderInitStatus init_stream_internal_(
633 FLAC__StreamEncoder *encoder,
634 FLAC__StreamEncoderReadCallback read_callback,
635 FLAC__StreamEncoderWriteCallback write_callback,
636 FLAC__StreamEncoderSeekCallback seek_callback,
637 FLAC__StreamEncoderTellCallback tell_callback,
638 FLAC__StreamEncoderMetadataCallback metadata_callback,
644 FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
646 FLAC__ASSERT(0 != encoder);
648 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
649 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
653 return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
656 if(0 == write_callback || (seek_callback && 0 == tell_callback))
657 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
659 if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
660 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
662 if(encoder->protected_->channels != 2) {
663 encoder->protected_->do_mid_side_stereo = false;
664 encoder->protected_->loose_mid_side_stereo = false;
666 else if(!encoder->protected_->do_mid_side_stereo)
667 encoder->protected_->loose_mid_side_stereo = false;
669 if(encoder->protected_->bits_per_sample >= 32)
670 encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
672 if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
673 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
675 if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
676 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
678 if(encoder->protected_->blocksize == 0) {
679 if(encoder->protected_->max_lpc_order == 0)
680 encoder->protected_->blocksize = 1152;
682 encoder->protected_->blocksize = 4096;
685 if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
686 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
688 if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
689 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
691 if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
692 return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
694 if(encoder->protected_->qlp_coeff_precision == 0) {
695 if(encoder->protected_->bits_per_sample < 16) {
696 /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
697 /* @@@ until then we'll make a guess */
698 encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
700 else if(encoder->protected_->bits_per_sample == 16) {
701 if(encoder->protected_->blocksize <= 192)
702 encoder->protected_->qlp_coeff_precision = 7;
703 else if(encoder->protected_->blocksize <= 384)
704 encoder->protected_->qlp_coeff_precision = 8;
705 else if(encoder->protected_->blocksize <= 576)
706 encoder->protected_->qlp_coeff_precision = 9;
707 else if(encoder->protected_->blocksize <= 1152)
708 encoder->protected_->qlp_coeff_precision = 10;
709 else if(encoder->protected_->blocksize <= 2304)
710 encoder->protected_->qlp_coeff_precision = 11;
711 else if(encoder->protected_->blocksize <= 4608)
712 encoder->protected_->qlp_coeff_precision = 12;
714 encoder->protected_->qlp_coeff_precision = 13;
717 if(encoder->protected_->blocksize <= 384)
718 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
719 else if(encoder->protected_->blocksize <= 1152)
720 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
722 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
724 FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
726 else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
727 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
729 if(encoder->protected_->streamable_subset) {
731 encoder->protected_->blocksize != 192 &&
732 encoder->protected_->blocksize != 576 &&
733 encoder->protected_->blocksize != 1152 &&
734 encoder->protected_->blocksize != 2304 &&
735 encoder->protected_->blocksize != 4608 &&
736 encoder->protected_->blocksize != 256 &&
737 encoder->protected_->blocksize != 512 &&
738 encoder->protected_->blocksize != 1024 &&
739 encoder->protected_->blocksize != 2048 &&
740 encoder->protected_->blocksize != 4096 &&
741 encoder->protected_->blocksize != 8192 &&
742 encoder->protected_->blocksize != 16384
744 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
745 if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
746 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
748 encoder->protected_->bits_per_sample != 8 &&
749 encoder->protected_->bits_per_sample != 12 &&
750 encoder->protected_->bits_per_sample != 16 &&
751 encoder->protected_->bits_per_sample != 20 &&
752 encoder->protected_->bits_per_sample != 24
754 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
755 if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
756 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
758 encoder->protected_->sample_rate <= 48000 &&
760 encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
761 encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
764 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
768 if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
769 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
770 if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
771 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
774 /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
775 if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
777 for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
778 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
779 FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
781 encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
782 encoder->protected_->metadata[0] = vc;
788 /* keep track of any SEEKTABLE block */
789 if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
791 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
792 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
793 encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
794 break; /* take only the first one */
799 /* validate metadata */
800 if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
801 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
802 metadata_has_seektable = false;
803 metadata_has_vorbis_comment = false;
804 metadata_picture_has_type1 = false;
805 metadata_picture_has_type2 = false;
806 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
807 const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
808 if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
809 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
810 else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
811 if(metadata_has_seektable) /* only one is allowed */
812 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
813 metadata_has_seektable = true;
814 if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
815 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
817 else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
818 if(metadata_has_vorbis_comment) /* only one is allowed */
819 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
820 metadata_has_vorbis_comment = true;
822 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
823 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
824 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
826 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
827 if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
828 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
829 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
830 if(metadata_picture_has_type1) /* there should only be 1 per stream */
831 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
832 metadata_picture_has_type1 = true;
833 /* standard icon must be 32x32 pixel PNG */
835 m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
837 (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
838 m->data.picture.width != 32 ||
839 m->data.picture.height != 32
842 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
844 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
845 if(metadata_picture_has_type2) /* there should only be 1 per stream */
846 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
847 metadata_picture_has_type2 = true;
852 encoder->private_->input_capacity = 0;
853 for(i = 0; i < encoder->protected_->channels; i++) {
854 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
855 #ifndef FLAC__INTEGER_ONLY_LIBRARY
856 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
859 for(i = 0; i < 2; i++) {
860 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
861 #ifndef FLAC__INTEGER_ONLY_LIBRARY
862 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
865 #ifndef FLAC__INTEGER_ONLY_LIBRARY
866 for(i = 0; i < encoder->protected_->num_apodizations; i++)
867 encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
868 encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
870 for(i = 0; i < encoder->protected_->channels; i++) {
871 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
872 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
873 encoder->private_->best_subframe[i] = 0;
875 for(i = 0; i < 2; i++) {
876 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
877 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
878 encoder->private_->best_subframe_mid_side[i] = 0;
880 encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
881 encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
882 #ifndef FLAC__INTEGER_ONLY_LIBRARY
883 encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
885 /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
886 /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply÷ by hand */
887 FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
888 FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
889 FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
890 FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
891 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);
893 if(encoder->private_->loose_mid_side_stereo_frames == 0)
894 encoder->private_->loose_mid_side_stereo_frames = 1;
895 encoder->private_->loose_mid_side_stereo_frame_count = 0;
896 encoder->private_->current_sample_number = 0;
897 encoder->private_->current_frame_number = 0;
899 encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
900 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? */
901 encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
904 * get the CPU info and set the function pointers
906 FLAC__cpu_info(&encoder->private_->cpuinfo);
907 /* first default to the non-asm routines */
908 #ifndef FLAC__INTEGER_ONLY_LIBRARY
909 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
911 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
912 #ifndef FLAC__INTEGER_ONLY_LIBRARY
913 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
914 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
915 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
917 /* now override with asm where appropriate */
918 #ifndef FLAC__INTEGER_ONLY_LIBRARY
919 # ifndef FLAC__NO_ASM
920 if(encoder->private_->cpuinfo.use_asm) {
921 # ifdef FLAC__CPU_IA32
922 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
923 # ifdef FLAC__HAS_NASM
924 if(encoder->private_->cpuinfo.data.ia32.sse) {
925 if(encoder->protected_->max_lpc_order < 4)
926 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
927 else if(encoder->protected_->max_lpc_order < 8)
928 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
929 else if(encoder->protected_->max_lpc_order < 12)
930 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
932 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
934 else if(encoder->private_->cpuinfo.data.ia32._3dnow)
935 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
937 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
938 if(encoder->private_->cpuinfo.data.ia32.mmx) {
939 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
940 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
943 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
944 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
946 if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
947 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
948 # endif /* FLAC__HAS_NASM */
949 # endif /* FLAC__CPU_IA32 */
951 # endif /* !FLAC__NO_ASM */
952 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
953 /* finally override based on wide-ness if necessary */
954 if(encoder->private_->use_wide_by_block) {
955 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
958 /* set state to OK; from here on, errors are fatal and we'll override the state then */
959 encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
962 encoder->private_->is_ogg = is_ogg;
963 if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
964 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
965 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
969 encoder->private_->read_callback = read_callback;
970 encoder->private_->write_callback = write_callback;
971 encoder->private_->seek_callback = seek_callback;
972 encoder->private_->tell_callback = tell_callback;
973 encoder->private_->metadata_callback = metadata_callback;
974 encoder->private_->client_data = client_data;
976 if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
977 /* the above function sets the state for us in case of an error */
978 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
981 if(!FLAC__bitwriter_init(encoder->private_->frame)) {
982 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
983 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
987 * Set up the verify stuff if necessary
989 if(encoder->protected_->verify) {
991 * First, set up the fifo which will hold the
992 * original signal to compare against
994 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
995 for(i = 0; i < encoder->protected_->channels; i++) {
996 if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder->private_->verify.input_fifo.size))) {
997 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
998 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1001 encoder->private_->verify.input_fifo.tail = 0;
1004 * Now set up a stream decoder for verification
1006 encoder->private_->verify.decoder = FLAC__stream_decoder_new();
1007 if(0 == encoder->private_->verify.decoder) {
1008 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1009 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1012 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) {
1013 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1014 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1017 encoder->private_->verify.error_stats.absolute_sample = 0;
1018 encoder->private_->verify.error_stats.frame_number = 0;
1019 encoder->private_->verify.error_stats.channel = 0;
1020 encoder->private_->verify.error_stats.sample = 0;
1021 encoder->private_->verify.error_stats.expected = 0;
1022 encoder->private_->verify.error_stats.got = 0;
1025 * These must be done before we write any metadata, because that
1026 * calls the write_callback, which uses these values.
1028 encoder->private_->first_seekpoint_to_check = 0;
1029 encoder->private_->samples_written = 0;
1030 encoder->protected_->streaminfo_offset = 0;
1031 encoder->protected_->seektable_offset = 0;
1032 encoder->protected_->audio_offset = 0;
1035 * write the stream header
1037 if(encoder->protected_->verify)
1038 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1039 if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1040 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1041 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1043 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1044 /* the above function sets the state for us in case of an error */
1045 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1049 * write the STREAMINFO metadata block
1051 if(encoder->protected_->verify)
1052 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1053 encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1054 encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1055 encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1056 encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1057 encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1058 encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1059 encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1060 encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1061 encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1062 encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1063 encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1064 memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1065 if(encoder->protected_->do_md5)
1066 FLAC__MD5Init(&encoder->private_->md5context);
1067 if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1068 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1069 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1071 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1072 /* the above function sets the state for us in case of an error */
1073 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1077 * Now that the STREAMINFO block is written, we can init this to an
1078 * absurdly-high value...
1080 encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1081 /* ... and clear this to 0 */
1082 encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1085 * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1086 * if not, we will write an empty one (FLAC__add_metadata_block()
1087 * automatically supplies the vendor string).
1089 * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1090 * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
1091 * true it will have already insured that the metadata list is properly
1094 if(!metadata_has_vorbis_comment) {
1095 FLAC__StreamMetadata vorbis_comment;
1096 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1097 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1098 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1099 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1100 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1101 vorbis_comment.data.vorbis_comment.num_comments = 0;
1102 vorbis_comment.data.vorbis_comment.comments = 0;
1103 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1104 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1105 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1107 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1108 /* the above function sets the state for us in case of an error */
1109 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1114 * write the user's metadata blocks
1116 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1117 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1118 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1119 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1120 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1122 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1123 /* the above function sets the state for us in case of an error */
1124 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1128 /* now that all the metadata is written, we save the stream offset */
1129 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 */
1130 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1131 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1134 if(encoder->protected_->verify)
1135 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1137 return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1140 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1141 FLAC__StreamEncoder *encoder,
1142 FLAC__StreamEncoderWriteCallback write_callback,
1143 FLAC__StreamEncoderSeekCallback seek_callback,
1144 FLAC__StreamEncoderTellCallback tell_callback,
1145 FLAC__StreamEncoderMetadataCallback metadata_callback,
1149 return init_stream_internal_(
1151 /*read_callback=*/0,
1161 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1162 FLAC__StreamEncoder *encoder,
1163 FLAC__StreamEncoderReadCallback read_callback,
1164 FLAC__StreamEncoderWriteCallback write_callback,
1165 FLAC__StreamEncoderSeekCallback seek_callback,
1166 FLAC__StreamEncoderTellCallback tell_callback,
1167 FLAC__StreamEncoderMetadataCallback metadata_callback,
1171 return init_stream_internal_(
1183 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1184 FLAC__StreamEncoder *encoder,
1186 FLAC__StreamEncoderProgressCallback progress_callback,
1191 FLAC__StreamEncoderInitStatus init_status;
1193 FLAC__ASSERT(0 != encoder);
1194 FLAC__ASSERT(0 != file);
1196 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1197 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1199 /* double protection */
1201 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1202 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1206 * To make sure that our file does not go unclosed after an error, we
1207 * must assign the FILE pointer before any further error can occur in
1211 file = get_binary_stdout_(); /* just to be safe */
1213 encoder->private_->file = file;
1215 encoder->private_->progress_callback = progress_callback;
1216 encoder->private_->bytes_written = 0;
1217 encoder->private_->samples_written = 0;
1218 encoder->private_->frames_written = 0;
1220 init_status = init_stream_internal_(
1222 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1223 file_write_callback_,
1224 encoder->private_->file == stdout? 0 : file_seek_callback_,
1225 encoder->private_->file == stdout? 0 : file_tell_callback_,
1226 /*metadata_callback=*/0,
1230 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1231 /* the above function sets the state for us in case of an error */
1236 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1238 FLAC__ASSERT(blocksize != 0);
1239 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1245 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1246 FLAC__StreamEncoder *encoder,
1248 FLAC__StreamEncoderProgressCallback progress_callback,
1252 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1255 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1256 FLAC__StreamEncoder *encoder,
1258 FLAC__StreamEncoderProgressCallback progress_callback,
1262 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1265 static FLAC__StreamEncoderInitStatus init_file_internal_(
1266 FLAC__StreamEncoder *encoder,
1267 const char *filename,
1268 FLAC__StreamEncoderProgressCallback progress_callback,
1275 FLAC__ASSERT(0 != encoder);
1278 * To make sure that our file does not go unclosed after an error, we
1279 * have to do the same entrance checks here that are later performed
1280 * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1282 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1283 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1285 file = filename? fopen(filename, "w+b") : stdout;
1288 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1289 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1292 return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1295 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1296 FLAC__StreamEncoder *encoder,
1297 const char *filename,
1298 FLAC__StreamEncoderProgressCallback progress_callback,
1302 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1305 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1306 FLAC__StreamEncoder *encoder,
1307 const char *filename,
1308 FLAC__StreamEncoderProgressCallback progress_callback,
1312 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1315 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1317 FLAC__bool error = false;
1319 FLAC__ASSERT(0 != encoder);
1320 FLAC__ASSERT(0 != encoder->private_);
1321 FLAC__ASSERT(0 != encoder->protected_);
1323 if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1326 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1327 if(encoder->private_->current_sample_number != 0) {
1328 const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1329 encoder->protected_->blocksize = encoder->private_->current_sample_number;
1330 if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1335 if(encoder->protected_->do_md5)
1336 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1338 if(!encoder->private_->is_being_deleted) {
1339 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1340 if(encoder->private_->seek_callback) {
1342 if(encoder->private_->is_ogg)
1343 update_ogg_metadata_(encoder);
1346 update_metadata_(encoder);
1348 /* check if an error occurred while updating metadata */
1349 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1352 if(encoder->private_->metadata_callback)
1353 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1356 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1358 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1363 if(0 != encoder->private_->file) {
1364 if(encoder->private_->file != stdout)
1365 fclose(encoder->private_->file);
1366 encoder->private_->file = 0;
1370 if(encoder->private_->is_ogg)
1371 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1375 set_defaults_(encoder);
1378 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1383 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1385 FLAC__ASSERT(0 != encoder);
1386 FLAC__ASSERT(0 != encoder->private_);
1387 FLAC__ASSERT(0 != encoder->protected_);
1388 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1391 /* can't check encoder->private_->is_ogg since that's not set until init time */
1392 FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1400 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1402 FLAC__ASSERT(0 != encoder);
1403 FLAC__ASSERT(0 != encoder->private_);
1404 FLAC__ASSERT(0 != encoder->protected_);
1405 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1407 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1408 encoder->protected_->verify = value;
1413 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1415 FLAC__ASSERT(0 != encoder);
1416 FLAC__ASSERT(0 != encoder->private_);
1417 FLAC__ASSERT(0 != encoder->protected_);
1418 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1420 encoder->protected_->streamable_subset = value;
1424 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
1426 FLAC__ASSERT(0 != encoder);
1427 FLAC__ASSERT(0 != encoder->private_);
1428 FLAC__ASSERT(0 != encoder->protected_);
1429 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1431 encoder->protected_->do_md5 = value;
1435 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1437 FLAC__ASSERT(0 != encoder);
1438 FLAC__ASSERT(0 != encoder->private_);
1439 FLAC__ASSERT(0 != encoder->protected_);
1440 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1442 encoder->protected_->channels = value;
1446 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1448 FLAC__ASSERT(0 != encoder);
1449 FLAC__ASSERT(0 != encoder->private_);
1450 FLAC__ASSERT(0 != encoder->protected_);
1451 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1453 encoder->protected_->bits_per_sample = value;
1457 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1459 FLAC__ASSERT(0 != encoder);
1460 FLAC__ASSERT(0 != encoder->private_);
1461 FLAC__ASSERT(0 != encoder->protected_);
1462 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1464 encoder->protected_->sample_rate = value;
1468 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1470 FLAC__bool ok = true;
1471 FLAC__ASSERT(0 != encoder);
1472 FLAC__ASSERT(0 != encoder->private_);
1473 FLAC__ASSERT(0 != encoder->protected_);
1474 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1476 if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1477 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1478 ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
1479 ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
1480 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1483 ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
1484 /* but it's too hard to specify the string in a locale-specific way */
1486 encoder->protected_->num_apodizations = 1;
1487 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1488 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1491 ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
1492 ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
1493 ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1494 ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
1495 ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
1496 ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1497 ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1498 ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
1502 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1504 FLAC__ASSERT(0 != encoder);
1505 FLAC__ASSERT(0 != encoder->private_);
1506 FLAC__ASSERT(0 != encoder->protected_);
1507 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1509 encoder->protected_->blocksize = value;
1513 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1515 FLAC__ASSERT(0 != encoder);
1516 FLAC__ASSERT(0 != encoder->private_);
1517 FLAC__ASSERT(0 != encoder->protected_);
1518 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1520 encoder->protected_->do_mid_side_stereo = value;
1524 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1526 FLAC__ASSERT(0 != encoder);
1527 FLAC__ASSERT(0 != encoder->private_);
1528 FLAC__ASSERT(0 != encoder->protected_);
1529 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1531 encoder->protected_->loose_mid_side_stereo = value;
1535 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1537 FLAC__ASSERT(0 != encoder);
1538 FLAC__ASSERT(0 != encoder->private_);
1539 FLAC__ASSERT(0 != encoder->protected_);
1540 FLAC__ASSERT(0 != specification);
1541 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1543 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1544 (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1546 encoder->protected_->num_apodizations = 0;
1548 const char *s = strchr(specification, ';');
1549 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1550 if (n==8 && 0 == strncmp("bartlett" , specification, n))
1551 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1552 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1553 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1554 else if(n==8 && 0 == strncmp("blackman" , specification, n))
1555 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1556 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1557 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1558 else if(n==6 && 0 == strncmp("connes" , specification, n))
1559 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1560 else if(n==7 && 0 == strncmp("flattop" , specification, n))
1561 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1562 else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
1563 FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1564 if (stddev > 0.0 && stddev <= 0.5) {
1565 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1566 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1569 else if(n==7 && 0 == strncmp("hamming" , specification, n))
1570 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1571 else if(n==4 && 0 == strncmp("hann" , specification, n))
1572 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1573 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1574 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1575 else if(n==7 && 0 == strncmp("nuttall" , specification, n))
1576 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1577 else if(n==9 && 0 == strncmp("rectangle" , specification, n))
1578 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1579 else if(n==8 && 0 == strncmp("triangle" , specification, n))
1580 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1581 else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
1582 FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1583 if (p >= 0.0 && p <= 1.0) {
1584 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1585 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1588 else if(n==5 && 0 == strncmp("welch" , specification, n))
1589 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1590 if (encoder->protected_->num_apodizations == 32)
1593 specification = s+1;
1597 if(encoder->protected_->num_apodizations == 0) {
1598 encoder->protected_->num_apodizations = 1;
1599 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1600 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1606 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1608 FLAC__ASSERT(0 != encoder);
1609 FLAC__ASSERT(0 != encoder->private_);
1610 FLAC__ASSERT(0 != encoder->protected_);
1611 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1613 encoder->protected_->max_lpc_order = value;
1617 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1619 FLAC__ASSERT(0 != encoder);
1620 FLAC__ASSERT(0 != encoder->private_);
1621 FLAC__ASSERT(0 != encoder->protected_);
1622 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1624 encoder->protected_->qlp_coeff_precision = value;
1628 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1630 FLAC__ASSERT(0 != encoder);
1631 FLAC__ASSERT(0 != encoder->private_);
1632 FLAC__ASSERT(0 != encoder->protected_);
1633 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1635 encoder->protected_->do_qlp_coeff_prec_search = value;
1639 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1641 FLAC__ASSERT(0 != encoder);
1642 FLAC__ASSERT(0 != encoder->private_);
1643 FLAC__ASSERT(0 != encoder->protected_);
1644 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1647 /*@@@ deprecated: */
1648 encoder->protected_->do_escape_coding = value;
1655 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1657 FLAC__ASSERT(0 != encoder);
1658 FLAC__ASSERT(0 != encoder->private_);
1659 FLAC__ASSERT(0 != encoder->protected_);
1660 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1662 encoder->protected_->do_exhaustive_model_search = value;
1666 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1668 FLAC__ASSERT(0 != encoder);
1669 FLAC__ASSERT(0 != encoder->private_);
1670 FLAC__ASSERT(0 != encoder->protected_);
1671 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1673 encoder->protected_->min_residual_partition_order = value;
1677 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1679 FLAC__ASSERT(0 != encoder);
1680 FLAC__ASSERT(0 != encoder->private_);
1681 FLAC__ASSERT(0 != encoder->protected_);
1682 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1684 encoder->protected_->max_residual_partition_order = value;
1688 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1690 FLAC__ASSERT(0 != encoder);
1691 FLAC__ASSERT(0 != encoder->private_);
1692 FLAC__ASSERT(0 != encoder->protected_);
1693 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1696 /*@@@ deprecated: */
1697 encoder->protected_->rice_parameter_search_dist = value;
1704 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1706 FLAC__ASSERT(0 != encoder);
1707 FLAC__ASSERT(0 != encoder->private_);
1708 FLAC__ASSERT(0 != encoder->protected_);
1709 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1711 encoder->protected_->total_samples_estimate = value;
1715 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1717 FLAC__ASSERT(0 != encoder);
1718 FLAC__ASSERT(0 != encoder->private_);
1719 FLAC__ASSERT(0 != encoder->protected_);
1720 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1726 /* realloc() does not do exactly what we want so... */
1727 if(encoder->protected_->metadata) {
1728 free(encoder->protected_->metadata);
1729 encoder->protected_->metadata = 0;
1730 encoder->protected_->num_metadata_blocks = 0;
1733 FLAC__StreamMetadata **m;
1734 if(0 == (m = (FLAC__StreamMetadata**)malloc(sizeof(m[0]) * num_blocks)))
1736 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1737 encoder->protected_->metadata = m;
1738 encoder->protected_->num_metadata_blocks = num_blocks;
1741 if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1748 * These three functions are not static, but not publically exposed in
1749 * include/FLAC/ either. They are used by the test suite.
1751 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1753 FLAC__ASSERT(0 != encoder);
1754 FLAC__ASSERT(0 != encoder->private_);
1755 FLAC__ASSERT(0 != encoder->protected_);
1756 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1758 encoder->private_->disable_constant_subframes = value;
1762 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1764 FLAC__ASSERT(0 != encoder);
1765 FLAC__ASSERT(0 != encoder->private_);
1766 FLAC__ASSERT(0 != encoder->protected_);
1767 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1769 encoder->private_->disable_fixed_subframes = value;
1773 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1775 FLAC__ASSERT(0 != encoder);
1776 FLAC__ASSERT(0 != encoder->private_);
1777 FLAC__ASSERT(0 != encoder->protected_);
1778 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1780 encoder->private_->disable_verbatim_subframes = value;
1784 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1786 FLAC__ASSERT(0 != encoder);
1787 FLAC__ASSERT(0 != encoder->private_);
1788 FLAC__ASSERT(0 != encoder->protected_);
1789 return encoder->protected_->state;
1792 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1794 FLAC__ASSERT(0 != encoder);
1795 FLAC__ASSERT(0 != encoder->private_);
1796 FLAC__ASSERT(0 != encoder->protected_);
1797 if(encoder->protected_->verify)
1798 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1800 return FLAC__STREAM_DECODER_UNINITIALIZED;
1803 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1805 FLAC__ASSERT(0 != encoder);
1806 FLAC__ASSERT(0 != encoder->private_);
1807 FLAC__ASSERT(0 != encoder->protected_);
1808 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1809 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1811 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1814 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)
1816 FLAC__ASSERT(0 != encoder);
1817 FLAC__ASSERT(0 != encoder->private_);
1818 FLAC__ASSERT(0 != encoder->protected_);
1819 if(0 != absolute_sample)
1820 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1821 if(0 != frame_number)
1822 *frame_number = encoder->private_->verify.error_stats.frame_number;
1824 *channel = encoder->private_->verify.error_stats.channel;
1826 *sample = encoder->private_->verify.error_stats.sample;
1828 *expected = encoder->private_->verify.error_stats.expected;
1830 *got = encoder->private_->verify.error_stats.got;
1833 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1835 FLAC__ASSERT(0 != encoder);
1836 FLAC__ASSERT(0 != encoder->private_);
1837 FLAC__ASSERT(0 != encoder->protected_);
1838 return encoder->protected_->verify;
1841 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1843 FLAC__ASSERT(0 != encoder);
1844 FLAC__ASSERT(0 != encoder->private_);
1845 FLAC__ASSERT(0 != encoder->protected_);
1846 return encoder->protected_->streamable_subset;
1849 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
1851 FLAC__ASSERT(0 != encoder);
1852 FLAC__ASSERT(0 != encoder->private_);
1853 FLAC__ASSERT(0 != encoder->protected_);
1854 return encoder->protected_->do_md5;
1857 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1859 FLAC__ASSERT(0 != encoder);
1860 FLAC__ASSERT(0 != encoder->private_);
1861 FLAC__ASSERT(0 != encoder->protected_);
1862 return encoder->protected_->channels;
1865 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1867 FLAC__ASSERT(0 != encoder);
1868 FLAC__ASSERT(0 != encoder->private_);
1869 FLAC__ASSERT(0 != encoder->protected_);
1870 return encoder->protected_->bits_per_sample;
1873 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1875 FLAC__ASSERT(0 != encoder);
1876 FLAC__ASSERT(0 != encoder->private_);
1877 FLAC__ASSERT(0 != encoder->protected_);
1878 return encoder->protected_->sample_rate;
1881 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1883 FLAC__ASSERT(0 != encoder);
1884 FLAC__ASSERT(0 != encoder->private_);
1885 FLAC__ASSERT(0 != encoder->protected_);
1886 return encoder->protected_->blocksize;
1889 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1891 FLAC__ASSERT(0 != encoder);
1892 FLAC__ASSERT(0 != encoder->private_);
1893 FLAC__ASSERT(0 != encoder->protected_);
1894 return encoder->protected_->do_mid_side_stereo;
1897 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1899 FLAC__ASSERT(0 != encoder);
1900 FLAC__ASSERT(0 != encoder->private_);
1901 FLAC__ASSERT(0 != encoder->protected_);
1902 return encoder->protected_->loose_mid_side_stereo;
1905 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1907 FLAC__ASSERT(0 != encoder);
1908 FLAC__ASSERT(0 != encoder->private_);
1909 FLAC__ASSERT(0 != encoder->protected_);
1910 return encoder->protected_->max_lpc_order;
1913 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1915 FLAC__ASSERT(0 != encoder);
1916 FLAC__ASSERT(0 != encoder->private_);
1917 FLAC__ASSERT(0 != encoder->protected_);
1918 return encoder->protected_->qlp_coeff_precision;
1921 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1923 FLAC__ASSERT(0 != encoder);
1924 FLAC__ASSERT(0 != encoder->private_);
1925 FLAC__ASSERT(0 != encoder->protected_);
1926 return encoder->protected_->do_qlp_coeff_prec_search;
1929 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1931 FLAC__ASSERT(0 != encoder);
1932 FLAC__ASSERT(0 != encoder->private_);
1933 FLAC__ASSERT(0 != encoder->protected_);
1934 return encoder->protected_->do_escape_coding;
1937 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1939 FLAC__ASSERT(0 != encoder);
1940 FLAC__ASSERT(0 != encoder->private_);
1941 FLAC__ASSERT(0 != encoder->protected_);
1942 return encoder->protected_->do_exhaustive_model_search;
1945 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1947 FLAC__ASSERT(0 != encoder);
1948 FLAC__ASSERT(0 != encoder->private_);
1949 FLAC__ASSERT(0 != encoder->protected_);
1950 return encoder->protected_->min_residual_partition_order;
1953 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1955 FLAC__ASSERT(0 != encoder);
1956 FLAC__ASSERT(0 != encoder->private_);
1957 FLAC__ASSERT(0 != encoder->protected_);
1958 return encoder->protected_->max_residual_partition_order;
1961 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1963 FLAC__ASSERT(0 != encoder);
1964 FLAC__ASSERT(0 != encoder->private_);
1965 FLAC__ASSERT(0 != encoder->protected_);
1966 return encoder->protected_->rice_parameter_search_dist;
1969 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1971 FLAC__ASSERT(0 != encoder);
1972 FLAC__ASSERT(0 != encoder->private_);
1973 FLAC__ASSERT(0 != encoder->protected_);
1974 return encoder->protected_->total_samples_estimate;
1977 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1979 unsigned i, j = 0, channel;
1980 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1982 FLAC__ASSERT(0 != encoder);
1983 FLAC__ASSERT(0 != encoder->private_);
1984 FLAC__ASSERT(0 != encoder->protected_);
1985 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1988 const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
1990 if(encoder->protected_->verify)
1991 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
1993 for(channel = 0; channel < channels; channel++)
1994 memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
1996 if(encoder->protected_->do_mid_side_stereo) {
1997 FLAC__ASSERT(channels == 2);
1998 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
1999 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2000 encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
2001 encoder->private_->integer_signal_mid_side[0][i] = (buffer[0][j] + buffer[1][j]) >> 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
2007 encoder->private_->current_sample_number += n;
2009 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2010 if(encoder->private_->current_sample_number > blocksize) {
2011 FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
2012 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2013 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2015 /* move unprocessed overread samples to beginnings of arrays */
2016 for(channel = 0; channel < channels; channel++)
2017 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2018 if(encoder->protected_->do_mid_side_stereo) {
2019 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2020 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2022 encoder->private_->current_sample_number = 1;
2024 } while(j < samples);
2029 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2031 unsigned i, j, k, channel;
2032 FLAC__int32 x, mid, side;
2033 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2035 FLAC__ASSERT(0 != encoder);
2036 FLAC__ASSERT(0 != encoder->private_);
2037 FLAC__ASSERT(0 != encoder->protected_);
2038 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2042 * we have several flavors of the same basic loop, optimized for
2043 * different conditions:
2045 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2047 * stereo coding: unroll channel loop
2050 if(encoder->protected_->verify)
2051 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2053 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2054 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2055 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2057 encoder->private_->integer_signal[1][i] = x;
2060 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2061 encoder->private_->integer_signal_mid_side[1][i] = side;
2062 encoder->private_->integer_signal_mid_side[0][i] = mid;
2064 encoder->private_->current_sample_number = i;
2065 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2067 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2069 /* move unprocessed overread samples to beginnings of arrays */
2070 FLAC__ASSERT(i == blocksize+OVERREAD_);
2071 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2072 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
2073 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
2074 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2075 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2076 encoder->private_->current_sample_number = 1;
2078 } while(j < samples);
2082 * independent channel coding: buffer each channel in inner loop
2085 if(encoder->protected_->verify)
2086 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2088 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2089 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2090 for(channel = 0; channel < channels; channel++)
2091 encoder->private_->integer_signal[channel][i] = buffer[k++];
2093 encoder->private_->current_sample_number = i;
2094 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2096 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2098 /* move unprocessed overread samples to beginnings of arrays */
2099 FLAC__ASSERT(i == blocksize+OVERREAD_);
2100 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2101 for(channel = 0; channel < channels; channel++)
2102 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2103 encoder->private_->current_sample_number = 1;
2105 } while(j < samples);
2111 /***********************************************************************
2113 * Private class methods
2115 ***********************************************************************/
2117 void set_defaults_(FLAC__StreamEncoder *encoder)
2119 FLAC__ASSERT(0 != encoder);
2121 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2122 encoder->protected_->verify = true;
2124 encoder->protected_->verify = false;
2126 encoder->protected_->streamable_subset = true;
2127 encoder->protected_->do_md5 = true;
2128 encoder->protected_->do_mid_side_stereo = false;
2129 encoder->protected_->loose_mid_side_stereo = false;
2130 encoder->protected_->channels = 2;
2131 encoder->protected_->bits_per_sample = 16;
2132 encoder->protected_->sample_rate = 44100;
2133 encoder->protected_->blocksize = 0;
2134 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2135 encoder->protected_->num_apodizations = 1;
2136 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2137 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2139 encoder->protected_->max_lpc_order = 0;
2140 encoder->protected_->qlp_coeff_precision = 0;
2141 encoder->protected_->do_qlp_coeff_prec_search = false;
2142 encoder->protected_->do_exhaustive_model_search = false;
2143 encoder->protected_->do_escape_coding = false;
2144 encoder->protected_->min_residual_partition_order = 0;
2145 encoder->protected_->max_residual_partition_order = 0;
2146 encoder->protected_->rice_parameter_search_dist = 0;
2147 encoder->protected_->total_samples_estimate = 0;
2148 encoder->protected_->metadata = 0;
2149 encoder->protected_->num_metadata_blocks = 0;
2151 encoder->private_->seek_table = 0;
2152 encoder->private_->disable_constant_subframes = false;
2153 encoder->private_->disable_fixed_subframes = false;
2154 encoder->private_->disable_verbatim_subframes = false;
2156 encoder->private_->is_ogg = false;
2158 encoder->private_->read_callback = 0;
2159 encoder->private_->write_callback = 0;
2160 encoder->private_->seek_callback = 0;
2161 encoder->private_->tell_callback = 0;
2162 encoder->private_->metadata_callback = 0;
2163 encoder->private_->progress_callback = 0;
2164 encoder->private_->client_data = 0;
2167 FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2171 void free_(FLAC__StreamEncoder *encoder)
2173 unsigned i, channel;
2175 FLAC__ASSERT(0 != encoder);
2176 if(encoder->protected_->metadata) {
2177 free(encoder->protected_->metadata);
2178 encoder->protected_->metadata = 0;
2179 encoder->protected_->num_metadata_blocks = 0;
2181 for(i = 0; i < encoder->protected_->channels; i++) {
2182 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2183 free(encoder->private_->integer_signal_unaligned[i]);
2184 encoder->private_->integer_signal_unaligned[i] = 0;
2186 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2187 if(0 != encoder->private_->real_signal_unaligned[i]) {
2188 free(encoder->private_->real_signal_unaligned[i]);
2189 encoder->private_->real_signal_unaligned[i] = 0;
2193 for(i = 0; i < 2; i++) {
2194 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2195 free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2196 encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2198 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2199 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2200 free(encoder->private_->real_signal_mid_side_unaligned[i]);
2201 encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2205 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2206 for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2207 if(0 != encoder->private_->window_unaligned[i]) {
2208 free(encoder->private_->window_unaligned[i]);
2209 encoder->private_->window_unaligned[i] = 0;
2212 if(0 != encoder->private_->windowed_signal_unaligned) {
2213 free(encoder->private_->windowed_signal_unaligned);
2214 encoder->private_->windowed_signal_unaligned = 0;
2217 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2218 for(i = 0; i < 2; i++) {
2219 if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2220 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2221 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2225 for(channel = 0; channel < 2; channel++) {
2226 for(i = 0; i < 2; i++) {
2227 if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2228 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2229 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2233 if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2234 free(encoder->private_->abs_residual_partition_sums_unaligned);
2235 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2237 if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2238 free(encoder->private_->raw_bits_per_partition_unaligned);
2239 encoder->private_->raw_bits_per_partition_unaligned = 0;
2241 if(encoder->protected_->verify) {
2242 for(i = 0; i < encoder->protected_->channels; i++) {
2243 if(0 != encoder->private_->verify.input_fifo.data[i]) {
2244 free(encoder->private_->verify.input_fifo.data[i]);
2245 encoder->private_->verify.input_fifo.data[i] = 0;
2249 FLAC__bitwriter_free(encoder->private_->frame);
2252 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2255 unsigned i, channel;
2257 FLAC__ASSERT(new_blocksize > 0);
2258 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2259 FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2261 /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2262 if(new_blocksize <= encoder->private_->input_capacity)
2267 /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
2268 * requires that the input arrays (in our case the integer signals)
2269 * have a buffer of up to 3 zeroes in front (at negative indices) for
2270 * alignment purposes; we use 4 in front to keep the data well-aligned.
2273 for(i = 0; ok && i < encoder->protected_->channels; i++) {
2274 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2275 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2276 encoder->private_->integer_signal[i] += 4;
2277 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2278 #if 0 /* @@@ currently unused */
2279 if(encoder->protected_->max_lpc_order > 0)
2280 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2284 for(i = 0; ok && i < 2; i++) {
2285 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]);
2286 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2287 encoder->private_->integer_signal_mid_side[i] += 4;
2288 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2289 #if 0 /* @@@ currently unused */
2290 if(encoder->protected_->max_lpc_order > 0)
2291 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]);
2295 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2296 if(ok && encoder->protected_->max_lpc_order > 0) {
2297 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2298 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2299 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2302 for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2303 for(i = 0; ok && i < 2; i++) {
2304 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2307 for(channel = 0; ok && channel < 2; channel++) {
2308 for(i = 0; ok && i < 2; i++) {
2309 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]);
2312 /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2313 /*@@@ 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) */
2314 ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2315 if(encoder->protected_->do_escape_coding)
2316 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2318 /* now adjust the windows if the blocksize has changed */
2319 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2320 if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2321 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2322 switch(encoder->protected_->apodizations[i].type) {
2323 case FLAC__APODIZATION_BARTLETT:
2324 FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2326 case FLAC__APODIZATION_BARTLETT_HANN:
2327 FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2329 case FLAC__APODIZATION_BLACKMAN:
2330 FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2332 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2333 FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2335 case FLAC__APODIZATION_CONNES:
2336 FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2338 case FLAC__APODIZATION_FLATTOP:
2339 FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2341 case FLAC__APODIZATION_GAUSS:
2342 FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2344 case FLAC__APODIZATION_HAMMING:
2345 FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2347 case FLAC__APODIZATION_HANN:
2348 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2350 case FLAC__APODIZATION_KAISER_BESSEL:
2351 FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2353 case FLAC__APODIZATION_NUTTALL:
2354 FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2356 case FLAC__APODIZATION_RECTANGLE:
2357 FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2359 case FLAC__APODIZATION_TRIANGLE:
2360 FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2362 case FLAC__APODIZATION_TUKEY:
2363 FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2365 case FLAC__APODIZATION_WELCH:
2366 FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2370 /* double protection */
2371 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2379 encoder->private_->input_capacity = new_blocksize;
2381 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2386 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2388 const FLAC__byte *buffer;
2391 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2393 if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2394 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2398 if(encoder->protected_->verify) {
2399 encoder->private_->verify.output.data = buffer;
2400 encoder->private_->verify.output.bytes = bytes;
2401 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2402 encoder->private_->verify.needs_magic_hack = true;
2405 if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2406 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2407 FLAC__bitwriter_clear(encoder->private_->frame);
2408 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2409 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2415 if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2416 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2417 FLAC__bitwriter_clear(encoder->private_->frame);
2418 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2422 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2423 FLAC__bitwriter_clear(encoder->private_->frame);
2426 encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2427 encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2433 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2435 FLAC__StreamEncoderWriteStatus status;
2436 FLAC__uint64 output_position = 0;
2438 /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2439 if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2440 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2441 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2445 * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2448 FLAC__MetadataType type = (buffer[0] & 0x7f);
2449 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2450 encoder->protected_->streaminfo_offset = output_position;
2451 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2452 encoder->protected_->seektable_offset = output_position;
2456 * Mark the current seek point if hit (if audio_offset == 0 that
2457 * means we're still writing metadata and haven't hit the first
2460 if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2461 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2462 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2463 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2464 FLAC__uint64 test_sample;
2466 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2467 test_sample = encoder->private_->seek_table->points[i].sample_number;
2468 if(test_sample > frame_last_sample) {
2471 else if(test_sample >= frame_first_sample) {
2472 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2473 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2474 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2475 encoder->private_->first_seekpoint_to_check++;
2476 /* DO NOT: "break;" and here's why:
2477 * The seektable template may contain more than one target
2478 * sample for any given frame; we will keep looping, generating
2479 * duplicate seekpoints for them, and we'll clean it up later,
2480 * just before writing the seektable back to the metadata.
2484 encoder->private_->first_seekpoint_to_check++;
2490 if(encoder->private_->is_ogg) {
2491 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2492 &encoder->protected_->ogg_encoder_aspect,
2496 encoder->private_->current_frame_number,
2498 (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2500 encoder->private_->client_data
2505 status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2507 if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2508 encoder->private_->bytes_written += bytes;
2509 encoder->private_->samples_written += samples;
2510 /* we keep a high watermark on the number of frames written because
2511 * when the encoder goes back to write metadata, 'current_frame'
2512 * will drop back to 0.
2514 encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2517 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2522 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2523 void update_metadata_(const FLAC__StreamEncoder *encoder)
2525 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2526 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2527 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2528 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2529 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2530 const unsigned bps = metadata->data.stream_info.bits_per_sample;
2531 FLAC__StreamEncoderSeekStatus seek_status;
2533 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2535 /* All this is based on intimate knowledge of the stream header
2536 * layout, but a change to the header format that would break this
2537 * would also break all streams encoded in the previous format.
2541 * Write MD5 signature
2544 const unsigned md5_offset =
2545 FLAC__STREAM_METADATA_HEADER_LENGTH +
2547 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2548 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2549 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2550 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2551 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2552 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2553 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2554 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2557 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2558 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2559 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2562 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2563 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2569 * Write total samples
2572 const unsigned total_samples_byte_offset =
2573 FLAC__STREAM_METADATA_HEADER_LENGTH +
2575 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2576 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2577 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2578 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2579 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2580 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2581 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2585 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2586 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2587 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2588 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2589 b[4] = (FLAC__byte)(samples & 0xFF);
2590 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) {
2591 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2592 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2595 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2596 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2602 * Write min/max framesize
2605 const unsigned min_framesize_offset =
2606 FLAC__STREAM_METADATA_HEADER_LENGTH +
2608 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2609 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2612 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2613 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2614 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2615 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2616 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2617 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2618 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) {
2619 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2620 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2623 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2624 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2632 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2635 FLAC__format_seektable_sort(encoder->private_->seek_table);
2637 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2639 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) {
2640 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2641 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2645 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2648 xx = encoder->private_->seek_table->points[i].sample_number;
2649 b[7] = (FLAC__byte)xx; xx >>= 8;
2650 b[6] = (FLAC__byte)xx; xx >>= 8;
2651 b[5] = (FLAC__byte)xx; xx >>= 8;
2652 b[4] = (FLAC__byte)xx; xx >>= 8;
2653 b[3] = (FLAC__byte)xx; xx >>= 8;
2654 b[2] = (FLAC__byte)xx; xx >>= 8;
2655 b[1] = (FLAC__byte)xx; xx >>= 8;
2656 b[0] = (FLAC__byte)xx; xx >>= 8;
2657 xx = encoder->private_->seek_table->points[i].stream_offset;
2658 b[15] = (FLAC__byte)xx; xx >>= 8;
2659 b[14] = (FLAC__byte)xx; xx >>= 8;
2660 b[13] = (FLAC__byte)xx; xx >>= 8;
2661 b[12] = (FLAC__byte)xx; xx >>= 8;
2662 b[11] = (FLAC__byte)xx; xx >>= 8;
2663 b[10] = (FLAC__byte)xx; xx >>= 8;
2664 b[9] = (FLAC__byte)xx; xx >>= 8;
2665 b[8] = (FLAC__byte)xx; xx >>= 8;
2666 x = encoder->private_->seek_table->points[i].frame_samples;
2667 b[17] = (FLAC__byte)x; x >>= 8;
2668 b[16] = (FLAC__byte)x; x >>= 8;
2669 if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2670 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2678 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2679 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2681 /* the # of bytes in the 1st packet that precede the STREAMINFO */
2682 static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2683 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2684 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2685 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2686 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2687 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2688 FLAC__STREAM_SYNC_LENGTH
2690 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2691 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2692 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2693 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2694 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2697 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2698 FLAC__ASSERT(0 != encoder->private_->seek_callback);
2700 /* Pre-check that client supports seeking, since we don't want the
2701 * ogg_helper code to ever have to deal with this condition.
2703 if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2706 /* All this is based on intimate knowledge of the stream header
2707 * layout, but a change to the header format that would break this
2708 * would also break all streams encoded in the previous format.
2712 ** Write STREAMINFO stats
2714 simple_ogg_page__init(&page);
2715 if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2716 simple_ogg_page__clear(&page);
2717 return; /* state already set */
2721 * Write MD5 signature
2724 const unsigned md5_offset =
2725 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2726 FLAC__STREAM_METADATA_HEADER_LENGTH +
2728 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2729 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2730 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2731 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2732 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2733 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2734 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2735 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2738 if(md5_offset + 16 > (unsigned)page.body_len) {
2739 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2740 simple_ogg_page__clear(&page);
2743 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2747 * Write total samples
2750 const unsigned total_samples_byte_offset =
2751 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2752 FLAC__STREAM_METADATA_HEADER_LENGTH +
2754 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2755 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2756 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2757 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2758 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2759 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2760 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2764 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2765 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2766 simple_ogg_page__clear(&page);
2769 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2770 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2771 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2772 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2773 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2774 b[4] = (FLAC__byte)(samples & 0xFF);
2775 memcpy(page.body + total_samples_byte_offset, b, 5);
2779 * Write min/max framesize
2782 const unsigned min_framesize_offset =
2783 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2784 FLAC__STREAM_METADATA_HEADER_LENGTH +
2786 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2787 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2790 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2791 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2792 simple_ogg_page__clear(&page);
2795 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2796 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2797 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2798 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2799 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2800 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2801 memcpy(page.body + min_framesize_offset, b, 6);
2803 if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2804 simple_ogg_page__clear(&page);
2805 return; /* state already set */
2807 simple_ogg_page__clear(&page);
2812 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2816 FLAC__format_seektable_sort(encoder->private_->seek_table);
2818 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2820 simple_ogg_page__init(&page);
2821 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2822 simple_ogg_page__clear(&page);
2823 return; /* state already set */
2826 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
2827 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2828 simple_ogg_page__clear(&page);
2832 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
2835 xx = encoder->private_->seek_table->points[i].sample_number;
2836 b[7] = (FLAC__byte)xx; xx >>= 8;
2837 b[6] = (FLAC__byte)xx; xx >>= 8;
2838 b[5] = (FLAC__byte)xx; xx >>= 8;
2839 b[4] = (FLAC__byte)xx; xx >>= 8;
2840 b[3] = (FLAC__byte)xx; xx >>= 8;
2841 b[2] = (FLAC__byte)xx; xx >>= 8;
2842 b[1] = (FLAC__byte)xx; xx >>= 8;
2843 b[0] = (FLAC__byte)xx; xx >>= 8;
2844 xx = encoder->private_->seek_table->points[i].stream_offset;
2845 b[15] = (FLAC__byte)xx; xx >>= 8;
2846 b[14] = (FLAC__byte)xx; xx >>= 8;
2847 b[13] = (FLAC__byte)xx; xx >>= 8;
2848 b[12] = (FLAC__byte)xx; xx >>= 8;
2849 b[11] = (FLAC__byte)xx; xx >>= 8;
2850 b[10] = (FLAC__byte)xx; xx >>= 8;
2851 b[9] = (FLAC__byte)xx; xx >>= 8;
2852 b[8] = (FLAC__byte)xx; xx >>= 8;
2853 x = encoder->private_->seek_table->points[i].frame_samples;
2854 b[17] = (FLAC__byte)x; x >>= 8;
2855 b[16] = (FLAC__byte)x; x >>= 8;
2859 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2860 simple_ogg_page__clear(&page);
2861 return; /* state already set */
2863 simple_ogg_page__clear(&page);
2868 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
2871 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2874 * Accumulate raw signal to the MD5 signature
2876 if(encoder->protected_->do_md5 && !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)) {
2877 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2882 * Process the frame header and subframes into the frame bitbuffer
2884 if(!process_subframes_(encoder, is_fractional_block)) {
2885 /* the above function sets the state for us in case of an error */
2890 * Zero-pad the frame to a byte_boundary
2892 if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
2893 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2898 * CRC-16 the whole thing
2900 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2902 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
2903 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
2905 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2912 if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
2913 /* the above function sets the state for us in case of an error */
2918 * Get ready for the next frame
2920 encoder->private_->current_sample_number = 0;
2921 encoder->private_->current_frame_number++;
2922 encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
2927 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
2929 FLAC__FrameHeader frame_header;
2930 unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
2931 FLAC__bool do_independent, do_mid_side;
2934 * Calculate the min,max Rice partition orders
2936 if(is_fractional_block) {
2937 max_partition_order = 0;
2940 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
2941 max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
2943 min_partition_order = min(min_partition_order, max_partition_order);
2948 frame_header.blocksize = encoder->protected_->blocksize;
2949 frame_header.sample_rate = encoder->protected_->sample_rate;
2950 frame_header.channels = encoder->protected_->channels;
2951 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
2952 frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
2953 frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2954 frame_header.number.frame_number = encoder->private_->current_frame_number;
2957 * Figure out what channel assignments to try
2959 if(encoder->protected_->do_mid_side_stereo) {
2960 if(encoder->protected_->loose_mid_side_stereo) {
2961 if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
2962 do_independent = true;
2966 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
2967 do_mid_side = !do_independent;
2971 do_independent = true;
2976 do_independent = true;
2977 do_mid_side = false;
2980 FLAC__ASSERT(do_independent || do_mid_side);
2983 * Check for wasted bits; set effective bps for each subframe
2985 if(do_independent) {
2986 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2987 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
2988 encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
2989 encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
2993 FLAC__ASSERT(encoder->protected_->channels == 2);
2994 for(channel = 0; channel < 2; channel++) {
2995 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
2996 encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
2997 encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
3002 * First do a normal encoding pass of each independent channel
3004 if(do_independent) {
3005 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3009 min_partition_order,
3010 max_partition_order,
3012 encoder->private_->subframe_bps[channel],
3013 encoder->private_->integer_signal[channel],
3014 encoder->private_->subframe_workspace_ptr[channel],
3015 encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3016 encoder->private_->residual_workspace[channel],
3017 encoder->private_->best_subframe+channel,
3018 encoder->private_->best_subframe_bits+channel
3026 * Now do mid and side channels if requested
3029 FLAC__ASSERT(encoder->protected_->channels == 2);
3031 for(channel = 0; channel < 2; channel++) {
3035 min_partition_order,
3036 max_partition_order,
3038 encoder->private_->subframe_bps_mid_side[channel],
3039 encoder->private_->integer_signal_mid_side[channel],
3040 encoder->private_->subframe_workspace_ptr_mid_side[channel],
3041 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3042 encoder->private_->residual_workspace_mid_side[channel],
3043 encoder->private_->best_subframe_mid_side+channel,
3044 encoder->private_->best_subframe_bits_mid_side+channel
3052 * Compose the frame bitbuffer
3055 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3056 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3057 FLAC__ChannelAssignment channel_assignment;
3059 FLAC__ASSERT(encoder->protected_->channels == 2);
3061 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3062 channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3065 unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3069 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3070 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
3071 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
3072 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
3073 FLAC__ASSERT(do_independent && do_mid_side);
3075 /* We have to figure out which channel assignent results in the smallest frame */
3076 bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
3077 bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
3078 bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
3079 bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3081 channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3082 min_bits = bits[channel_assignment];
3083 for(ca = 1; ca <= 3; ca++) {
3084 if(bits[ca] < min_bits) {
3085 min_bits = bits[ca];
3086 channel_assignment = (FLAC__ChannelAssignment)ca;
3091 frame_header.channel_assignment = channel_assignment;
3093 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3094 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3098 switch(channel_assignment) {
3099 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3100 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3101 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3103 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3104 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3105 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3107 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3108 left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3109 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3111 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3112 left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3113 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3119 switch(channel_assignment) {
3120 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3121 left_bps = encoder->private_->subframe_bps [0];
3122 right_bps = encoder->private_->subframe_bps [1];
3124 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3125 left_bps = encoder->private_->subframe_bps [0];
3126 right_bps = encoder->private_->subframe_bps_mid_side[1];
3128 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3129 left_bps = encoder->private_->subframe_bps_mid_side[1];
3130 right_bps = encoder->private_->subframe_bps [1];
3132 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3133 left_bps = encoder->private_->subframe_bps_mid_side[0];
3134 right_bps = encoder->private_->subframe_bps_mid_side[1];
3140 /* note that encoder_add_subframe_ sets the state for us in case of an error */
3141 if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3143 if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3147 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3148 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3152 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3153 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)) {
3154 /* the above function sets the state for us in case of an error */
3160 if(encoder->protected_->loose_mid_side_stereo) {
3161 encoder->private_->loose_mid_side_stereo_frame_count++;
3162 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3163 encoder->private_->loose_mid_side_stereo_frame_count = 0;
3166 encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3171 FLAC__bool process_subframe_(
3172 FLAC__StreamEncoder *encoder,
3173 unsigned min_partition_order,
3174 unsigned max_partition_order,
3175 const FLAC__FrameHeader *frame_header,
3176 unsigned subframe_bps,
3177 const FLAC__int32 integer_signal[],
3178 FLAC__Subframe *subframe[2],
3179 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3180 FLAC__int32 *residual[2],
3181 unsigned *best_subframe,
3185 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3186 FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3188 FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3190 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3191 FLAC__double lpc_residual_bits_per_sample;
3192 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 */
3193 FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3194 unsigned min_lpc_order, max_lpc_order, lpc_order;
3195 unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3197 unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3198 unsigned rice_parameter;
3199 unsigned _candidate_bits, _best_bits;
3200 unsigned _best_subframe;
3201 /* only use RICE2 partitions if stream bps > 16 */
3202 const unsigned rice_parameter_limit = FLAC__stream_encoder_get_bits_per_sample(encoder) > 16? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
3204 FLAC__ASSERT(frame_header->blocksize > 0);
3206 /* verbatim subframe is the baseline against which we measure other compressed subframes */
3208 if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3209 _best_bits = UINT_MAX;
3211 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3213 if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3214 unsigned signal_is_constant = false;
3215 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);
3216 /* check for constant subframe */
3218 !encoder->private_->disable_constant_subframes &&
3219 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3220 fixed_residual_bits_per_sample[1] == 0.0
3222 fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3225 /* the above means it's possible all samples are the same value; now double-check it: */
3227 signal_is_constant = true;
3228 for(i = 1; i < frame_header->blocksize; i++) {
3229 if(integer_signal[0] != integer_signal[i]) {
3230 signal_is_constant = false;
3235 if(signal_is_constant) {
3236 _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3237 if(_candidate_bits < _best_bits) {
3238 _best_subframe = !_best_subframe;
3239 _best_bits = _candidate_bits;
3243 if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3245 if(encoder->protected_->do_exhaustive_model_search) {
3246 min_fixed_order = 0;
3247 max_fixed_order = FLAC__MAX_FIXED_ORDER;
3250 min_fixed_order = max_fixed_order = guess_fixed_order;
3252 if(max_fixed_order >= frame_header->blocksize)
3253 max_fixed_order = frame_header->blocksize - 1;
3254 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3255 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3256 if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3257 continue; /* don't even try */
3258 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 */
3260 if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3261 continue; /* don't even try */
3262 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 */
3264 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3265 if(rice_parameter >= rice_parameter_limit) {
3266 #ifdef DEBUG_VERBOSE
3267 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
3269 rice_parameter = rice_parameter_limit - 1;
3272 evaluate_fixed_subframe_(
3275 residual[!_best_subframe],
3276 encoder->private_->abs_residual_partition_sums,
3277 encoder->private_->raw_bits_per_partition,
3278 frame_header->blocksize,
3282 rice_parameter_limit,
3283 min_partition_order,
3284 max_partition_order,
3285 encoder->protected_->do_escape_coding,
3286 encoder->protected_->rice_parameter_search_dist,
3287 subframe[!_best_subframe],
3288 partitioned_rice_contents[!_best_subframe]
3290 if(_candidate_bits < _best_bits) {
3291 _best_subframe = !_best_subframe;
3292 _best_bits = _candidate_bits;
3297 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3299 if(encoder->protected_->max_lpc_order > 0) {
3300 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3301 max_lpc_order = frame_header->blocksize-1;
3303 max_lpc_order = encoder->protected_->max_lpc_order;
3304 if(max_lpc_order > 0) {
3306 for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3307 FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3308 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3309 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3310 if(autoc[0] != 0.0) {
3311 FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3312 if(encoder->protected_->do_exhaustive_model_search) {
3316 const unsigned guess_lpc_order =
3317 FLAC__lpc_compute_best_order(
3320 frame_header->blocksize,
3322 encoder->protected_->do_qlp_coeff_prec_search?
3323 FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
3324 encoder->protected_->qlp_coeff_precision
3327 min_lpc_order = max_lpc_order = guess_lpc_order;
3329 if(max_lpc_order >= frame_header->blocksize)
3330 max_lpc_order = frame_header->blocksize - 1;
3331 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
3332 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
3333 if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
3334 continue; /* don't even try */
3335 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
3336 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3337 if(rice_parameter >= rice_parameter_limit) {
3338 #ifdef DEBUG_VERBOSE
3339 fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
3341 rice_parameter = rice_parameter_limit - 1;
3343 if(encoder->protected_->do_qlp_coeff_prec_search) {
3344 min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
3345 /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
3346 if(subframe_bps <= 17) {
3347 max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
3348 max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
3351 max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
3354 min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
3356 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
3358 evaluate_lpc_subframe_(
3361 residual[!_best_subframe],
3362 encoder->private_->abs_residual_partition_sums,
3363 encoder->private_->raw_bits_per_partition,
3364 encoder->private_->lp_coeff[lpc_order-1],
3365 frame_header->blocksize,
3368 qlp_coeff_precision,
3370 rice_parameter_limit,
3371 min_partition_order,
3372 max_partition_order,
3373 encoder->protected_->do_escape_coding,
3374 encoder->protected_->rice_parameter_search_dist,
3375 subframe[!_best_subframe],
3376 partitioned_rice_contents[!_best_subframe]
3378 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
3379 if(_candidate_bits < _best_bits) {
3380 _best_subframe = !_best_subframe;
3381 _best_bits = _candidate_bits;
3390 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3394 /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3395 if(_best_bits == UINT_MAX) {
3396 FLAC__ASSERT(_best_subframe == 0);
3397 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3400 *best_subframe = _best_subframe;
3401 *best_bits = _best_bits;
3406 FLAC__bool add_subframe_(
3407 FLAC__StreamEncoder *encoder,
3409 unsigned subframe_bps,
3410 const FLAC__Subframe *subframe,
3411 FLAC__BitWriter *frame
3414 switch(subframe->type) {
3415 case FLAC__SUBFRAME_TYPE_CONSTANT:
3416 if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3417 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3421 case FLAC__SUBFRAME_TYPE_FIXED:
3422 if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3423 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3427 case FLAC__SUBFRAME_TYPE_LPC:
3428 if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3429 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3433 case FLAC__SUBFRAME_TYPE_VERBATIM:
3434 if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3435 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3446 #define SPOTCHECK_ESTIMATE 0
3447 #if SPOTCHECK_ESTIMATE
3448 static void spotcheck_subframe_estimate_(
3449 FLAC__StreamEncoder *encoder,
3451 unsigned subframe_bps,
3452 const FLAC__Subframe *subframe,
3457 FLAC__BitWriter *frame = FLAC__bitwriter_new();
3459 fprintf(stderr, "EST: can't allocate frame\n");
3462 if(!FLAC__bitwriter_init(frame)) {
3463 fprintf(stderr, "EST: can't init frame\n");
3466 ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
3469 const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
3470 if(estimate != actual)
3471 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);
3473 FLAC__bitwriter_delete(frame);
3477 unsigned evaluate_constant_subframe_(
3478 FLAC__StreamEncoder *encoder,
3479 const FLAC__int32 signal,
3481 unsigned subframe_bps,
3482 FLAC__Subframe *subframe
3486 subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3487 subframe->data.constant.value = signal;
3489 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
3491 #if SPOTCHECK_ESTIMATE
3492 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3494 (void)encoder, (void)blocksize;
3500 unsigned evaluate_fixed_subframe_(
3501 FLAC__StreamEncoder *encoder,
3502 const FLAC__int32 signal[],
3503 FLAC__int32 residual[],
3504 FLAC__uint64 abs_residual_partition_sums[],
3505 unsigned raw_bits_per_partition[],
3507 unsigned subframe_bps,
3509 unsigned rice_parameter,
3510 unsigned rice_parameter_limit,
3511 unsigned min_partition_order,
3512 unsigned max_partition_order,
3513 FLAC__bool do_escape_coding,
3514 unsigned rice_parameter_search_dist,
3515 FLAC__Subframe *subframe,
3516 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3519 unsigned i, residual_bits, estimate;
3520 const unsigned residual_samples = blocksize - order;
3522 FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3524 subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3526 subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3527 subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3528 subframe->data.fixed.residual = residual;
3531 find_best_partition_order_(
3534 abs_residual_partition_sums,
3535 raw_bits_per_partition,
3539 rice_parameter_limit,
3540 min_partition_order,
3541 max_partition_order,
3544 rice_parameter_search_dist,
3545 &subframe->data.fixed.entropy_coding_method
3548 subframe->data.fixed.order = order;
3549 for(i = 0; i < order; i++)
3550 subframe->data.fixed.warmup[i] = signal[i];
3552 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
3554 #if SPOTCHECK_ESTIMATE
3555 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3561 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3562 unsigned evaluate_lpc_subframe_(
3563 FLAC__StreamEncoder *encoder,
3564 const FLAC__int32 signal[],
3565 FLAC__int32 residual[],
3566 FLAC__uint64 abs_residual_partition_sums[],
3567 unsigned raw_bits_per_partition[],
3568 const FLAC__real lp_coeff[],
3570 unsigned subframe_bps,
3572 unsigned qlp_coeff_precision,
3573 unsigned rice_parameter,
3574 unsigned rice_parameter_limit,
3575 unsigned min_partition_order,
3576 unsigned max_partition_order,
3577 FLAC__bool do_escape_coding,
3578 unsigned rice_parameter_search_dist,
3579 FLAC__Subframe *subframe,
3580 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3583 FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
3584 unsigned i, residual_bits, estimate;
3585 int quantization, ret;
3586 const unsigned residual_samples = blocksize - order;
3588 /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3589 if(subframe_bps <= 16) {
3590 FLAC__ASSERT(order > 0);
3591 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3592 qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3595 ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3597 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3599 if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3600 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3601 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3603 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3605 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3607 subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3609 subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3610 subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3611 subframe->data.lpc.residual = residual;
3614 find_best_partition_order_(
3617 abs_residual_partition_sums,
3618 raw_bits_per_partition,
3622 rice_parameter_limit,
3623 min_partition_order,
3624 max_partition_order,
3627 rice_parameter_search_dist,
3628 &subframe->data.lpc.entropy_coding_method
3631 subframe->data.lpc.order = order;
3632 subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3633 subframe->data.lpc.quantization_level = quantization;
3634 memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3635 for(i = 0; i < order; i++)
3636 subframe->data.lpc.warmup[i] = signal[i];
3638 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;
3640 #if SPOTCHECK_ESTIMATE
3641 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3648 unsigned evaluate_verbatim_subframe_(
3649 FLAC__StreamEncoder *encoder,
3650 const FLAC__int32 signal[],
3652 unsigned subframe_bps,
3653 FLAC__Subframe *subframe
3658 subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3660 subframe->data.verbatim.data = signal;
3662 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
3664 #if SPOTCHECK_ESTIMATE
3665 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3673 unsigned find_best_partition_order_(
3674 FLAC__StreamEncoderPrivate *private_,
3675 const FLAC__int32 residual[],
3676 FLAC__uint64 abs_residual_partition_sums[],
3677 unsigned raw_bits_per_partition[],
3678 unsigned residual_samples,
3679 unsigned predictor_order,
3680 unsigned rice_parameter,
3681 unsigned rice_parameter_limit,
3682 unsigned min_partition_order,
3683 unsigned max_partition_order,
3685 FLAC__bool do_escape_coding,
3686 unsigned rice_parameter_search_dist,
3687 FLAC__EntropyCodingMethod *best_ecm
3690 unsigned residual_bits, best_residual_bits = 0;
3691 unsigned best_parameters_index = 0;
3692 unsigned best_partition_order = 0;
3693 const unsigned blocksize = residual_samples + predictor_order;
3695 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3696 min_partition_order = min(min_partition_order, max_partition_order);
3698 precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
3700 if(do_escape_coding)
3701 precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3704 int partition_order;
3707 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3709 set_partitioned_rice_(
3710 #ifdef EXACT_RICE_BITS_CALCULATION
3713 abs_residual_partition_sums+sum,
3714 raw_bits_per_partition+sum,
3718 rice_parameter_limit,
3719 rice_parameter_search_dist,
3720 (unsigned)partition_order,
3722 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3727 FLAC__ASSERT(best_residual_bits != 0);
3730 sum += 1u << partition_order;
3731 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3732 best_residual_bits = residual_bits;
3733 best_parameters_index = !best_parameters_index;
3734 best_partition_order = partition_order;
3739 best_ecm->data.partitioned_rice.order = best_partition_order;
3743 * We are allowed to de-const the pointer based on our special
3744 * knowledge; it is const to the outside world.
3746 FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
3749 /* save best parameters and raw_bits */
3750 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
3751 memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
3752 if(do_escape_coding)
3753 memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
3755 * Now need to check if the type should be changed to
3756 * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
3757 * size of the rice parameters.
3759 for(partition = 0; partition < (1u<<best_partition_order); partition++) {
3760 if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3761 best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
3767 return best_residual_bits;
3770 #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
3771 extern void precompute_partition_info_sums_32bit_asm_ia32_(
3772 const FLAC__int32 residual[],
3773 FLAC__uint64 abs_residual_partition_sums[],
3775 unsigned predictor_order,
3776 unsigned min_partition_order,
3777 unsigned max_partition_order
3781 void precompute_partition_info_sums_(
3782 const FLAC__int32 residual[],
3783 FLAC__uint64 abs_residual_partition_sums[],
3784 unsigned residual_samples,
3785 unsigned predictor_order,
3786 unsigned min_partition_order,
3787 unsigned max_partition_order,
3791 const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
3792 unsigned partitions = 1u << max_partition_order;
3794 FLAC__ASSERT(default_partition_samples > predictor_order);
3796 #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
3797 /* slightly pessimistic but still catches all common cases */
3798 /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
3799 if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
3800 precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
3805 /* first do max_partition_order */
3807 unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
3808 /* slightly pessimistic but still catches all common cases */
3809 /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
3810 if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
3811 FLAC__uint32 abs_residual_partition_sum;
3813 for(partition = residual_sample = 0; partition < partitions; partition++) {
3814 end += default_partition_samples;
3815 abs_residual_partition_sum = 0;
3816 for( ; residual_sample < end; residual_sample++)
3817 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3818 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3821 else { /* have to pessimistically use 64 bits for accumulator */
3822 FLAC__uint64 abs_residual_partition_sum;
3824 for(partition = residual_sample = 0; partition < partitions; partition++) {
3825 end += default_partition_samples;
3826 abs_residual_partition_sum = 0;
3827 for( ; residual_sample < end; residual_sample++)
3828 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3829 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3834 /* now merge partitions for lower orders */
3836 unsigned from_partition = 0, to_partition = partitions;
3837 int partition_order;
3838 for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
3841 for(i = 0; i < partitions; i++) {
3842 abs_residual_partition_sums[to_partition++] =
3843 abs_residual_partition_sums[from_partition ] +
3844 abs_residual_partition_sums[from_partition+1];
3845 from_partition += 2;
3851 void precompute_partition_info_escapes_(
3852 const FLAC__int32 residual[],
3853 unsigned raw_bits_per_partition[],
3854 unsigned residual_samples,
3855 unsigned predictor_order,
3856 unsigned min_partition_order,
3857 unsigned max_partition_order
3860 int partition_order;
3861 unsigned from_partition, to_partition = 0;
3862 const unsigned blocksize = residual_samples + predictor_order;
3864 /* first do max_partition_order */
3865 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3868 unsigned partition, partition_sample, partition_samples, residual_sample;
3869 const unsigned partitions = 1u << partition_order;
3870 const unsigned default_partition_samples = blocksize >> partition_order;
3872 FLAC__ASSERT(default_partition_samples > predictor_order);
3874 for(partition = residual_sample = 0; partition < partitions; partition++) {
3875 partition_samples = default_partition_samples;
3877 partition_samples -= predictor_order;
3879 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
3880 r = residual[residual_sample++];
3881 /* OPT: maybe faster: rmax |= r ^ (r>>31) */
3887 /* now we know all residual values are in the range [-rmax-1,rmax] */
3888 raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
3890 to_partition = partitions;
3891 break; /*@@@ yuck, should remove the 'for' loop instead */
3894 /* now merge partitions for lower orders */
3895 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
3898 const unsigned partitions = 1u << partition_order;
3899 for(i = 0; i < partitions; i++) {
3900 m = raw_bits_per_partition[from_partition];
3902 raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
3909 #ifdef EXACT_RICE_BITS_CALCULATION
3910 static FLaC__INLINE unsigned count_rice_bits_in_partition_(
3911 const unsigned rice_parameter,
3912 const unsigned partition_samples,
3913 const FLAC__int32 *residual
3916 unsigned i, partition_bits =
3917 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
3918 (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
3920 for(i = 0; i < partition_samples; i++)
3921 partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
3922 return partition_bits;
3925 static FLaC__INLINE unsigned count_rice_bits_in_partition_(
3926 const unsigned rice_parameter,
3927 const unsigned partition_samples,
3928 const FLAC__uint64 abs_residual_partition_sum
3932 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
3933 (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
3936 (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
3937 : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
3939 - (partition_samples >> 1)
3940 /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
3941 * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
3942 * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
3943 * So the subtraction term tries to guess how many extra bits were contributed.
3944 * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
3950 FLAC__bool set_partitioned_rice_(
3951 #ifdef EXACT_RICE_BITS_CALCULATION
3952 const FLAC__int32 residual[],
3954 const FLAC__uint64 abs_residual_partition_sums[],
3955 const unsigned raw_bits_per_partition[],
3956 const unsigned residual_samples,
3957 const unsigned predictor_order,
3958 const unsigned suggested_rice_parameter,
3959 const unsigned rice_parameter_limit,
3960 const unsigned rice_parameter_search_dist,
3961 const unsigned partition_order,
3962 const FLAC__bool search_for_escapes,
3963 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3967 unsigned rice_parameter, partition_bits;
3968 unsigned best_partition_bits, best_rice_parameter = 0;
3969 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
3970 unsigned *parameters, *raw_bits;
3971 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3972 unsigned min_rice_parameter, max_rice_parameter;
3974 (void)rice_parameter_search_dist;
3977 FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
3978 FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
3980 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
3981 parameters = partitioned_rice_contents->parameters;
3982 raw_bits = partitioned_rice_contents->raw_bits;
3984 if(partition_order == 0) {
3985 best_partition_bits = (unsigned)(-1);
3986 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3987 if(rice_parameter_search_dist) {
3988 if(suggested_rice_parameter < rice_parameter_search_dist)
3989 min_rice_parameter = 0;
3991 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
3992 max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
3993 if(max_rice_parameter >= rice_parameter_limit) {
3994 #ifdef DEBUG_VERBOSE
3995 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
3997 max_rice_parameter = rice_parameter_limit - 1;
4001 min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
4003 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4005 rice_parameter = suggested_rice_parameter;
4007 #ifdef EXACT_RICE_BITS_CALCULATION
4008 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
4010 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
4012 if(partition_bits < best_partition_bits) {
4013 best_rice_parameter = rice_parameter;
4014 best_partition_bits = partition_bits;
4016 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4019 if(search_for_escapes) {
4020 partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[0] * residual_samples;
4021 if(partition_bits <= best_partition_bits) {
4022 raw_bits[0] = raw_bits_per_partition[0];
4023 best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4024 best_partition_bits = partition_bits;
4029 parameters[0] = best_rice_parameter;
4030 bits_ += best_partition_bits;
4033 unsigned partition, residual_sample;
4034 unsigned partition_samples;
4035 FLAC__uint64 mean, k;
4036 const unsigned partitions = 1u << partition_order;
4037 for(partition = residual_sample = 0; partition < partitions; partition++) {
4038 partition_samples = (residual_samples+predictor_order) >> partition_order;
4039 if(partition == 0) {
4040 if(partition_samples <= predictor_order)
4043 partition_samples -= predictor_order;
4045 mean = abs_residual_partition_sums[partition];
4046 /* we are basically calculating the size in bits of the
4047 * average residual magnitude in the partition:
4048 * rice_parameter = floor(log2(mean/partition_samples))
4049 * 'mean' is not a good name for the variable, it is
4050 * actually the sum of magnitudes of all residual values
4051 * in the partition, so the actual mean is
4052 * mean/partition_samples
4054 for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
4056 if(rice_parameter >= rice_parameter_limit) {
4057 #ifdef DEBUG_VERBOSE
4058 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
4060 rice_parameter = rice_parameter_limit - 1;
4063 best_partition_bits = (unsigned)(-1);
4064 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4065 if(rice_parameter_search_dist) {
4066 if(rice_parameter < rice_parameter_search_dist)
4067 min_rice_parameter = 0;
4069 min_rice_parameter = rice_parameter - rice_parameter_search_dist;
4070 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
4071 if(max_rice_parameter >= rice_parameter_limit) {
4072 #ifdef DEBUG_VERBOSE
4073 fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
4075 max_rice_parameter = rice_parameter_limit - 1;
4079 min_rice_parameter = max_rice_parameter = rice_parameter;
4081 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4083 #ifdef EXACT_RICE_BITS_CALCULATION
4084 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
4086 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
4088 if(partition_bits < best_partition_bits) {
4089 best_rice_parameter = rice_parameter;
4090 best_partition_bits = partition_bits;
4092 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4095 if(search_for_escapes) {
4096 partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[partition] * partition_samples;
4097 if(partition_bits <= best_partition_bits) {
4098 raw_bits[partition] = raw_bits_per_partition[partition];
4099 best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4100 best_partition_bits = partition_bits;
4103 raw_bits[partition] = 0;
4105 parameters[partition] = best_rice_parameter;
4106 bits_ += best_partition_bits;
4107 residual_sample += partition_samples;
4115 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
4120 for(i = 0; i < samples && !(x&1); i++)
4127 for(shift = 0; !(x&1); shift++)
4132 for(i = 0; i < samples; i++)
4133 signal[i] >>= shift;
4139 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4143 for(channel = 0; channel < channels; channel++)
4144 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
4146 fifo->tail += wide_samples;
4148 FLAC__ASSERT(fifo->tail <= fifo->size);
4151 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4154 unsigned sample, wide_sample;
4155 unsigned tail = fifo->tail;
4157 sample = input_offset * channels;
4158 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
4159 for(channel = 0; channel < channels; channel++)
4160 fifo->data[channel][tail] = input[sample++];
4165 FLAC__ASSERT(fifo->tail <= fifo->size);
4168 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4170 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4171 const size_t encoded_bytes = encoder->private_->verify.output.bytes;
4174 if(encoder->private_->verify.needs_magic_hack) {
4175 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
4176 *bytes = FLAC__STREAM_SYNC_LENGTH;
4177 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
4178 encoder->private_->verify.needs_magic_hack = false;
4181 if(encoded_bytes == 0) {
4183 * If we get here, a FIFO underflow has occurred,
4184 * which means there is a bug somewhere.
4187 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
4189 else if(encoded_bytes < *bytes)
4190 *bytes = encoded_bytes;
4191 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
4192 encoder->private_->verify.output.data += *bytes;
4193 encoder->private_->verify.output.bytes -= *bytes;
4196 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
4199 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
4201 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
4203 const unsigned channels = frame->header.channels;
4204 const unsigned blocksize = frame->header.blocksize;
4205 const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
4209 for(channel = 0; channel < channels; channel++) {
4210 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
4211 unsigned i, sample = 0;
4212 FLAC__int32 expect = 0, got = 0;
4214 for(i = 0; i < blocksize; i++) {
4215 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
4217 expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
4218 got = (FLAC__int32)buffer[channel][i];
4222 FLAC__ASSERT(i < blocksize);
4223 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
4224 encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
4225 encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
4226 encoder->private_->verify.error_stats.channel = channel;
4227 encoder->private_->verify.error_stats.sample = sample;
4228 encoder->private_->verify.error_stats.expected = expect;
4229 encoder->private_->verify.error_stats.got = got;
4230 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
4231 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
4234 /* dequeue the frame from the fifo */
4235 encoder->private_->verify.input_fifo.tail -= blocksize;
4236 FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
4237 for(channel = 0; channel < channels; channel++)
4238 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]));
4239 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4242 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4244 (void)decoder, (void)metadata, (void)client_data;
4247 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4249 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4250 (void)decoder, (void)status;
4251 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4254 FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4258 *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
4260 if (feof(encoder->private_->file))
4261 return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
4262 else if (ferror(encoder->private_->file))
4263 return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
4265 return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
4268 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4272 if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
4273 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4275 return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4278 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4284 offset = ftello(encoder->private_->file);
4287 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4290 *absolute_byte_offset = (FLAC__uint64)offset;
4291 return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4295 #ifdef FLAC__VALGRIND_TESTING
4296 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4298 size_t ret = fwrite(ptr, size, nmemb, stream);
4304 #define local__fwrite fwrite
4307 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
4309 (void)client_data, (void)current_frame;
4311 if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4312 FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
4314 /* We would like to be able to use 'samples > 0' in the
4315 * clause here but currently because of the nature of our
4316 * Ogg writing implementation, 'samples' is always 0 (see
4317 * ogg_encoder_aspect.c). The downside is extra progress
4320 encoder->private_->is_ogg? true :
4325 /* NOTE: We have to add +bytes, +samples, and +1 to the stats
4326 * because at this point in the callback chain, the stats
4327 * have not been updated. Only after we return and control
4328 * gets back to write_frame_() are the stats updated
4330 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);
4332 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4335 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4339 * This will forcibly set stdout to binary mode (for OSes that require it)
4341 FILE *get_binary_stdout_(void)
4343 /* if something breaks here it is probably due to the presence or
4344 * absence of an underscore before the identifiers 'setmode',
4345 * 'fileno', and/or 'O_BINARY'; check your system header files.
4347 #if defined _MSC_VER || defined __MINGW32__
4348 _setmode(_fileno(stdout), _O_BINARY);
4349 #elif defined __CYGWIN__
4350 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4351 setmode(_fileno(stdout), _O_BINARY);
4352 #elif defined __EMX__
4353 setmode(fileno(stdout), O_BINARY);