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 "share/alloc.h"
58 #include "protected/stream_encoder.h"
59 #include "private/bitwriter.h"
60 #include "private/bitmath.h"
61 #include "private/crc.h"
62 #include "private/cpu.h"
63 #include "private/fixed.h"
64 #include "private/format.h"
65 #include "private/lpc.h"
66 #include "private/md5.h"
67 #include "private/memory.h"
69 #include "private/ogg_helper.h"
70 #include "private/ogg_mapping.h"
72 #include "private/stream_encoder_framing.h"
73 #include "private/window.h"
75 #ifdef TARGET_MSDOS /* @@@ [2G limit] */
87 #define min(x,y) ((x)<(y)?(x):(y))
92 #define max(x,y) ((x)>(y)?(x):(y))
94 /* Exact Rice codeword length calculation is off by default. The simple
95 * (and fast) estimation (of how many bits a residual value will be
96 * encoded with) in this encoder is very good, almost always yielding
97 * compression within 0.1% of exact calculation.
99 #undef EXACT_RICE_BITS_CALCULATION
100 /* Rice parameter searching is off by default. The simple (and fast)
101 * parameter estimation in this encoder is very good, almost always
102 * yielding compression within 0.1% of the optimal parameters.
104 #undef ENABLE_RICE_PARAMETER_SEARCH
108 FLAC__int32 *data[FLAC__MAX_CHANNELS];
109 unsigned size; /* of each data[] in samples */
114 const FLAC__byte *data;
120 ENCODER_IN_MAGIC = 0,
121 ENCODER_IN_METADATA = 1,
125 static struct CompressionLevels {
126 FLAC__bool do_mid_side_stereo;
127 FLAC__bool loose_mid_side_stereo;
128 unsigned max_lpc_order;
129 unsigned qlp_coeff_precision;
130 FLAC__bool do_qlp_coeff_prec_search;
131 FLAC__bool do_escape_coding;
132 FLAC__bool do_exhaustive_model_search;
133 unsigned min_residual_partition_order;
134 unsigned max_residual_partition_order;
135 unsigned rice_parameter_search_dist;
136 } compression_levels_[] = {
137 { false, false, 0, 0, false, false, false, 0, 3, 0 },
138 { true , true , 0, 0, false, false, false, 0, 3, 0 },
139 { true , false, 0, 0, false, false, false, 0, 3, 0 },
140 { false, false, 6, 0, false, false, false, 0, 4, 0 },
141 { true , true , 8, 0, false, false, false, 0, 4, 0 },
142 { true , false, 8, 0, false, false, false, 0, 5, 0 },
143 { true , false, 8, 0, false, false, false, 0, 6, 0 },
144 { true , false, 8, 0, false, false, true , 0, 6, 0 },
145 { true , false, 12, 0, false, false, true , 0, 6, 0 }
149 /***********************************************************************
151 * Private class method prototypes
153 ***********************************************************************/
155 static void set_defaults_(FLAC__StreamEncoder *encoder);
156 static void free_(FLAC__StreamEncoder *encoder);
157 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
158 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
159 static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
160 static void update_metadata_(const FLAC__StreamEncoder *encoder);
162 static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
164 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
165 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
167 static FLAC__bool process_subframe_(
168 FLAC__StreamEncoder *encoder,
169 unsigned min_partition_order,
170 unsigned max_partition_order,
171 const FLAC__FrameHeader *frame_header,
172 unsigned subframe_bps,
173 const FLAC__int32 integer_signal[],
174 FLAC__Subframe *subframe[2],
175 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
176 FLAC__int32 *residual[2],
177 unsigned *best_subframe,
181 static FLAC__bool add_subframe_(
182 FLAC__StreamEncoder *encoder,
184 unsigned subframe_bps,
185 const FLAC__Subframe *subframe,
186 FLAC__BitWriter *frame
189 static unsigned evaluate_constant_subframe_(
190 FLAC__StreamEncoder *encoder,
191 const FLAC__int32 signal,
193 unsigned subframe_bps,
194 FLAC__Subframe *subframe
197 static unsigned evaluate_fixed_subframe_(
198 FLAC__StreamEncoder *encoder,
199 const FLAC__int32 signal[],
200 FLAC__int32 residual[],
201 FLAC__uint64 abs_residual_partition_sums[],
202 unsigned raw_bits_per_partition[],
204 unsigned subframe_bps,
206 unsigned rice_parameter,
207 unsigned rice_parameter_limit,
208 unsigned min_partition_order,
209 unsigned max_partition_order,
210 FLAC__bool do_escape_coding,
211 unsigned rice_parameter_search_dist,
212 FLAC__Subframe *subframe,
213 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
216 #ifndef FLAC__INTEGER_ONLY_LIBRARY
217 static unsigned evaluate_lpc_subframe_(
218 FLAC__StreamEncoder *encoder,
219 const FLAC__int32 signal[],
220 FLAC__int32 residual[],
221 FLAC__uint64 abs_residual_partition_sums[],
222 unsigned raw_bits_per_partition[],
223 const FLAC__real lp_coeff[],
225 unsigned subframe_bps,
227 unsigned qlp_coeff_precision,
228 unsigned rice_parameter,
229 unsigned rice_parameter_limit,
230 unsigned min_partition_order,
231 unsigned max_partition_order,
232 FLAC__bool do_escape_coding,
233 unsigned rice_parameter_search_dist,
234 FLAC__Subframe *subframe,
235 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
239 static unsigned evaluate_verbatim_subframe_(
240 FLAC__StreamEncoder *encoder,
241 const FLAC__int32 signal[],
243 unsigned subframe_bps,
244 FLAC__Subframe *subframe
247 static unsigned find_best_partition_order_(
248 struct FLAC__StreamEncoderPrivate *private_,
249 const FLAC__int32 residual[],
250 FLAC__uint64 abs_residual_partition_sums[],
251 unsigned raw_bits_per_partition[],
252 unsigned residual_samples,
253 unsigned predictor_order,
254 unsigned rice_parameter,
255 unsigned rice_parameter_limit,
256 unsigned min_partition_order,
257 unsigned max_partition_order,
259 FLAC__bool do_escape_coding,
260 unsigned rice_parameter_search_dist,
261 FLAC__EntropyCodingMethod *best_ecm
264 static void precompute_partition_info_sums_(
265 const FLAC__int32 residual[],
266 FLAC__uint64 abs_residual_partition_sums[],
267 unsigned residual_samples,
268 unsigned predictor_order,
269 unsigned min_partition_order,
270 unsigned max_partition_order,
274 static void precompute_partition_info_escapes_(
275 const FLAC__int32 residual[],
276 unsigned raw_bits_per_partition[],
277 unsigned residual_samples,
278 unsigned predictor_order,
279 unsigned min_partition_order,
280 unsigned max_partition_order
283 static FLAC__bool set_partitioned_rice_(
284 #ifdef EXACT_RICE_BITS_CALCULATION
285 const FLAC__int32 residual[],
287 const FLAC__uint64 abs_residual_partition_sums[],
288 const unsigned raw_bits_per_partition[],
289 const unsigned residual_samples,
290 const unsigned predictor_order,
291 const unsigned suggested_rice_parameter,
292 const unsigned rice_parameter_limit,
293 const unsigned rice_parameter_search_dist,
294 const unsigned partition_order,
295 const FLAC__bool search_for_escapes,
296 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
300 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
302 /* verify-related routines: */
303 static void append_to_verify_fifo_(
304 verify_input_fifo *fifo,
305 const FLAC__int32 * const input[],
306 unsigned input_offset,
308 unsigned wide_samples
311 static void append_to_verify_fifo_interleaved_(
312 verify_input_fifo *fifo,
313 const FLAC__int32 input[],
314 unsigned input_offset,
316 unsigned wide_samples
319 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
320 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
321 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
322 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
324 static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
325 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
326 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
327 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);
328 static FILE *get_binary_stdout_(void);
331 /***********************************************************************
335 ***********************************************************************/
337 typedef struct FLAC__StreamEncoderPrivate {
338 unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
339 FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
340 FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
341 #ifndef FLAC__INTEGER_ONLY_LIBRARY
342 FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
343 FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
344 FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
345 FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
347 unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
348 unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
349 FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
350 FLAC__int32 *residual_workspace_mid_side[2][2];
351 FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
352 FLAC__Subframe subframe_workspace_mid_side[2][2];
353 FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
354 FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
355 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
356 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
357 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
358 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
359 unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
360 unsigned best_subframe_mid_side[2];
361 unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
362 unsigned best_subframe_bits_mid_side[2];
363 FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
364 unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
365 FLAC__BitWriter *frame; /* the current frame being worked on */
366 unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
367 unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
368 FLAC__ChannelAssignment last_channel_assignment;
369 FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
370 FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
371 unsigned current_sample_number;
372 unsigned current_frame_number;
373 FLAC__MD5Context md5context;
374 FLAC__CPUInfo cpuinfo;
375 #ifndef FLAC__INTEGER_ONLY_LIBRARY
376 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
378 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
380 #ifndef FLAC__INTEGER_ONLY_LIBRARY
381 void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
382 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[]);
383 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[]);
384 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[]);
386 FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
387 FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
388 FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
389 FLAC__bool disable_constant_subframes;
390 FLAC__bool disable_fixed_subframes;
391 FLAC__bool disable_verbatim_subframes;
395 FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
396 FLAC__StreamEncoderSeekCallback seek_callback;
397 FLAC__StreamEncoderTellCallback tell_callback;
398 FLAC__StreamEncoderWriteCallback write_callback;
399 FLAC__StreamEncoderMetadataCallback metadata_callback;
400 FLAC__StreamEncoderProgressCallback progress_callback;
402 unsigned first_seekpoint_to_check;
403 FILE *file; /* only used when encoding to a file */
404 FLAC__uint64 bytes_written;
405 FLAC__uint64 samples_written;
406 unsigned frames_written;
407 unsigned total_frames_estimate;
408 /* unaligned (original) pointers to allocated data */
409 FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
410 FLAC__int32 *integer_signal_mid_side_unaligned[2];
411 #ifndef FLAC__INTEGER_ONLY_LIBRARY
412 FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
413 FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
414 FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
415 FLAC__real *windowed_signal_unaligned;
417 FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
418 FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
419 FLAC__uint64 *abs_residual_partition_sums_unaligned;
420 unsigned *raw_bits_per_partition_unaligned;
422 * These fields have been moved here from private function local
423 * declarations merely to save stack space during encoding.
425 #ifndef FLAC__INTEGER_ONLY_LIBRARY
426 FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
428 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
430 * The data for the verify section
433 FLAC__StreamDecoder *decoder;
434 EncoderStateHint state_hint;
435 FLAC__bool needs_magic_hack;
436 verify_input_fifo input_fifo;
437 verify_output output;
439 FLAC__uint64 absolute_sample;
440 unsigned frame_number;
443 FLAC__int32 expected;
447 FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
448 } FLAC__StreamEncoderPrivate;
450 /***********************************************************************
452 * Public static class data
454 ***********************************************************************/
456 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
457 "FLAC__STREAM_ENCODER_OK",
458 "FLAC__STREAM_ENCODER_UNINITIALIZED",
459 "FLAC__STREAM_ENCODER_OGG_ERROR",
460 "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
461 "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
462 "FLAC__STREAM_ENCODER_CLIENT_ERROR",
463 "FLAC__STREAM_ENCODER_IO_ERROR",
464 "FLAC__STREAM_ENCODER_FRAMING_ERROR",
465 "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
468 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
469 "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
470 "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
471 "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
472 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
473 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
474 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
475 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
476 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
477 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
478 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
479 "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
480 "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
481 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
482 "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
485 FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
486 "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
487 "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
488 "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
489 "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
492 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
493 "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
494 "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
497 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
498 "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
499 "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
500 "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
503 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
504 "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
505 "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
506 "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
509 /* Number of samples that will be overread to watch for end of stream. By
510 * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
511 * always try to read blocksize+1 samples before encoding a block, so that
512 * even if the stream has a total sample count that is an integral multiple
513 * of the blocksize, we will still notice when we are encoding the last
514 * block. This is needed, for example, to correctly set the end-of-stream
515 * marker in Ogg FLAC.
517 * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
518 * not really any reason to change it.
520 static const unsigned OVERREAD_ = 1;
522 /***********************************************************************
524 * Class constructor/destructor
527 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
529 FLAC__StreamEncoder *encoder;
532 FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
534 encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
539 encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
540 if(encoder->protected_ == 0) {
545 encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
546 if(encoder->private_ == 0) {
547 free(encoder->protected_);
552 encoder->private_->frame = FLAC__bitwriter_new();
553 if(encoder->private_->frame == 0) {
554 free(encoder->private_);
555 free(encoder->protected_);
560 encoder->private_->file = 0;
562 set_defaults_(encoder);
564 encoder->private_->is_being_deleted = false;
566 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
567 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
568 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
570 for(i = 0; i < 2; i++) {
571 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
572 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
574 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
575 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
576 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
578 for(i = 0; i < 2; i++) {
579 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
580 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
583 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
584 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
585 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
587 for(i = 0; i < 2; i++) {
588 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
589 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
591 for(i = 0; i < 2; i++)
592 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
594 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
599 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
603 FLAC__ASSERT(0 != encoder);
604 FLAC__ASSERT(0 != encoder->protected_);
605 FLAC__ASSERT(0 != encoder->private_);
606 FLAC__ASSERT(0 != encoder->private_->frame);
608 encoder->private_->is_being_deleted = true;
610 (void)FLAC__stream_encoder_finish(encoder);
612 if(0 != encoder->private_->verify.decoder)
613 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
615 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
616 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
617 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
619 for(i = 0; i < 2; i++) {
620 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
621 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
623 for(i = 0; i < 2; i++)
624 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
626 FLAC__bitwriter_delete(encoder->private_->frame);
627 free(encoder->private_);
628 free(encoder->protected_);
632 /***********************************************************************
634 * Public class methods
636 ***********************************************************************/
638 static FLAC__StreamEncoderInitStatus init_stream_internal_(
639 FLAC__StreamEncoder *encoder,
640 FLAC__StreamEncoderReadCallback read_callback,
641 FLAC__StreamEncoderWriteCallback write_callback,
642 FLAC__StreamEncoderSeekCallback seek_callback,
643 FLAC__StreamEncoderTellCallback tell_callback,
644 FLAC__StreamEncoderMetadataCallback metadata_callback,
650 FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
652 FLAC__ASSERT(0 != encoder);
654 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
655 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
659 return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
662 if(0 == write_callback || (seek_callback && 0 == tell_callback))
663 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
665 if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
666 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
668 if(encoder->protected_->channels != 2) {
669 encoder->protected_->do_mid_side_stereo = false;
670 encoder->protected_->loose_mid_side_stereo = false;
672 else if(!encoder->protected_->do_mid_side_stereo)
673 encoder->protected_->loose_mid_side_stereo = false;
675 if(encoder->protected_->bits_per_sample >= 32)
676 encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
678 if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
679 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
681 if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
682 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
684 if(encoder->protected_->blocksize == 0) {
685 if(encoder->protected_->max_lpc_order == 0)
686 encoder->protected_->blocksize = 1152;
688 encoder->protected_->blocksize = 4096;
691 if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
692 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
694 if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
695 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
697 if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
698 return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
700 if(encoder->protected_->qlp_coeff_precision == 0) {
701 if(encoder->protected_->bits_per_sample < 16) {
702 /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
703 /* @@@ until then we'll make a guess */
704 encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
706 else if(encoder->protected_->bits_per_sample == 16) {
707 if(encoder->protected_->blocksize <= 192)
708 encoder->protected_->qlp_coeff_precision = 7;
709 else if(encoder->protected_->blocksize <= 384)
710 encoder->protected_->qlp_coeff_precision = 8;
711 else if(encoder->protected_->blocksize <= 576)
712 encoder->protected_->qlp_coeff_precision = 9;
713 else if(encoder->protected_->blocksize <= 1152)
714 encoder->protected_->qlp_coeff_precision = 10;
715 else if(encoder->protected_->blocksize <= 2304)
716 encoder->protected_->qlp_coeff_precision = 11;
717 else if(encoder->protected_->blocksize <= 4608)
718 encoder->protected_->qlp_coeff_precision = 12;
720 encoder->protected_->qlp_coeff_precision = 13;
723 if(encoder->protected_->blocksize <= 384)
724 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
725 else if(encoder->protected_->blocksize <= 1152)
726 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
728 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
730 FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
732 else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
733 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
735 if(encoder->protected_->streamable_subset) {
737 encoder->protected_->blocksize != 192 &&
738 encoder->protected_->blocksize != 576 &&
739 encoder->protected_->blocksize != 1152 &&
740 encoder->protected_->blocksize != 2304 &&
741 encoder->protected_->blocksize != 4608 &&
742 encoder->protected_->blocksize != 256 &&
743 encoder->protected_->blocksize != 512 &&
744 encoder->protected_->blocksize != 1024 &&
745 encoder->protected_->blocksize != 2048 &&
746 encoder->protected_->blocksize != 4096 &&
747 encoder->protected_->blocksize != 8192 &&
748 encoder->protected_->blocksize != 16384
750 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
751 if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
752 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
754 encoder->protected_->bits_per_sample != 8 &&
755 encoder->protected_->bits_per_sample != 12 &&
756 encoder->protected_->bits_per_sample != 16 &&
757 encoder->protected_->bits_per_sample != 20 &&
758 encoder->protected_->bits_per_sample != 24
760 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
761 if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
762 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
764 encoder->protected_->sample_rate <= 48000 &&
766 encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
767 encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
770 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
774 if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
775 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
776 if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
777 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
780 /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
781 if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
783 for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
784 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
785 FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
787 encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
788 encoder->protected_->metadata[0] = vc;
794 /* keep track of any SEEKTABLE block */
795 if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
797 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
798 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
799 encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
800 break; /* take only the first one */
805 /* validate metadata */
806 if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
807 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
808 metadata_has_seektable = false;
809 metadata_has_vorbis_comment = false;
810 metadata_picture_has_type1 = false;
811 metadata_picture_has_type2 = false;
812 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
813 const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
814 if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
815 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
816 else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
817 if(metadata_has_seektable) /* only one is allowed */
818 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
819 metadata_has_seektable = true;
820 if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
821 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
823 else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
824 if(metadata_has_vorbis_comment) /* only one is allowed */
825 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
826 metadata_has_vorbis_comment = true;
828 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
829 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
830 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
832 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
833 if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
834 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
835 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
836 if(metadata_picture_has_type1) /* there should only be 1 per stream */
837 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
838 metadata_picture_has_type1 = true;
839 /* standard icon must be 32x32 pixel PNG */
841 m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
843 (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
844 m->data.picture.width != 32 ||
845 m->data.picture.height != 32
848 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
850 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
851 if(metadata_picture_has_type2) /* there should only be 1 per stream */
852 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
853 metadata_picture_has_type2 = true;
858 encoder->private_->input_capacity = 0;
859 for(i = 0; i < encoder->protected_->channels; i++) {
860 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
861 #ifndef FLAC__INTEGER_ONLY_LIBRARY
862 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
865 for(i = 0; i < 2; i++) {
866 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
867 #ifndef FLAC__INTEGER_ONLY_LIBRARY
868 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
871 #ifndef FLAC__INTEGER_ONLY_LIBRARY
872 for(i = 0; i < encoder->protected_->num_apodizations; i++)
873 encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
874 encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
876 for(i = 0; i < encoder->protected_->channels; i++) {
877 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
878 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
879 encoder->private_->best_subframe[i] = 0;
881 for(i = 0; i < 2; i++) {
882 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
883 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
884 encoder->private_->best_subframe_mid_side[i] = 0;
886 encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
887 encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
888 #ifndef FLAC__INTEGER_ONLY_LIBRARY
889 encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
891 /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
892 /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply÷ by hand */
893 FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
894 FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
895 FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
896 FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
897 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);
899 if(encoder->private_->loose_mid_side_stereo_frames == 0)
900 encoder->private_->loose_mid_side_stereo_frames = 1;
901 encoder->private_->loose_mid_side_stereo_frame_count = 0;
902 encoder->private_->current_sample_number = 0;
903 encoder->private_->current_frame_number = 0;
905 encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
906 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? */
907 encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
910 * get the CPU info and set the function pointers
912 FLAC__cpu_info(&encoder->private_->cpuinfo);
913 /* first default to the non-asm routines */
914 #ifndef FLAC__INTEGER_ONLY_LIBRARY
915 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
917 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
918 #ifndef FLAC__INTEGER_ONLY_LIBRARY
919 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
920 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
921 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
923 /* now override with asm where appropriate */
924 #ifndef FLAC__INTEGER_ONLY_LIBRARY
925 # ifndef FLAC__NO_ASM
926 if(encoder->private_->cpuinfo.use_asm) {
927 # ifdef FLAC__CPU_IA32
928 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
929 # ifdef FLAC__HAS_NASM
930 if(encoder->private_->cpuinfo.data.ia32.sse) {
931 if(encoder->protected_->max_lpc_order < 4)
932 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
933 else if(encoder->protected_->max_lpc_order < 8)
934 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
935 else if(encoder->protected_->max_lpc_order < 12)
936 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
938 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
940 else if(encoder->private_->cpuinfo.data.ia32._3dnow)
941 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
943 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
944 if(encoder->private_->cpuinfo.data.ia32.mmx) {
945 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
946 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
949 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
950 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
952 if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
953 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
954 # endif /* FLAC__HAS_NASM */
955 # endif /* FLAC__CPU_IA32 */
957 # endif /* !FLAC__NO_ASM */
958 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
959 /* finally override based on wide-ness if necessary */
960 if(encoder->private_->use_wide_by_block) {
961 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
964 /* set state to OK; from here on, errors are fatal and we'll override the state then */
965 encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
968 encoder->private_->is_ogg = is_ogg;
969 if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
970 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
971 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
975 encoder->private_->read_callback = read_callback;
976 encoder->private_->write_callback = write_callback;
977 encoder->private_->seek_callback = seek_callback;
978 encoder->private_->tell_callback = tell_callback;
979 encoder->private_->metadata_callback = metadata_callback;
980 encoder->private_->client_data = client_data;
982 if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
983 /* the above function sets the state for us in case of an error */
984 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
987 if(!FLAC__bitwriter_init(encoder->private_->frame)) {
988 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
989 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
993 * Set up the verify stuff if necessary
995 if(encoder->protected_->verify) {
997 * First, set up the fifo which will hold the
998 * original signal to compare against
1000 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
1001 for(i = 0; i < encoder->protected_->channels; i++) {
1002 if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)safe_malloc_mul_2op_(sizeof(FLAC__int32), /*times*/encoder->private_->verify.input_fifo.size))) {
1003 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1004 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1007 encoder->private_->verify.input_fifo.tail = 0;
1010 * Now set up a stream decoder for verification
1012 encoder->private_->verify.decoder = FLAC__stream_decoder_new();
1013 if(0 == encoder->private_->verify.decoder) {
1014 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1015 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1018 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) {
1019 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1020 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1023 encoder->private_->verify.error_stats.absolute_sample = 0;
1024 encoder->private_->verify.error_stats.frame_number = 0;
1025 encoder->private_->verify.error_stats.channel = 0;
1026 encoder->private_->verify.error_stats.sample = 0;
1027 encoder->private_->verify.error_stats.expected = 0;
1028 encoder->private_->verify.error_stats.got = 0;
1031 * These must be done before we write any metadata, because that
1032 * calls the write_callback, which uses these values.
1034 encoder->private_->first_seekpoint_to_check = 0;
1035 encoder->private_->samples_written = 0;
1036 encoder->protected_->streaminfo_offset = 0;
1037 encoder->protected_->seektable_offset = 0;
1038 encoder->protected_->audio_offset = 0;
1041 * write the stream header
1043 if(encoder->protected_->verify)
1044 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1045 if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1046 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1047 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1049 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1050 /* the above function sets the state for us in case of an error */
1051 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1055 * write the STREAMINFO metadata block
1057 if(encoder->protected_->verify)
1058 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1059 encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1060 encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1061 encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1062 encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1063 encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1064 encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1065 encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1066 encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1067 encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1068 encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1069 encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1070 memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1071 if(encoder->protected_->do_md5)
1072 FLAC__MD5Init(&encoder->private_->md5context);
1073 if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1074 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1075 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1077 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1078 /* the above function sets the state for us in case of an error */
1079 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1083 * Now that the STREAMINFO block is written, we can init this to an
1084 * absurdly-high value...
1086 encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1087 /* ... and clear this to 0 */
1088 encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1091 * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1092 * if not, we will write an empty one (FLAC__add_metadata_block()
1093 * automatically supplies the vendor string).
1095 * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1096 * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
1097 * true it will have already insured that the metadata list is properly
1100 if(!metadata_has_vorbis_comment) {
1101 FLAC__StreamMetadata vorbis_comment;
1102 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1103 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1104 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1105 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1106 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1107 vorbis_comment.data.vorbis_comment.num_comments = 0;
1108 vorbis_comment.data.vorbis_comment.comments = 0;
1109 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1110 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1111 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1113 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1114 /* the above function sets the state for us in case of an error */
1115 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1120 * write the user's metadata blocks
1122 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1123 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1124 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1125 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1126 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1128 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1129 /* the above function sets the state for us in case of an error */
1130 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1134 /* now that all the metadata is written, we save the stream offset */
1135 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 */
1136 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1137 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1140 if(encoder->protected_->verify)
1141 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1143 return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1146 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1147 FLAC__StreamEncoder *encoder,
1148 FLAC__StreamEncoderWriteCallback write_callback,
1149 FLAC__StreamEncoderSeekCallback seek_callback,
1150 FLAC__StreamEncoderTellCallback tell_callback,
1151 FLAC__StreamEncoderMetadataCallback metadata_callback,
1155 return init_stream_internal_(
1157 /*read_callback=*/0,
1167 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1168 FLAC__StreamEncoder *encoder,
1169 FLAC__StreamEncoderReadCallback read_callback,
1170 FLAC__StreamEncoderWriteCallback write_callback,
1171 FLAC__StreamEncoderSeekCallback seek_callback,
1172 FLAC__StreamEncoderTellCallback tell_callback,
1173 FLAC__StreamEncoderMetadataCallback metadata_callback,
1177 return init_stream_internal_(
1189 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1190 FLAC__StreamEncoder *encoder,
1192 FLAC__StreamEncoderProgressCallback progress_callback,
1197 FLAC__StreamEncoderInitStatus init_status;
1199 FLAC__ASSERT(0 != encoder);
1200 FLAC__ASSERT(0 != file);
1202 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1203 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1205 /* double protection */
1207 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1208 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1212 * To make sure that our file does not go unclosed after an error, we
1213 * must assign the FILE pointer before any further error can occur in
1217 file = get_binary_stdout_(); /* just to be safe */
1219 encoder->private_->file = file;
1221 encoder->private_->progress_callback = progress_callback;
1222 encoder->private_->bytes_written = 0;
1223 encoder->private_->samples_written = 0;
1224 encoder->private_->frames_written = 0;
1226 init_status = init_stream_internal_(
1228 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1229 file_write_callback_,
1230 encoder->private_->file == stdout? 0 : file_seek_callback_,
1231 encoder->private_->file == stdout? 0 : file_tell_callback_,
1232 /*metadata_callback=*/0,
1236 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1237 /* the above function sets the state for us in case of an error */
1242 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1244 FLAC__ASSERT(blocksize != 0);
1245 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1251 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1252 FLAC__StreamEncoder *encoder,
1254 FLAC__StreamEncoderProgressCallback progress_callback,
1258 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1261 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1262 FLAC__StreamEncoder *encoder,
1264 FLAC__StreamEncoderProgressCallback progress_callback,
1268 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1271 static FLAC__StreamEncoderInitStatus init_file_internal_(
1272 FLAC__StreamEncoder *encoder,
1273 const char *filename,
1274 FLAC__StreamEncoderProgressCallback progress_callback,
1281 FLAC__ASSERT(0 != encoder);
1284 * To make sure that our file does not go unclosed after an error, we
1285 * have to do the same entrance checks here that are later performed
1286 * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1288 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1289 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1291 file = filename? fopen(filename, "w+b") : stdout;
1294 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1295 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1298 return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1301 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1302 FLAC__StreamEncoder *encoder,
1303 const char *filename,
1304 FLAC__StreamEncoderProgressCallback progress_callback,
1308 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1311 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1312 FLAC__StreamEncoder *encoder,
1313 const char *filename,
1314 FLAC__StreamEncoderProgressCallback progress_callback,
1318 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1321 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1323 FLAC__bool error = false;
1325 FLAC__ASSERT(0 != encoder);
1326 FLAC__ASSERT(0 != encoder->private_);
1327 FLAC__ASSERT(0 != encoder->protected_);
1329 if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1332 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1333 if(encoder->private_->current_sample_number != 0) {
1334 const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1335 encoder->protected_->blocksize = encoder->private_->current_sample_number;
1336 if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1341 if(encoder->protected_->do_md5)
1342 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1344 if(!encoder->private_->is_being_deleted) {
1345 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1346 if(encoder->private_->seek_callback) {
1348 if(encoder->private_->is_ogg)
1349 update_ogg_metadata_(encoder);
1352 update_metadata_(encoder);
1354 /* check if an error occurred while updating metadata */
1355 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1358 if(encoder->private_->metadata_callback)
1359 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1362 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1364 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1369 if(0 != encoder->private_->file) {
1370 if(encoder->private_->file != stdout)
1371 fclose(encoder->private_->file);
1372 encoder->private_->file = 0;
1376 if(encoder->private_->is_ogg)
1377 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1381 set_defaults_(encoder);
1384 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1389 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1391 FLAC__ASSERT(0 != encoder);
1392 FLAC__ASSERT(0 != encoder->private_);
1393 FLAC__ASSERT(0 != encoder->protected_);
1394 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1397 /* can't check encoder->private_->is_ogg since that's not set until init time */
1398 FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1406 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1408 FLAC__ASSERT(0 != encoder);
1409 FLAC__ASSERT(0 != encoder->private_);
1410 FLAC__ASSERT(0 != encoder->protected_);
1411 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1413 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1414 encoder->protected_->verify = value;
1419 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1421 FLAC__ASSERT(0 != encoder);
1422 FLAC__ASSERT(0 != encoder->private_);
1423 FLAC__ASSERT(0 != encoder->protected_);
1424 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1426 encoder->protected_->streamable_subset = value;
1430 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
1432 FLAC__ASSERT(0 != encoder);
1433 FLAC__ASSERT(0 != encoder->private_);
1434 FLAC__ASSERT(0 != encoder->protected_);
1435 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1437 encoder->protected_->do_md5 = value;
1441 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1443 FLAC__ASSERT(0 != encoder);
1444 FLAC__ASSERT(0 != encoder->private_);
1445 FLAC__ASSERT(0 != encoder->protected_);
1446 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1448 encoder->protected_->channels = value;
1452 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1454 FLAC__ASSERT(0 != encoder);
1455 FLAC__ASSERT(0 != encoder->private_);
1456 FLAC__ASSERT(0 != encoder->protected_);
1457 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1459 encoder->protected_->bits_per_sample = value;
1463 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1465 FLAC__ASSERT(0 != encoder);
1466 FLAC__ASSERT(0 != encoder->private_);
1467 FLAC__ASSERT(0 != encoder->protected_);
1468 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1470 encoder->protected_->sample_rate = value;
1474 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1476 FLAC__bool ok = true;
1477 FLAC__ASSERT(0 != encoder);
1478 FLAC__ASSERT(0 != encoder->private_);
1479 FLAC__ASSERT(0 != encoder->protected_);
1480 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1482 if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1483 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1484 ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
1485 ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
1486 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1489 ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
1490 /* but it's too hard to specify the string in a locale-specific way */
1492 encoder->protected_->num_apodizations = 1;
1493 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1494 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1497 ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
1498 ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
1499 ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1500 ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
1501 ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
1502 ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1503 ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1504 ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
1508 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1510 FLAC__ASSERT(0 != encoder);
1511 FLAC__ASSERT(0 != encoder->private_);
1512 FLAC__ASSERT(0 != encoder->protected_);
1513 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1515 encoder->protected_->blocksize = value;
1519 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1521 FLAC__ASSERT(0 != encoder);
1522 FLAC__ASSERT(0 != encoder->private_);
1523 FLAC__ASSERT(0 != encoder->protected_);
1524 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1526 encoder->protected_->do_mid_side_stereo = value;
1530 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1532 FLAC__ASSERT(0 != encoder);
1533 FLAC__ASSERT(0 != encoder->private_);
1534 FLAC__ASSERT(0 != encoder->protected_);
1535 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1537 encoder->protected_->loose_mid_side_stereo = value;
1541 /*@@@@add to tests*/
1542 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1544 FLAC__ASSERT(0 != encoder);
1545 FLAC__ASSERT(0 != encoder->private_);
1546 FLAC__ASSERT(0 != encoder->protected_);
1547 FLAC__ASSERT(0 != specification);
1548 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1550 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1551 (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1553 encoder->protected_->num_apodizations = 0;
1555 const char *s = strchr(specification, ';');
1556 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1557 if (n==8 && 0 == strncmp("bartlett" , specification, n))
1558 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1559 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1560 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1561 else if(n==8 && 0 == strncmp("blackman" , specification, n))
1562 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1563 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1564 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1565 else if(n==6 && 0 == strncmp("connes" , specification, n))
1566 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1567 else if(n==7 && 0 == strncmp("flattop" , specification, n))
1568 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1569 else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
1570 FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1571 if (stddev > 0.0 && stddev <= 0.5) {
1572 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1573 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1576 else if(n==7 && 0 == strncmp("hamming" , specification, n))
1577 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1578 else if(n==4 && 0 == strncmp("hann" , specification, n))
1579 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1580 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1581 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1582 else if(n==7 && 0 == strncmp("nuttall" , specification, n))
1583 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1584 else if(n==9 && 0 == strncmp("rectangle" , specification, n))
1585 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1586 else if(n==8 && 0 == strncmp("triangle" , specification, n))
1587 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1588 else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
1589 FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1590 if (p >= 0.0 && p <= 1.0) {
1591 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1592 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1595 else if(n==5 && 0 == strncmp("welch" , specification, n))
1596 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1597 if (encoder->protected_->num_apodizations == 32)
1600 specification = s+1;
1604 if(encoder->protected_->num_apodizations == 0) {
1605 encoder->protected_->num_apodizations = 1;
1606 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1607 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1613 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1615 FLAC__ASSERT(0 != encoder);
1616 FLAC__ASSERT(0 != encoder->private_);
1617 FLAC__ASSERT(0 != encoder->protected_);
1618 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1620 encoder->protected_->max_lpc_order = value;
1624 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1626 FLAC__ASSERT(0 != encoder);
1627 FLAC__ASSERT(0 != encoder->private_);
1628 FLAC__ASSERT(0 != encoder->protected_);
1629 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1631 encoder->protected_->qlp_coeff_precision = value;
1635 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1637 FLAC__ASSERT(0 != encoder);
1638 FLAC__ASSERT(0 != encoder->private_);
1639 FLAC__ASSERT(0 != encoder->protected_);
1640 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1642 encoder->protected_->do_qlp_coeff_prec_search = value;
1646 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1648 FLAC__ASSERT(0 != encoder);
1649 FLAC__ASSERT(0 != encoder->private_);
1650 FLAC__ASSERT(0 != encoder->protected_);
1651 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1654 /*@@@ deprecated: */
1655 encoder->protected_->do_escape_coding = value;
1662 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1664 FLAC__ASSERT(0 != encoder);
1665 FLAC__ASSERT(0 != encoder->private_);
1666 FLAC__ASSERT(0 != encoder->protected_);
1667 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1669 encoder->protected_->do_exhaustive_model_search = value;
1673 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1675 FLAC__ASSERT(0 != encoder);
1676 FLAC__ASSERT(0 != encoder->private_);
1677 FLAC__ASSERT(0 != encoder->protected_);
1678 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1680 encoder->protected_->min_residual_partition_order = value;
1684 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1686 FLAC__ASSERT(0 != encoder);
1687 FLAC__ASSERT(0 != encoder->private_);
1688 FLAC__ASSERT(0 != encoder->protected_);
1689 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1691 encoder->protected_->max_residual_partition_order = value;
1695 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1697 FLAC__ASSERT(0 != encoder);
1698 FLAC__ASSERT(0 != encoder->private_);
1699 FLAC__ASSERT(0 != encoder->protected_);
1700 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1703 /*@@@ deprecated: */
1704 encoder->protected_->rice_parameter_search_dist = value;
1711 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1713 FLAC__ASSERT(0 != encoder);
1714 FLAC__ASSERT(0 != encoder->private_);
1715 FLAC__ASSERT(0 != encoder->protected_);
1716 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1718 encoder->protected_->total_samples_estimate = value;
1722 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1724 FLAC__ASSERT(0 != encoder);
1725 FLAC__ASSERT(0 != encoder->private_);
1726 FLAC__ASSERT(0 != encoder->protected_);
1727 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1733 /* realloc() does not do exactly what we want so... */
1734 if(encoder->protected_->metadata) {
1735 free(encoder->protected_->metadata);
1736 encoder->protected_->metadata = 0;
1737 encoder->protected_->num_metadata_blocks = 0;
1740 FLAC__StreamMetadata **m;
1741 if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
1743 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1744 encoder->protected_->metadata = m;
1745 encoder->protected_->num_metadata_blocks = num_blocks;
1748 if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1755 * These three functions are not static, but not publically exposed in
1756 * include/FLAC/ either. They are used by the test suite.
1758 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1760 FLAC__ASSERT(0 != encoder);
1761 FLAC__ASSERT(0 != encoder->private_);
1762 FLAC__ASSERT(0 != encoder->protected_);
1763 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1765 encoder->private_->disable_constant_subframes = value;
1769 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1771 FLAC__ASSERT(0 != encoder);
1772 FLAC__ASSERT(0 != encoder->private_);
1773 FLAC__ASSERT(0 != encoder->protected_);
1774 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1776 encoder->private_->disable_fixed_subframes = value;
1780 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1782 FLAC__ASSERT(0 != encoder);
1783 FLAC__ASSERT(0 != encoder->private_);
1784 FLAC__ASSERT(0 != encoder->protected_);
1785 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1787 encoder->private_->disable_verbatim_subframes = value;
1791 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1793 FLAC__ASSERT(0 != encoder);
1794 FLAC__ASSERT(0 != encoder->private_);
1795 FLAC__ASSERT(0 != encoder->protected_);
1796 return encoder->protected_->state;
1799 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1801 FLAC__ASSERT(0 != encoder);
1802 FLAC__ASSERT(0 != encoder->private_);
1803 FLAC__ASSERT(0 != encoder->protected_);
1804 if(encoder->protected_->verify)
1805 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1807 return FLAC__STREAM_DECODER_UNINITIALIZED;
1810 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1812 FLAC__ASSERT(0 != encoder);
1813 FLAC__ASSERT(0 != encoder->private_);
1814 FLAC__ASSERT(0 != encoder->protected_);
1815 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1816 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1818 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1821 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)
1823 FLAC__ASSERT(0 != encoder);
1824 FLAC__ASSERT(0 != encoder->private_);
1825 FLAC__ASSERT(0 != encoder->protected_);
1826 if(0 != absolute_sample)
1827 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1828 if(0 != frame_number)
1829 *frame_number = encoder->private_->verify.error_stats.frame_number;
1831 *channel = encoder->private_->verify.error_stats.channel;
1833 *sample = encoder->private_->verify.error_stats.sample;
1835 *expected = encoder->private_->verify.error_stats.expected;
1837 *got = encoder->private_->verify.error_stats.got;
1840 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1842 FLAC__ASSERT(0 != encoder);
1843 FLAC__ASSERT(0 != encoder->private_);
1844 FLAC__ASSERT(0 != encoder->protected_);
1845 return encoder->protected_->verify;
1848 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1850 FLAC__ASSERT(0 != encoder);
1851 FLAC__ASSERT(0 != encoder->private_);
1852 FLAC__ASSERT(0 != encoder->protected_);
1853 return encoder->protected_->streamable_subset;
1856 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
1858 FLAC__ASSERT(0 != encoder);
1859 FLAC__ASSERT(0 != encoder->private_);
1860 FLAC__ASSERT(0 != encoder->protected_);
1861 return encoder->protected_->do_md5;
1864 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1866 FLAC__ASSERT(0 != encoder);
1867 FLAC__ASSERT(0 != encoder->private_);
1868 FLAC__ASSERT(0 != encoder->protected_);
1869 return encoder->protected_->channels;
1872 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1874 FLAC__ASSERT(0 != encoder);
1875 FLAC__ASSERT(0 != encoder->private_);
1876 FLAC__ASSERT(0 != encoder->protected_);
1877 return encoder->protected_->bits_per_sample;
1880 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1882 FLAC__ASSERT(0 != encoder);
1883 FLAC__ASSERT(0 != encoder->private_);
1884 FLAC__ASSERT(0 != encoder->protected_);
1885 return encoder->protected_->sample_rate;
1888 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1890 FLAC__ASSERT(0 != encoder);
1891 FLAC__ASSERT(0 != encoder->private_);
1892 FLAC__ASSERT(0 != encoder->protected_);
1893 return encoder->protected_->blocksize;
1896 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1898 FLAC__ASSERT(0 != encoder);
1899 FLAC__ASSERT(0 != encoder->private_);
1900 FLAC__ASSERT(0 != encoder->protected_);
1901 return encoder->protected_->do_mid_side_stereo;
1904 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1906 FLAC__ASSERT(0 != encoder);
1907 FLAC__ASSERT(0 != encoder->private_);
1908 FLAC__ASSERT(0 != encoder->protected_);
1909 return encoder->protected_->loose_mid_side_stereo;
1912 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1914 FLAC__ASSERT(0 != encoder);
1915 FLAC__ASSERT(0 != encoder->private_);
1916 FLAC__ASSERT(0 != encoder->protected_);
1917 return encoder->protected_->max_lpc_order;
1920 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1922 FLAC__ASSERT(0 != encoder);
1923 FLAC__ASSERT(0 != encoder->private_);
1924 FLAC__ASSERT(0 != encoder->protected_);
1925 return encoder->protected_->qlp_coeff_precision;
1928 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1930 FLAC__ASSERT(0 != encoder);
1931 FLAC__ASSERT(0 != encoder->private_);
1932 FLAC__ASSERT(0 != encoder->protected_);
1933 return encoder->protected_->do_qlp_coeff_prec_search;
1936 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1938 FLAC__ASSERT(0 != encoder);
1939 FLAC__ASSERT(0 != encoder->private_);
1940 FLAC__ASSERT(0 != encoder->protected_);
1941 return encoder->protected_->do_escape_coding;
1944 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1946 FLAC__ASSERT(0 != encoder);
1947 FLAC__ASSERT(0 != encoder->private_);
1948 FLAC__ASSERT(0 != encoder->protected_);
1949 return encoder->protected_->do_exhaustive_model_search;
1952 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1954 FLAC__ASSERT(0 != encoder);
1955 FLAC__ASSERT(0 != encoder->private_);
1956 FLAC__ASSERT(0 != encoder->protected_);
1957 return encoder->protected_->min_residual_partition_order;
1960 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1962 FLAC__ASSERT(0 != encoder);
1963 FLAC__ASSERT(0 != encoder->private_);
1964 FLAC__ASSERT(0 != encoder->protected_);
1965 return encoder->protected_->max_residual_partition_order;
1968 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1970 FLAC__ASSERT(0 != encoder);
1971 FLAC__ASSERT(0 != encoder->private_);
1972 FLAC__ASSERT(0 != encoder->protected_);
1973 return encoder->protected_->rice_parameter_search_dist;
1976 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1978 FLAC__ASSERT(0 != encoder);
1979 FLAC__ASSERT(0 != encoder->private_);
1980 FLAC__ASSERT(0 != encoder->protected_);
1981 return encoder->protected_->total_samples_estimate;
1984 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1986 unsigned i, j = 0, channel;
1987 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1989 FLAC__ASSERT(0 != encoder);
1990 FLAC__ASSERT(0 != encoder->private_);
1991 FLAC__ASSERT(0 != encoder->protected_);
1992 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1995 const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
1997 if(encoder->protected_->verify)
1998 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
2000 for(channel = 0; channel < channels; channel++)
2001 memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
2003 if(encoder->protected_->do_mid_side_stereo) {
2004 FLAC__ASSERT(channels == 2);
2005 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2006 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2007 encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
2008 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' ! */
2014 encoder->private_->current_sample_number += n;
2016 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2017 if(encoder->private_->current_sample_number > blocksize) {
2018 FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
2019 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2020 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2022 /* move unprocessed overread samples to beginnings of arrays */
2023 for(channel = 0; channel < channels; channel++)
2024 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2025 if(encoder->protected_->do_mid_side_stereo) {
2026 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2027 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2029 encoder->private_->current_sample_number = 1;
2031 } while(j < samples);
2036 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2038 unsigned i, j, k, channel;
2039 FLAC__int32 x, mid, side;
2040 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2042 FLAC__ASSERT(0 != encoder);
2043 FLAC__ASSERT(0 != encoder->private_);
2044 FLAC__ASSERT(0 != encoder->protected_);
2045 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2049 * we have several flavors of the same basic loop, optimized for
2050 * different conditions:
2052 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2054 * stereo coding: unroll channel loop
2057 if(encoder->protected_->verify)
2058 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2060 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2061 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2062 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2064 encoder->private_->integer_signal[1][i] = x;
2067 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2068 encoder->private_->integer_signal_mid_side[1][i] = side;
2069 encoder->private_->integer_signal_mid_side[0][i] = mid;
2071 encoder->private_->current_sample_number = i;
2072 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2074 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2076 /* move unprocessed overread samples to beginnings of arrays */
2077 FLAC__ASSERT(i == blocksize+OVERREAD_);
2078 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2079 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
2080 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
2081 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2082 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2083 encoder->private_->current_sample_number = 1;
2085 } while(j < samples);
2089 * independent channel coding: buffer each channel in inner loop
2092 if(encoder->protected_->verify)
2093 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2095 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2096 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2097 for(channel = 0; channel < channels; channel++)
2098 encoder->private_->integer_signal[channel][i] = buffer[k++];
2100 encoder->private_->current_sample_number = i;
2101 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2103 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2105 /* move unprocessed overread samples to beginnings of arrays */
2106 FLAC__ASSERT(i == blocksize+OVERREAD_);
2107 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2108 for(channel = 0; channel < channels; channel++)
2109 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2110 encoder->private_->current_sample_number = 1;
2112 } while(j < samples);
2118 /***********************************************************************
2120 * Private class methods
2122 ***********************************************************************/
2124 void set_defaults_(FLAC__StreamEncoder *encoder)
2126 FLAC__ASSERT(0 != encoder);
2128 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2129 encoder->protected_->verify = true;
2131 encoder->protected_->verify = false;
2133 encoder->protected_->streamable_subset = true;
2134 encoder->protected_->do_md5 = true;
2135 encoder->protected_->do_mid_side_stereo = false;
2136 encoder->protected_->loose_mid_side_stereo = false;
2137 encoder->protected_->channels = 2;
2138 encoder->protected_->bits_per_sample = 16;
2139 encoder->protected_->sample_rate = 44100;
2140 encoder->protected_->blocksize = 0;
2141 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2142 encoder->protected_->num_apodizations = 1;
2143 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2144 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2146 encoder->protected_->max_lpc_order = 0;
2147 encoder->protected_->qlp_coeff_precision = 0;
2148 encoder->protected_->do_qlp_coeff_prec_search = false;
2149 encoder->protected_->do_exhaustive_model_search = false;
2150 encoder->protected_->do_escape_coding = false;
2151 encoder->protected_->min_residual_partition_order = 0;
2152 encoder->protected_->max_residual_partition_order = 0;
2153 encoder->protected_->rice_parameter_search_dist = 0;
2154 encoder->protected_->total_samples_estimate = 0;
2155 encoder->protected_->metadata = 0;
2156 encoder->protected_->num_metadata_blocks = 0;
2158 encoder->private_->seek_table = 0;
2159 encoder->private_->disable_constant_subframes = false;
2160 encoder->private_->disable_fixed_subframes = false;
2161 encoder->private_->disable_verbatim_subframes = false;
2163 encoder->private_->is_ogg = false;
2165 encoder->private_->read_callback = 0;
2166 encoder->private_->write_callback = 0;
2167 encoder->private_->seek_callback = 0;
2168 encoder->private_->tell_callback = 0;
2169 encoder->private_->metadata_callback = 0;
2170 encoder->private_->progress_callback = 0;
2171 encoder->private_->client_data = 0;
2174 FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2178 void free_(FLAC__StreamEncoder *encoder)
2180 unsigned i, channel;
2182 FLAC__ASSERT(0 != encoder);
2183 if(encoder->protected_->metadata) {
2184 free(encoder->protected_->metadata);
2185 encoder->protected_->metadata = 0;
2186 encoder->protected_->num_metadata_blocks = 0;
2188 for(i = 0; i < encoder->protected_->channels; i++) {
2189 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2190 free(encoder->private_->integer_signal_unaligned[i]);
2191 encoder->private_->integer_signal_unaligned[i] = 0;
2193 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2194 if(0 != encoder->private_->real_signal_unaligned[i]) {
2195 free(encoder->private_->real_signal_unaligned[i]);
2196 encoder->private_->real_signal_unaligned[i] = 0;
2200 for(i = 0; i < 2; i++) {
2201 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2202 free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2203 encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2205 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2206 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2207 free(encoder->private_->real_signal_mid_side_unaligned[i]);
2208 encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2212 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2213 for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2214 if(0 != encoder->private_->window_unaligned[i]) {
2215 free(encoder->private_->window_unaligned[i]);
2216 encoder->private_->window_unaligned[i] = 0;
2219 if(0 != encoder->private_->windowed_signal_unaligned) {
2220 free(encoder->private_->windowed_signal_unaligned);
2221 encoder->private_->windowed_signal_unaligned = 0;
2224 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2225 for(i = 0; i < 2; i++) {
2226 if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2227 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2228 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2232 for(channel = 0; channel < 2; channel++) {
2233 for(i = 0; i < 2; i++) {
2234 if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2235 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2236 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2240 if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2241 free(encoder->private_->abs_residual_partition_sums_unaligned);
2242 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2244 if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2245 free(encoder->private_->raw_bits_per_partition_unaligned);
2246 encoder->private_->raw_bits_per_partition_unaligned = 0;
2248 if(encoder->protected_->verify) {
2249 for(i = 0; i < encoder->protected_->channels; i++) {
2250 if(0 != encoder->private_->verify.input_fifo.data[i]) {
2251 free(encoder->private_->verify.input_fifo.data[i]);
2252 encoder->private_->verify.input_fifo.data[i] = 0;
2256 FLAC__bitwriter_free(encoder->private_->frame);
2259 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2262 unsigned i, channel;
2264 FLAC__ASSERT(new_blocksize > 0);
2265 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2266 FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2268 /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2269 if(new_blocksize <= encoder->private_->input_capacity)
2274 /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
2275 * requires that the input arrays (in our case the integer signals)
2276 * have a buffer of up to 3 zeroes in front (at negative indices) for
2277 * alignment purposes; we use 4 in front to keep the data well-aligned.
2280 for(i = 0; ok && i < encoder->protected_->channels; i++) {
2281 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2282 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2283 encoder->private_->integer_signal[i] += 4;
2284 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2285 #if 0 /* @@@ currently unused */
2286 if(encoder->protected_->max_lpc_order > 0)
2287 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2291 for(i = 0; ok && i < 2; i++) {
2292 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]);
2293 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2294 encoder->private_->integer_signal_mid_side[i] += 4;
2295 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2296 #if 0 /* @@@ currently unused */
2297 if(encoder->protected_->max_lpc_order > 0)
2298 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]);
2302 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2303 if(ok && encoder->protected_->max_lpc_order > 0) {
2304 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2305 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2306 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2309 for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2310 for(i = 0; ok && i < 2; i++) {
2311 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2314 for(channel = 0; ok && channel < 2; channel++) {
2315 for(i = 0; ok && i < 2; i++) {
2316 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]);
2319 /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2320 /*@@@ 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) */
2321 ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2322 if(encoder->protected_->do_escape_coding)
2323 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2325 /* now adjust the windows if the blocksize has changed */
2326 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2327 if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2328 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2329 switch(encoder->protected_->apodizations[i].type) {
2330 case FLAC__APODIZATION_BARTLETT:
2331 FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2333 case FLAC__APODIZATION_BARTLETT_HANN:
2334 FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2336 case FLAC__APODIZATION_BLACKMAN:
2337 FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2339 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2340 FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2342 case FLAC__APODIZATION_CONNES:
2343 FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2345 case FLAC__APODIZATION_FLATTOP:
2346 FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2348 case FLAC__APODIZATION_GAUSS:
2349 FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2351 case FLAC__APODIZATION_HAMMING:
2352 FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2354 case FLAC__APODIZATION_HANN:
2355 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2357 case FLAC__APODIZATION_KAISER_BESSEL:
2358 FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2360 case FLAC__APODIZATION_NUTTALL:
2361 FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2363 case FLAC__APODIZATION_RECTANGLE:
2364 FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2366 case FLAC__APODIZATION_TRIANGLE:
2367 FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2369 case FLAC__APODIZATION_TUKEY:
2370 FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2372 case FLAC__APODIZATION_WELCH:
2373 FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2377 /* double protection */
2378 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2386 encoder->private_->input_capacity = new_blocksize;
2388 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2393 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2395 const FLAC__byte *buffer;
2398 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2400 if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2401 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2405 if(encoder->protected_->verify) {
2406 encoder->private_->verify.output.data = buffer;
2407 encoder->private_->verify.output.bytes = bytes;
2408 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2409 encoder->private_->verify.needs_magic_hack = true;
2412 if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2413 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2414 FLAC__bitwriter_clear(encoder->private_->frame);
2415 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2416 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2422 if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2423 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2424 FLAC__bitwriter_clear(encoder->private_->frame);
2425 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2429 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2430 FLAC__bitwriter_clear(encoder->private_->frame);
2433 encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2434 encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2440 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2442 FLAC__StreamEncoderWriteStatus status;
2443 FLAC__uint64 output_position = 0;
2445 /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2446 if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2447 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2448 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2452 * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2455 FLAC__MetadataType type = (buffer[0] & 0x7f);
2456 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2457 encoder->protected_->streaminfo_offset = output_position;
2458 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2459 encoder->protected_->seektable_offset = output_position;
2463 * Mark the current seek point if hit (if audio_offset == 0 that
2464 * means we're still writing metadata and haven't hit the first
2467 if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2468 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2469 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2470 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2471 FLAC__uint64 test_sample;
2473 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2474 test_sample = encoder->private_->seek_table->points[i].sample_number;
2475 if(test_sample > frame_last_sample) {
2478 else if(test_sample >= frame_first_sample) {
2479 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2480 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2481 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2482 encoder->private_->first_seekpoint_to_check++;
2483 /* DO NOT: "break;" and here's why:
2484 * The seektable template may contain more than one target
2485 * sample for any given frame; we will keep looping, generating
2486 * duplicate seekpoints for them, and we'll clean it up later,
2487 * just before writing the seektable back to the metadata.
2491 encoder->private_->first_seekpoint_to_check++;
2497 if(encoder->private_->is_ogg) {
2498 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2499 &encoder->protected_->ogg_encoder_aspect,
2503 encoder->private_->current_frame_number,
2505 (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2507 encoder->private_->client_data
2512 status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2514 if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2515 encoder->private_->bytes_written += bytes;
2516 encoder->private_->samples_written += samples;
2517 /* we keep a high watermark on the number of frames written because
2518 * when the encoder goes back to write metadata, 'current_frame'
2519 * will drop back to 0.
2521 encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2524 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2529 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2530 void update_metadata_(const FLAC__StreamEncoder *encoder)
2532 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2533 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2534 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2535 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2536 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2537 const unsigned bps = metadata->data.stream_info.bits_per_sample;
2538 FLAC__StreamEncoderSeekStatus seek_status;
2540 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2542 /* All this is based on intimate knowledge of the stream header
2543 * layout, but a change to the header format that would break this
2544 * would also break all streams encoded in the previous format.
2548 * Write MD5 signature
2551 const unsigned md5_offset =
2552 FLAC__STREAM_METADATA_HEADER_LENGTH +
2554 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2555 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2556 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2557 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2558 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2559 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2560 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2561 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2564 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2565 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2566 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2569 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2570 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2576 * Write total samples
2579 const unsigned total_samples_byte_offset =
2580 FLAC__STREAM_METADATA_HEADER_LENGTH +
2582 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2583 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2584 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2585 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2586 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2587 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2588 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2592 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2593 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2594 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2595 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2596 b[4] = (FLAC__byte)(samples & 0xFF);
2597 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) {
2598 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2599 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2602 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2603 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2609 * Write min/max framesize
2612 const unsigned min_framesize_offset =
2613 FLAC__STREAM_METADATA_HEADER_LENGTH +
2615 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2616 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2619 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2620 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2621 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2622 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2623 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2624 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2625 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) {
2626 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2627 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2630 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2631 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2639 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2642 FLAC__format_seektable_sort(encoder->private_->seek_table);
2644 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2646 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) {
2647 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2648 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2652 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2655 xx = encoder->private_->seek_table->points[i].sample_number;
2656 b[7] = (FLAC__byte)xx; xx >>= 8;
2657 b[6] = (FLAC__byte)xx; xx >>= 8;
2658 b[5] = (FLAC__byte)xx; xx >>= 8;
2659 b[4] = (FLAC__byte)xx; xx >>= 8;
2660 b[3] = (FLAC__byte)xx; xx >>= 8;
2661 b[2] = (FLAC__byte)xx; xx >>= 8;
2662 b[1] = (FLAC__byte)xx; xx >>= 8;
2663 b[0] = (FLAC__byte)xx; xx >>= 8;
2664 xx = encoder->private_->seek_table->points[i].stream_offset;
2665 b[15] = (FLAC__byte)xx; xx >>= 8;
2666 b[14] = (FLAC__byte)xx; xx >>= 8;
2667 b[13] = (FLAC__byte)xx; xx >>= 8;
2668 b[12] = (FLAC__byte)xx; xx >>= 8;
2669 b[11] = (FLAC__byte)xx; xx >>= 8;
2670 b[10] = (FLAC__byte)xx; xx >>= 8;
2671 b[9] = (FLAC__byte)xx; xx >>= 8;
2672 b[8] = (FLAC__byte)xx; xx >>= 8;
2673 x = encoder->private_->seek_table->points[i].frame_samples;
2674 b[17] = (FLAC__byte)x; x >>= 8;
2675 b[16] = (FLAC__byte)x; x >>= 8;
2676 if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2677 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2685 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2686 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2688 /* the # of bytes in the 1st packet that precede the STREAMINFO */
2689 static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2690 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2691 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2692 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2693 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2694 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2695 FLAC__STREAM_SYNC_LENGTH
2697 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2698 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2699 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2700 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2701 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2704 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2705 FLAC__ASSERT(0 != encoder->private_->seek_callback);
2707 /* Pre-check that client supports seeking, since we don't want the
2708 * ogg_helper code to ever have to deal with this condition.
2710 if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2713 /* All this is based on intimate knowledge of the stream header
2714 * layout, but a change to the header format that would break this
2715 * would also break all streams encoded in the previous format.
2719 ** Write STREAMINFO stats
2721 simple_ogg_page__init(&page);
2722 if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2723 simple_ogg_page__clear(&page);
2724 return; /* state already set */
2728 * Write MD5 signature
2731 const unsigned md5_offset =
2732 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2733 FLAC__STREAM_METADATA_HEADER_LENGTH +
2735 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2736 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2737 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2738 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2739 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2740 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2741 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2742 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2745 if(md5_offset + 16 > (unsigned)page.body_len) {
2746 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2747 simple_ogg_page__clear(&page);
2750 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2754 * Write total samples
2757 const unsigned total_samples_byte_offset =
2758 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2759 FLAC__STREAM_METADATA_HEADER_LENGTH +
2761 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2762 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2763 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2764 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2765 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2766 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2767 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2771 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2772 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2773 simple_ogg_page__clear(&page);
2776 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2777 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2778 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2779 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2780 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2781 b[4] = (FLAC__byte)(samples & 0xFF);
2782 memcpy(page.body + total_samples_byte_offset, b, 5);
2786 * Write min/max framesize
2789 const unsigned min_framesize_offset =
2790 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2791 FLAC__STREAM_METADATA_HEADER_LENGTH +
2793 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2794 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2797 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2798 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2799 simple_ogg_page__clear(&page);
2802 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2803 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2804 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2805 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2806 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2807 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2808 memcpy(page.body + min_framesize_offset, b, 6);
2810 if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2811 simple_ogg_page__clear(&page);
2812 return; /* state already set */
2814 simple_ogg_page__clear(&page);
2819 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2823 FLAC__format_seektable_sort(encoder->private_->seek_table);
2825 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2827 simple_ogg_page__init(&page);
2828 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2829 simple_ogg_page__clear(&page);
2830 return; /* state already set */
2833 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
2834 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2835 simple_ogg_page__clear(&page);
2839 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
2842 xx = encoder->private_->seek_table->points[i].sample_number;
2843 b[7] = (FLAC__byte)xx; xx >>= 8;
2844 b[6] = (FLAC__byte)xx; xx >>= 8;
2845 b[5] = (FLAC__byte)xx; xx >>= 8;
2846 b[4] = (FLAC__byte)xx; xx >>= 8;
2847 b[3] = (FLAC__byte)xx; xx >>= 8;
2848 b[2] = (FLAC__byte)xx; xx >>= 8;
2849 b[1] = (FLAC__byte)xx; xx >>= 8;
2850 b[0] = (FLAC__byte)xx; xx >>= 8;
2851 xx = encoder->private_->seek_table->points[i].stream_offset;
2852 b[15] = (FLAC__byte)xx; xx >>= 8;
2853 b[14] = (FLAC__byte)xx; xx >>= 8;
2854 b[13] = (FLAC__byte)xx; xx >>= 8;
2855 b[12] = (FLAC__byte)xx; xx >>= 8;
2856 b[11] = (FLAC__byte)xx; xx >>= 8;
2857 b[10] = (FLAC__byte)xx; xx >>= 8;
2858 b[9] = (FLAC__byte)xx; xx >>= 8;
2859 b[8] = (FLAC__byte)xx; xx >>= 8;
2860 x = encoder->private_->seek_table->points[i].frame_samples;
2861 b[17] = (FLAC__byte)x; x >>= 8;
2862 b[16] = (FLAC__byte)x; x >>= 8;
2866 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2867 simple_ogg_page__clear(&page);
2868 return; /* state already set */
2870 simple_ogg_page__clear(&page);
2875 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
2878 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2881 * Accumulate raw signal to the MD5 signature
2883 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)) {
2884 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2889 * Process the frame header and subframes into the frame bitbuffer
2891 if(!process_subframes_(encoder, is_fractional_block)) {
2892 /* the above function sets the state for us in case of an error */
2897 * Zero-pad the frame to a byte_boundary
2899 if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
2900 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2905 * CRC-16 the whole thing
2907 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2909 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
2910 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
2912 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2919 if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
2920 /* the above function sets the state for us in case of an error */
2925 * Get ready for the next frame
2927 encoder->private_->current_sample_number = 0;
2928 encoder->private_->current_frame_number++;
2929 encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
2934 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
2936 FLAC__FrameHeader frame_header;
2937 unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
2938 FLAC__bool do_independent, do_mid_side;
2941 * Calculate the min,max Rice partition orders
2943 if(is_fractional_block) {
2944 max_partition_order = 0;
2947 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
2948 max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
2950 min_partition_order = min(min_partition_order, max_partition_order);
2955 frame_header.blocksize = encoder->protected_->blocksize;
2956 frame_header.sample_rate = encoder->protected_->sample_rate;
2957 frame_header.channels = encoder->protected_->channels;
2958 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
2959 frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
2960 frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2961 frame_header.number.frame_number = encoder->private_->current_frame_number;
2964 * Figure out what channel assignments to try
2966 if(encoder->protected_->do_mid_side_stereo) {
2967 if(encoder->protected_->loose_mid_side_stereo) {
2968 if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
2969 do_independent = true;
2973 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
2974 do_mid_side = !do_independent;
2978 do_independent = true;
2983 do_independent = true;
2984 do_mid_side = false;
2987 FLAC__ASSERT(do_independent || do_mid_side);
2990 * Check for wasted bits; set effective bps for each subframe
2992 if(do_independent) {
2993 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2994 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
2995 encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
2996 encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
3000 FLAC__ASSERT(encoder->protected_->channels == 2);
3001 for(channel = 0; channel < 2; channel++) {
3002 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
3003 encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
3004 encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
3009 * First do a normal encoding pass of each independent channel
3011 if(do_independent) {
3012 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3016 min_partition_order,
3017 max_partition_order,
3019 encoder->private_->subframe_bps[channel],
3020 encoder->private_->integer_signal[channel],
3021 encoder->private_->subframe_workspace_ptr[channel],
3022 encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3023 encoder->private_->residual_workspace[channel],
3024 encoder->private_->best_subframe+channel,
3025 encoder->private_->best_subframe_bits+channel
3033 * Now do mid and side channels if requested
3036 FLAC__ASSERT(encoder->protected_->channels == 2);
3038 for(channel = 0; channel < 2; channel++) {
3042 min_partition_order,
3043 max_partition_order,
3045 encoder->private_->subframe_bps_mid_side[channel],
3046 encoder->private_->integer_signal_mid_side[channel],
3047 encoder->private_->subframe_workspace_ptr_mid_side[channel],
3048 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3049 encoder->private_->residual_workspace_mid_side[channel],
3050 encoder->private_->best_subframe_mid_side+channel,
3051 encoder->private_->best_subframe_bits_mid_side+channel
3059 * Compose the frame bitbuffer
3062 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3063 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3064 FLAC__ChannelAssignment channel_assignment;
3066 FLAC__ASSERT(encoder->protected_->channels == 2);
3068 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3069 channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3072 unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3076 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3077 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
3078 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
3079 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
3080 FLAC__ASSERT(do_independent && do_mid_side);
3082 /* We have to figure out which channel assignent results in the smallest frame */
3083 bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
3084 bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
3085 bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
3086 bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3088 channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3089 min_bits = bits[channel_assignment];
3090 for(ca = 1; ca <= 3; ca++) {
3091 if(bits[ca] < min_bits) {
3092 min_bits = bits[ca];
3093 channel_assignment = (FLAC__ChannelAssignment)ca;
3098 frame_header.channel_assignment = channel_assignment;
3100 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3101 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3105 switch(channel_assignment) {
3106 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3107 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3108 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3110 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3111 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3112 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3114 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3115 left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3116 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3118 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3119 left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3120 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3126 switch(channel_assignment) {
3127 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3128 left_bps = encoder->private_->subframe_bps [0];
3129 right_bps = encoder->private_->subframe_bps [1];
3131 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3132 left_bps = encoder->private_->subframe_bps [0];
3133 right_bps = encoder->private_->subframe_bps_mid_side[1];
3135 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3136 left_bps = encoder->private_->subframe_bps_mid_side[1];
3137 right_bps = encoder->private_->subframe_bps [1];
3139 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3140 left_bps = encoder->private_->subframe_bps_mid_side[0];
3141 right_bps = encoder->private_->subframe_bps_mid_side[1];
3147 /* note that encoder_add_subframe_ sets the state for us in case of an error */
3148 if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3150 if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3154 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3155 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3159 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3160 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)) {
3161 /* the above function sets the state for us in case of an error */
3167 if(encoder->protected_->loose_mid_side_stereo) {
3168 encoder->private_->loose_mid_side_stereo_frame_count++;
3169 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3170 encoder->private_->loose_mid_side_stereo_frame_count = 0;
3173 encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3178 FLAC__bool process_subframe_(
3179 FLAC__StreamEncoder *encoder,
3180 unsigned min_partition_order,
3181 unsigned max_partition_order,
3182 const FLAC__FrameHeader *frame_header,
3183 unsigned subframe_bps,
3184 const FLAC__int32 integer_signal[],
3185 FLAC__Subframe *subframe[2],
3186 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3187 FLAC__int32 *residual[2],
3188 unsigned *best_subframe,
3192 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3193 FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3195 FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3197 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3198 FLAC__double lpc_residual_bits_per_sample;
3199 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 */
3200 FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3201 unsigned min_lpc_order, max_lpc_order, lpc_order;
3202 unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3204 unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3205 unsigned rice_parameter;
3206 unsigned _candidate_bits, _best_bits;
3207 unsigned _best_subframe;
3208 /* only use RICE2 partitions if stream bps > 16 */
3209 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;
3211 FLAC__ASSERT(frame_header->blocksize > 0);
3213 /* verbatim subframe is the baseline against which we measure other compressed subframes */
3215 if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3216 _best_bits = UINT_MAX;
3218 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3220 if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3221 unsigned signal_is_constant = false;
3222 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);
3223 /* check for constant subframe */
3225 !encoder->private_->disable_constant_subframes &&
3226 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3227 fixed_residual_bits_per_sample[1] == 0.0
3229 fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3232 /* the above means it's possible all samples are the same value; now double-check it: */
3234 signal_is_constant = true;
3235 for(i = 1; i < frame_header->blocksize; i++) {
3236 if(integer_signal[0] != integer_signal[i]) {
3237 signal_is_constant = false;
3242 if(signal_is_constant) {
3243 _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3244 if(_candidate_bits < _best_bits) {
3245 _best_subframe = !_best_subframe;
3246 _best_bits = _candidate_bits;
3250 if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3252 if(encoder->protected_->do_exhaustive_model_search) {
3253 min_fixed_order = 0;
3254 max_fixed_order = FLAC__MAX_FIXED_ORDER;
3257 min_fixed_order = max_fixed_order = guess_fixed_order;
3259 if(max_fixed_order >= frame_header->blocksize)
3260 max_fixed_order = frame_header->blocksize - 1;
3261 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3262 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3263 if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3264 continue; /* don't even try */
3265 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 */
3267 if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3268 continue; /* don't even try */
3269 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 */
3271 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3272 if(rice_parameter >= rice_parameter_limit) {
3273 #ifdef DEBUG_VERBOSE
3274 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
3276 rice_parameter = rice_parameter_limit - 1;
3279 evaluate_fixed_subframe_(
3282 residual[!_best_subframe],
3283 encoder->private_->abs_residual_partition_sums,
3284 encoder->private_->raw_bits_per_partition,
3285 frame_header->blocksize,
3289 rice_parameter_limit,
3290 min_partition_order,
3291 max_partition_order,
3292 encoder->protected_->do_escape_coding,
3293 encoder->protected_->rice_parameter_search_dist,
3294 subframe[!_best_subframe],
3295 partitioned_rice_contents[!_best_subframe]
3297 if(_candidate_bits < _best_bits) {
3298 _best_subframe = !_best_subframe;
3299 _best_bits = _candidate_bits;
3304 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3306 if(encoder->protected_->max_lpc_order > 0) {
3307 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3308 max_lpc_order = frame_header->blocksize-1;
3310 max_lpc_order = encoder->protected_->max_lpc_order;
3311 if(max_lpc_order > 0) {
3313 for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3314 FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3315 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3316 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3317 if(autoc[0] != 0.0) {
3318 FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3319 if(encoder->protected_->do_exhaustive_model_search) {
3323 const unsigned guess_lpc_order =
3324 FLAC__lpc_compute_best_order(
3327 frame_header->blocksize,
3329 encoder->protected_->do_qlp_coeff_prec_search?
3330 FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
3331 encoder->protected_->qlp_coeff_precision
3334 min_lpc_order = max_lpc_order = guess_lpc_order;
3336 if(max_lpc_order >= frame_header->blocksize)
3337 max_lpc_order = frame_header->blocksize - 1;
3338 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
3339 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
3340 if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
3341 continue; /* don't even try */
3342 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
3343 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3344 if(rice_parameter >= rice_parameter_limit) {
3345 #ifdef DEBUG_VERBOSE
3346 fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
3348 rice_parameter = rice_parameter_limit - 1;
3350 if(encoder->protected_->do_qlp_coeff_prec_search) {
3351 min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
3352 /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
3353 if(subframe_bps <= 17) {
3354 max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
3355 max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
3358 max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
3361 min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
3363 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
3365 evaluate_lpc_subframe_(
3368 residual[!_best_subframe],
3369 encoder->private_->abs_residual_partition_sums,
3370 encoder->private_->raw_bits_per_partition,
3371 encoder->private_->lp_coeff[lpc_order-1],
3372 frame_header->blocksize,
3375 qlp_coeff_precision,
3377 rice_parameter_limit,
3378 min_partition_order,
3379 max_partition_order,
3380 encoder->protected_->do_escape_coding,
3381 encoder->protected_->rice_parameter_search_dist,
3382 subframe[!_best_subframe],
3383 partitioned_rice_contents[!_best_subframe]
3385 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
3386 if(_candidate_bits < _best_bits) {
3387 _best_subframe = !_best_subframe;
3388 _best_bits = _candidate_bits;
3397 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3401 /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3402 if(_best_bits == UINT_MAX) {
3403 FLAC__ASSERT(_best_subframe == 0);
3404 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3407 *best_subframe = _best_subframe;
3408 *best_bits = _best_bits;
3413 FLAC__bool add_subframe_(
3414 FLAC__StreamEncoder *encoder,
3416 unsigned subframe_bps,
3417 const FLAC__Subframe *subframe,
3418 FLAC__BitWriter *frame
3421 switch(subframe->type) {
3422 case FLAC__SUBFRAME_TYPE_CONSTANT:
3423 if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3424 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3428 case FLAC__SUBFRAME_TYPE_FIXED:
3429 if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3430 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3434 case FLAC__SUBFRAME_TYPE_LPC:
3435 if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3436 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3440 case FLAC__SUBFRAME_TYPE_VERBATIM:
3441 if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3442 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3453 #define SPOTCHECK_ESTIMATE 0
3454 #if SPOTCHECK_ESTIMATE
3455 static void spotcheck_subframe_estimate_(
3456 FLAC__StreamEncoder *encoder,
3458 unsigned subframe_bps,
3459 const FLAC__Subframe *subframe,
3464 FLAC__BitWriter *frame = FLAC__bitwriter_new();
3466 fprintf(stderr, "EST: can't allocate frame\n");
3469 if(!FLAC__bitwriter_init(frame)) {
3470 fprintf(stderr, "EST: can't init frame\n");
3473 ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
3476 const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
3477 if(estimate != actual)
3478 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);
3480 FLAC__bitwriter_delete(frame);
3484 unsigned evaluate_constant_subframe_(
3485 FLAC__StreamEncoder *encoder,
3486 const FLAC__int32 signal,
3488 unsigned subframe_bps,
3489 FLAC__Subframe *subframe
3493 subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3494 subframe->data.constant.value = signal;
3496 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
3498 #if SPOTCHECK_ESTIMATE
3499 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3501 (void)encoder, (void)blocksize;
3507 unsigned evaluate_fixed_subframe_(
3508 FLAC__StreamEncoder *encoder,
3509 const FLAC__int32 signal[],
3510 FLAC__int32 residual[],
3511 FLAC__uint64 abs_residual_partition_sums[],
3512 unsigned raw_bits_per_partition[],
3514 unsigned subframe_bps,
3516 unsigned rice_parameter,
3517 unsigned rice_parameter_limit,
3518 unsigned min_partition_order,
3519 unsigned max_partition_order,
3520 FLAC__bool do_escape_coding,
3521 unsigned rice_parameter_search_dist,
3522 FLAC__Subframe *subframe,
3523 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3526 unsigned i, residual_bits, estimate;
3527 const unsigned residual_samples = blocksize - order;
3529 FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3531 subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3533 subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3534 subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3535 subframe->data.fixed.residual = residual;
3538 find_best_partition_order_(
3541 abs_residual_partition_sums,
3542 raw_bits_per_partition,
3546 rice_parameter_limit,
3547 min_partition_order,
3548 max_partition_order,
3551 rice_parameter_search_dist,
3552 &subframe->data.fixed.entropy_coding_method
3555 subframe->data.fixed.order = order;
3556 for(i = 0; i < order; i++)
3557 subframe->data.fixed.warmup[i] = signal[i];
3559 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
3561 #if SPOTCHECK_ESTIMATE
3562 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3568 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3569 unsigned evaluate_lpc_subframe_(
3570 FLAC__StreamEncoder *encoder,
3571 const FLAC__int32 signal[],
3572 FLAC__int32 residual[],
3573 FLAC__uint64 abs_residual_partition_sums[],
3574 unsigned raw_bits_per_partition[],
3575 const FLAC__real lp_coeff[],
3577 unsigned subframe_bps,
3579 unsigned qlp_coeff_precision,
3580 unsigned rice_parameter,
3581 unsigned rice_parameter_limit,
3582 unsigned min_partition_order,
3583 unsigned max_partition_order,
3584 FLAC__bool do_escape_coding,
3585 unsigned rice_parameter_search_dist,
3586 FLAC__Subframe *subframe,
3587 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3590 FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
3591 unsigned i, residual_bits, estimate;
3592 int quantization, ret;
3593 const unsigned residual_samples = blocksize - order;
3595 /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3596 if(subframe_bps <= 16) {
3597 FLAC__ASSERT(order > 0);
3598 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3599 qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3602 ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3604 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3606 if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3607 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3608 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3610 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3612 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3614 subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3616 subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3617 subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3618 subframe->data.lpc.residual = residual;
3621 find_best_partition_order_(
3624 abs_residual_partition_sums,
3625 raw_bits_per_partition,
3629 rice_parameter_limit,
3630 min_partition_order,
3631 max_partition_order,
3634 rice_parameter_search_dist,
3635 &subframe->data.lpc.entropy_coding_method
3638 subframe->data.lpc.order = order;
3639 subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3640 subframe->data.lpc.quantization_level = quantization;
3641 memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3642 for(i = 0; i < order; i++)
3643 subframe->data.lpc.warmup[i] = signal[i];
3645 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;
3647 #if SPOTCHECK_ESTIMATE
3648 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3655 unsigned evaluate_verbatim_subframe_(
3656 FLAC__StreamEncoder *encoder,
3657 const FLAC__int32 signal[],
3659 unsigned subframe_bps,
3660 FLAC__Subframe *subframe
3665 subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3667 subframe->data.verbatim.data = signal;
3669 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
3671 #if SPOTCHECK_ESTIMATE
3672 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3680 unsigned find_best_partition_order_(
3681 FLAC__StreamEncoderPrivate *private_,
3682 const FLAC__int32 residual[],
3683 FLAC__uint64 abs_residual_partition_sums[],
3684 unsigned raw_bits_per_partition[],
3685 unsigned residual_samples,
3686 unsigned predictor_order,
3687 unsigned rice_parameter,
3688 unsigned rice_parameter_limit,
3689 unsigned min_partition_order,
3690 unsigned max_partition_order,
3692 FLAC__bool do_escape_coding,
3693 unsigned rice_parameter_search_dist,
3694 FLAC__EntropyCodingMethod *best_ecm
3697 unsigned residual_bits, best_residual_bits = 0;
3698 unsigned best_parameters_index = 0;
3699 unsigned best_partition_order = 0;
3700 const unsigned blocksize = residual_samples + predictor_order;
3702 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3703 min_partition_order = min(min_partition_order, max_partition_order);
3705 precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
3707 if(do_escape_coding)
3708 precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3711 int partition_order;
3714 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3716 set_partitioned_rice_(
3717 #ifdef EXACT_RICE_BITS_CALCULATION
3720 abs_residual_partition_sums+sum,
3721 raw_bits_per_partition+sum,
3725 rice_parameter_limit,
3726 rice_parameter_search_dist,
3727 (unsigned)partition_order,
3729 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3734 FLAC__ASSERT(best_residual_bits != 0);
3737 sum += 1u << partition_order;
3738 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3739 best_residual_bits = residual_bits;
3740 best_parameters_index = !best_parameters_index;
3741 best_partition_order = partition_order;
3746 best_ecm->data.partitioned_rice.order = best_partition_order;
3750 * We are allowed to de-const the pointer based on our special
3751 * knowledge; it is const to the outside world.
3753 FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
3756 /* save best parameters and raw_bits */
3757 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
3758 memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
3759 if(do_escape_coding)
3760 memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
3762 * Now need to check if the type should be changed to
3763 * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
3764 * size of the rice parameters.
3766 for(partition = 0; partition < (1u<<best_partition_order); partition++) {
3767 if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3768 best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
3774 return best_residual_bits;
3777 #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
3778 extern void precompute_partition_info_sums_32bit_asm_ia32_(
3779 const FLAC__int32 residual[],
3780 FLAC__uint64 abs_residual_partition_sums[],
3782 unsigned predictor_order,
3783 unsigned min_partition_order,
3784 unsigned max_partition_order
3788 void precompute_partition_info_sums_(
3789 const FLAC__int32 residual[],
3790 FLAC__uint64 abs_residual_partition_sums[],
3791 unsigned residual_samples,
3792 unsigned predictor_order,
3793 unsigned min_partition_order,
3794 unsigned max_partition_order,
3798 const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
3799 unsigned partitions = 1u << max_partition_order;
3801 FLAC__ASSERT(default_partition_samples > predictor_order);
3803 #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
3804 /* slightly pessimistic but still catches all common cases */
3805 /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
3806 if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
3807 precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
3812 /* first do max_partition_order */
3814 unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
3815 /* slightly pessimistic but still catches all common cases */
3816 /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
3817 if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
3818 FLAC__uint32 abs_residual_partition_sum;
3820 for(partition = residual_sample = 0; partition < partitions; partition++) {
3821 end += default_partition_samples;
3822 abs_residual_partition_sum = 0;
3823 for( ; residual_sample < end; residual_sample++)
3824 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3825 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3828 else { /* have to pessimistically use 64 bits for accumulator */
3829 FLAC__uint64 abs_residual_partition_sum;
3831 for(partition = residual_sample = 0; partition < partitions; partition++) {
3832 end += default_partition_samples;
3833 abs_residual_partition_sum = 0;
3834 for( ; residual_sample < end; residual_sample++)
3835 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3836 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3841 /* now merge partitions for lower orders */
3843 unsigned from_partition = 0, to_partition = partitions;
3844 int partition_order;
3845 for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
3848 for(i = 0; i < partitions; i++) {
3849 abs_residual_partition_sums[to_partition++] =
3850 abs_residual_partition_sums[from_partition ] +
3851 abs_residual_partition_sums[from_partition+1];
3852 from_partition += 2;
3858 void precompute_partition_info_escapes_(
3859 const FLAC__int32 residual[],
3860 unsigned raw_bits_per_partition[],
3861 unsigned residual_samples,
3862 unsigned predictor_order,
3863 unsigned min_partition_order,
3864 unsigned max_partition_order
3867 int partition_order;
3868 unsigned from_partition, to_partition = 0;
3869 const unsigned blocksize = residual_samples + predictor_order;
3871 /* first do max_partition_order */
3872 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3875 unsigned partition, partition_sample, partition_samples, residual_sample;
3876 const unsigned partitions = 1u << partition_order;
3877 const unsigned default_partition_samples = blocksize >> partition_order;
3879 FLAC__ASSERT(default_partition_samples > predictor_order);
3881 for(partition = residual_sample = 0; partition < partitions; partition++) {
3882 partition_samples = default_partition_samples;
3884 partition_samples -= predictor_order;
3886 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
3887 r = residual[residual_sample++];
3888 /* OPT: maybe faster: rmax |= r ^ (r>>31) */
3894 /* now we know all residual values are in the range [-rmax-1,rmax] */
3895 raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
3897 to_partition = partitions;
3898 break; /*@@@ yuck, should remove the 'for' loop instead */
3901 /* now merge partitions for lower orders */
3902 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
3905 const unsigned partitions = 1u << partition_order;
3906 for(i = 0; i < partitions; i++) {
3907 m = raw_bits_per_partition[from_partition];
3909 raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
3916 #ifdef EXACT_RICE_BITS_CALCULATION
3917 static FLaC__INLINE unsigned count_rice_bits_in_partition_(
3918 const unsigned rice_parameter,
3919 const unsigned partition_samples,
3920 const FLAC__int32 *residual
3923 unsigned i, partition_bits =
3924 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 */
3925 (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
3927 for(i = 0; i < partition_samples; i++)
3928 partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
3929 return partition_bits;
3932 static FLaC__INLINE unsigned count_rice_bits_in_partition_(
3933 const unsigned rice_parameter,
3934 const unsigned partition_samples,
3935 const FLAC__uint64 abs_residual_partition_sum
3939 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 */
3940 (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
3943 (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
3944 : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
3946 - (partition_samples >> 1)
3947 /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
3948 * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
3949 * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
3950 * So the subtraction term tries to guess how many extra bits were contributed.
3951 * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
3957 FLAC__bool set_partitioned_rice_(
3958 #ifdef EXACT_RICE_BITS_CALCULATION
3959 const FLAC__int32 residual[],
3961 const FLAC__uint64 abs_residual_partition_sums[],
3962 const unsigned raw_bits_per_partition[],
3963 const unsigned residual_samples,
3964 const unsigned predictor_order,
3965 const unsigned suggested_rice_parameter,
3966 const unsigned rice_parameter_limit,
3967 const unsigned rice_parameter_search_dist,
3968 const unsigned partition_order,
3969 const FLAC__bool search_for_escapes,
3970 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3974 unsigned rice_parameter, partition_bits;
3975 unsigned best_partition_bits, best_rice_parameter = 0;
3976 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
3977 unsigned *parameters, *raw_bits;
3978 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3979 unsigned min_rice_parameter, max_rice_parameter;
3981 (void)rice_parameter_search_dist;
3984 FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
3985 FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
3987 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
3988 parameters = partitioned_rice_contents->parameters;
3989 raw_bits = partitioned_rice_contents->raw_bits;
3991 if(partition_order == 0) {
3992 best_partition_bits = (unsigned)(-1);
3993 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3994 if(rice_parameter_search_dist) {
3995 if(suggested_rice_parameter < rice_parameter_search_dist)
3996 min_rice_parameter = 0;
3998 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
3999 max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
4000 if(max_rice_parameter >= rice_parameter_limit) {
4001 #ifdef DEBUG_VERBOSE
4002 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
4004 max_rice_parameter = rice_parameter_limit - 1;
4008 min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
4010 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4012 rice_parameter = suggested_rice_parameter;
4014 #ifdef EXACT_RICE_BITS_CALCULATION
4015 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
4017 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
4019 if(partition_bits < best_partition_bits) {
4020 best_rice_parameter = rice_parameter;
4021 best_partition_bits = partition_bits;
4023 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4026 if(search_for_escapes) {
4027 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;
4028 if(partition_bits <= best_partition_bits) {
4029 raw_bits[0] = raw_bits_per_partition[0];
4030 best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4031 best_partition_bits = partition_bits;
4036 parameters[0] = best_rice_parameter;
4037 bits_ += best_partition_bits;
4040 unsigned partition, residual_sample;
4041 unsigned partition_samples;
4042 FLAC__uint64 mean, k;
4043 const unsigned partitions = 1u << partition_order;
4044 for(partition = residual_sample = 0; partition < partitions; partition++) {
4045 partition_samples = (residual_samples+predictor_order) >> partition_order;
4046 if(partition == 0) {
4047 if(partition_samples <= predictor_order)
4050 partition_samples -= predictor_order;
4052 mean = abs_residual_partition_sums[partition];
4053 /* we are basically calculating the size in bits of the
4054 * average residual magnitude in the partition:
4055 * rice_parameter = floor(log2(mean/partition_samples))
4056 * 'mean' is not a good name for the variable, it is
4057 * actually the sum of magnitudes of all residual values
4058 * in the partition, so the actual mean is
4059 * mean/partition_samples
4061 for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
4063 if(rice_parameter >= rice_parameter_limit) {
4064 #ifdef DEBUG_VERBOSE
4065 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
4067 rice_parameter = rice_parameter_limit - 1;
4070 best_partition_bits = (unsigned)(-1);
4071 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4072 if(rice_parameter_search_dist) {
4073 if(rice_parameter < rice_parameter_search_dist)
4074 min_rice_parameter = 0;
4076 min_rice_parameter = rice_parameter - rice_parameter_search_dist;
4077 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
4078 if(max_rice_parameter >= rice_parameter_limit) {
4079 #ifdef DEBUG_VERBOSE
4080 fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
4082 max_rice_parameter = rice_parameter_limit - 1;
4086 min_rice_parameter = max_rice_parameter = rice_parameter;
4088 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4090 #ifdef EXACT_RICE_BITS_CALCULATION
4091 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
4093 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
4095 if(partition_bits < best_partition_bits) {
4096 best_rice_parameter = rice_parameter;
4097 best_partition_bits = partition_bits;
4099 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4102 if(search_for_escapes) {
4103 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;
4104 if(partition_bits <= best_partition_bits) {
4105 raw_bits[partition] = raw_bits_per_partition[partition];
4106 best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4107 best_partition_bits = partition_bits;
4110 raw_bits[partition] = 0;
4112 parameters[partition] = best_rice_parameter;
4113 bits_ += best_partition_bits;
4114 residual_sample += partition_samples;
4122 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
4127 for(i = 0; i < samples && !(x&1); i++)
4134 for(shift = 0; !(x&1); shift++)
4139 for(i = 0; i < samples; i++)
4140 signal[i] >>= shift;
4146 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4150 for(channel = 0; channel < channels; channel++)
4151 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
4153 fifo->tail += wide_samples;
4155 FLAC__ASSERT(fifo->tail <= fifo->size);
4158 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4161 unsigned sample, wide_sample;
4162 unsigned tail = fifo->tail;
4164 sample = input_offset * channels;
4165 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
4166 for(channel = 0; channel < channels; channel++)
4167 fifo->data[channel][tail] = input[sample++];
4172 FLAC__ASSERT(fifo->tail <= fifo->size);
4175 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4177 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4178 const size_t encoded_bytes = encoder->private_->verify.output.bytes;
4181 if(encoder->private_->verify.needs_magic_hack) {
4182 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
4183 *bytes = FLAC__STREAM_SYNC_LENGTH;
4184 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
4185 encoder->private_->verify.needs_magic_hack = false;
4188 if(encoded_bytes == 0) {
4190 * If we get here, a FIFO underflow has occurred,
4191 * which means there is a bug somewhere.
4194 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
4196 else if(encoded_bytes < *bytes)
4197 *bytes = encoded_bytes;
4198 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
4199 encoder->private_->verify.output.data += *bytes;
4200 encoder->private_->verify.output.bytes -= *bytes;
4203 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
4206 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
4208 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
4210 const unsigned channels = frame->header.channels;
4211 const unsigned blocksize = frame->header.blocksize;
4212 const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
4216 for(channel = 0; channel < channels; channel++) {
4217 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
4218 unsigned i, sample = 0;
4219 FLAC__int32 expect = 0, got = 0;
4221 for(i = 0; i < blocksize; i++) {
4222 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
4224 expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
4225 got = (FLAC__int32)buffer[channel][i];
4229 FLAC__ASSERT(i < blocksize);
4230 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
4231 encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
4232 encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
4233 encoder->private_->verify.error_stats.channel = channel;
4234 encoder->private_->verify.error_stats.sample = sample;
4235 encoder->private_->verify.error_stats.expected = expect;
4236 encoder->private_->verify.error_stats.got = got;
4237 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
4238 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
4241 /* dequeue the frame from the fifo */
4242 encoder->private_->verify.input_fifo.tail -= blocksize;
4243 FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
4244 for(channel = 0; channel < channels; channel++)
4245 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]));
4246 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4249 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4251 (void)decoder, (void)metadata, (void)client_data;
4254 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4256 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4257 (void)decoder, (void)status;
4258 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4261 FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4265 *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
4267 if (feof(encoder->private_->file))
4268 return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
4269 else if (ferror(encoder->private_->file))
4270 return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
4272 return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
4275 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4279 if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
4280 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4282 return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4285 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4291 offset = ftello(encoder->private_->file);
4294 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4297 *absolute_byte_offset = (FLAC__uint64)offset;
4298 return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4302 #ifdef FLAC__VALGRIND_TESTING
4303 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4305 size_t ret = fwrite(ptr, size, nmemb, stream);
4311 #define local__fwrite fwrite
4314 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
4316 (void)client_data, (void)current_frame;
4318 if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4319 FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
4321 /* We would like to be able to use 'samples > 0' in the
4322 * clause here but currently because of the nature of our
4323 * Ogg writing implementation, 'samples' is always 0 (see
4324 * ogg_encoder_aspect.c). The downside is extra progress
4327 encoder->private_->is_ogg? true :
4332 /* NOTE: We have to add +bytes, +samples, and +1 to the stats
4333 * because at this point in the callback chain, the stats
4334 * have not been updated. Only after we return and control
4335 * gets back to write_frame_() are the stats updated
4337 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);
4339 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4342 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4346 * This will forcibly set stdout to binary mode (for OSes that require it)
4348 FILE *get_binary_stdout_(void)
4350 /* if something breaks here it is probably due to the presence or
4351 * absence of an underscore before the identifiers 'setmode',
4352 * 'fileno', and/or 'O_BINARY'; check your system header files.
4354 #if defined _MSC_VER || defined __MINGW32__
4355 _setmode(_fileno(stdout), _O_BINARY);
4356 #elif defined __CYGWIN__
4357 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4358 setmode(_fileno(stdout), _O_BINARY);
4359 #elif defined __EMX__
4360 setmode(fileno(stdout), O_BINARY);