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"
82 #define min(x,y) ((x)<(y)?(x):(y))
87 #define max(x,y) ((x)>(y)?(x):(y))
89 /* Exact Rice codeword length calculation is off by default. The simple
90 * (and fast) estimation (of how many bits a residual value will be
91 * encoded with) in this encoder is very good, almost always yielding
92 * compression within 0.1% of exact calculation.
94 #undef EXACT_RICE_BITS_CALCULATION
95 /* Rice parameter searching is off by default. The simple (and fast)
96 * parameter estimation in this encoder is very good, almost always
97 * yielding compression within 0.1% of the optimal parameters.
99 #undef ENABLE_RICE_PARAMETER_SEARCH
103 FLAC__int32 *data[FLAC__MAX_CHANNELS];
104 unsigned size; /* of each data[] in samples */
109 const FLAC__byte *data;
115 ENCODER_IN_MAGIC = 0,
116 ENCODER_IN_METADATA = 1,
120 static struct CompressionLevels {
121 FLAC__bool do_mid_side_stereo;
122 FLAC__bool loose_mid_side_stereo;
123 unsigned max_lpc_order;
124 unsigned qlp_coeff_precision;
125 FLAC__bool do_qlp_coeff_prec_search;
126 FLAC__bool do_escape_coding;
127 FLAC__bool do_exhaustive_model_search;
128 unsigned min_residual_partition_order;
129 unsigned max_residual_partition_order;
130 unsigned rice_parameter_search_dist;
131 } compression_levels_[] = {
132 { false, false, 0, 0, false, false, false, 0, 3, 0 },
133 { true , true , 0, 0, false, false, false, 0, 3, 0 },
134 { true , false, 0, 0, false, false, false, 0, 3, 0 },
135 { false, false, 6, 0, false, false, false, 0, 4, 0 },
136 { true , true , 8, 0, false, false, false, 0, 4, 0 },
137 { true , false, 8, 0, false, false, false, 0, 5, 0 },
138 { true , false, 8, 0, false, false, false, 0, 6, 0 },
139 { true , false, 8, 0, false, false, true , 0, 6, 0 },
140 { true , false, 12, 0, false, false, true , 0, 6, 0 }
144 /***********************************************************************
146 * Private class method prototypes
148 ***********************************************************************/
150 static void set_defaults_(FLAC__StreamEncoder *encoder);
151 static void free_(FLAC__StreamEncoder *encoder);
152 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
153 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
154 static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
155 static void update_metadata_(const FLAC__StreamEncoder *encoder);
157 static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
159 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
160 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
162 static FLAC__bool process_subframe_(
163 FLAC__StreamEncoder *encoder,
164 unsigned min_partition_order,
165 unsigned max_partition_order,
166 const FLAC__FrameHeader *frame_header,
167 unsigned subframe_bps,
168 const FLAC__int32 integer_signal[],
169 FLAC__Subframe *subframe[2],
170 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
171 FLAC__int32 *residual[2],
172 unsigned *best_subframe,
176 static FLAC__bool add_subframe_(
177 FLAC__StreamEncoder *encoder,
179 unsigned subframe_bps,
180 const FLAC__Subframe *subframe,
181 FLAC__BitWriter *frame
184 static unsigned evaluate_constant_subframe_(
185 FLAC__StreamEncoder *encoder,
186 const FLAC__int32 signal,
188 unsigned subframe_bps,
189 FLAC__Subframe *subframe
192 static unsigned evaluate_fixed_subframe_(
193 FLAC__StreamEncoder *encoder,
194 const FLAC__int32 signal[],
195 FLAC__int32 residual[],
196 FLAC__uint64 abs_residual_partition_sums[],
197 unsigned raw_bits_per_partition[],
199 unsigned subframe_bps,
201 unsigned rice_parameter,
202 unsigned rice_parameter_limit,
203 unsigned min_partition_order,
204 unsigned max_partition_order,
205 FLAC__bool do_escape_coding,
206 unsigned rice_parameter_search_dist,
207 FLAC__Subframe *subframe,
208 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
211 #ifndef FLAC__INTEGER_ONLY_LIBRARY
212 static unsigned evaluate_lpc_subframe_(
213 FLAC__StreamEncoder *encoder,
214 const FLAC__int32 signal[],
215 FLAC__int32 residual[],
216 FLAC__uint64 abs_residual_partition_sums[],
217 unsigned raw_bits_per_partition[],
218 const FLAC__real lp_coeff[],
220 unsigned subframe_bps,
222 unsigned qlp_coeff_precision,
223 unsigned rice_parameter,
224 unsigned rice_parameter_limit,
225 unsigned min_partition_order,
226 unsigned max_partition_order,
227 FLAC__bool do_escape_coding,
228 unsigned rice_parameter_search_dist,
229 FLAC__Subframe *subframe,
230 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
234 static unsigned evaluate_verbatim_subframe_(
235 FLAC__StreamEncoder *encoder,
236 const FLAC__int32 signal[],
238 unsigned subframe_bps,
239 FLAC__Subframe *subframe
242 static unsigned find_best_partition_order_(
243 struct FLAC__StreamEncoderPrivate *private_,
244 const FLAC__int32 residual[],
245 FLAC__uint64 abs_residual_partition_sums[],
246 unsigned raw_bits_per_partition[],
247 unsigned residual_samples,
248 unsigned predictor_order,
249 unsigned rice_parameter,
250 unsigned rice_parameter_limit,
251 unsigned min_partition_order,
252 unsigned max_partition_order,
254 FLAC__bool do_escape_coding,
255 unsigned rice_parameter_search_dist,
256 FLAC__EntropyCodingMethod *best_ecm
259 static void precompute_partition_info_sums_(
260 const FLAC__int32 residual[],
261 FLAC__uint64 abs_residual_partition_sums[],
262 unsigned residual_samples,
263 unsigned predictor_order,
264 unsigned min_partition_order,
265 unsigned max_partition_order,
269 static void precompute_partition_info_escapes_(
270 const FLAC__int32 residual[],
271 unsigned raw_bits_per_partition[],
272 unsigned residual_samples,
273 unsigned predictor_order,
274 unsigned min_partition_order,
275 unsigned max_partition_order
278 static FLAC__bool set_partitioned_rice_(
279 #ifdef EXACT_RICE_BITS_CALCULATION
280 const FLAC__int32 residual[],
282 const FLAC__uint64 abs_residual_partition_sums[],
283 const unsigned raw_bits_per_partition[],
284 const unsigned residual_samples,
285 const unsigned predictor_order,
286 const unsigned suggested_rice_parameter,
287 const unsigned rice_parameter_limit,
288 const unsigned rice_parameter_search_dist,
289 const unsigned partition_order,
290 const FLAC__bool search_for_escapes,
291 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
295 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
297 /* verify-related routines: */
298 static void append_to_verify_fifo_(
299 verify_input_fifo *fifo,
300 const FLAC__int32 * const input[],
301 unsigned input_offset,
303 unsigned wide_samples
306 static void append_to_verify_fifo_interleaved_(
307 verify_input_fifo *fifo,
308 const FLAC__int32 input[],
309 unsigned input_offset,
311 unsigned wide_samples
314 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
315 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
316 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
317 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
319 static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
320 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
321 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
322 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);
323 static FILE *get_binary_stdout_(void);
326 /***********************************************************************
330 ***********************************************************************/
332 typedef struct FLAC__StreamEncoderPrivate {
333 unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
334 FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
335 FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
336 #ifndef FLAC__INTEGER_ONLY_LIBRARY
337 FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
338 FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
339 FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
340 FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
342 unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
343 unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
344 FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
345 FLAC__int32 *residual_workspace_mid_side[2][2];
346 FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
347 FLAC__Subframe subframe_workspace_mid_side[2][2];
348 FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
349 FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
350 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
351 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
352 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
353 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
354 unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
355 unsigned best_subframe_mid_side[2];
356 unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
357 unsigned best_subframe_bits_mid_side[2];
358 FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
359 unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
360 FLAC__BitWriter *frame; /* the current frame being worked on */
361 unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
362 unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
363 FLAC__ChannelAssignment last_channel_assignment;
364 FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
365 FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
366 unsigned current_sample_number;
367 unsigned current_frame_number;
368 FLAC__MD5Context md5context;
369 FLAC__CPUInfo cpuinfo;
370 #ifndef FLAC__INTEGER_ONLY_LIBRARY
371 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
373 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
375 #ifndef FLAC__INTEGER_ONLY_LIBRARY
376 void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
377 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[]);
378 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[]);
379 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[]);
381 FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
382 FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
383 FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
384 FLAC__bool disable_constant_subframes;
385 FLAC__bool disable_fixed_subframes;
386 FLAC__bool disable_verbatim_subframes;
390 FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
391 FLAC__StreamEncoderSeekCallback seek_callback;
392 FLAC__StreamEncoderTellCallback tell_callback;
393 FLAC__StreamEncoderWriteCallback write_callback;
394 FLAC__StreamEncoderMetadataCallback metadata_callback;
395 FLAC__StreamEncoderProgressCallback progress_callback;
397 unsigned first_seekpoint_to_check;
398 FILE *file; /* only used when encoding to a file */
399 FLAC__uint64 bytes_written;
400 FLAC__uint64 samples_written;
401 unsigned frames_written;
402 unsigned total_frames_estimate;
403 /* unaligned (original) pointers to allocated data */
404 FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
405 FLAC__int32 *integer_signal_mid_side_unaligned[2];
406 #ifndef FLAC__INTEGER_ONLY_LIBRARY
407 FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
408 FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
409 FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
410 FLAC__real *windowed_signal_unaligned;
412 FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
413 FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
414 FLAC__uint64 *abs_residual_partition_sums_unaligned;
415 unsigned *raw_bits_per_partition_unaligned;
417 * These fields have been moved here from private function local
418 * declarations merely to save stack space during encoding.
420 #ifndef FLAC__INTEGER_ONLY_LIBRARY
421 FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
423 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
425 * The data for the verify section
428 FLAC__StreamDecoder *decoder;
429 EncoderStateHint state_hint;
430 FLAC__bool needs_magic_hack;
431 verify_input_fifo input_fifo;
432 verify_output output;
434 FLAC__uint64 absolute_sample;
435 unsigned frame_number;
438 FLAC__int32 expected;
442 FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
443 } FLAC__StreamEncoderPrivate;
445 /***********************************************************************
447 * Public static class data
449 ***********************************************************************/
451 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
452 "FLAC__STREAM_ENCODER_OK",
453 "FLAC__STREAM_ENCODER_UNINITIALIZED",
454 "FLAC__STREAM_ENCODER_OGG_ERROR",
455 "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
456 "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
457 "FLAC__STREAM_ENCODER_CLIENT_ERROR",
458 "FLAC__STREAM_ENCODER_IO_ERROR",
459 "FLAC__STREAM_ENCODER_FRAMING_ERROR",
460 "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
463 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
464 "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
465 "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
466 "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
467 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
468 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
469 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
470 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
471 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
472 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
473 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
474 "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
475 "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
476 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
477 "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
480 FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
481 "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
482 "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
483 "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
484 "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
487 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
488 "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
489 "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
492 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
493 "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
494 "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
495 "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
498 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
499 "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
500 "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
501 "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
504 /* Number of samples that will be overread to watch for end of stream. By
505 * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
506 * always try to read blocksize+1 samples before encoding a block, so that
507 * even if the stream has a total sample count that is an integral multiple
508 * of the blocksize, we will still notice when we are encoding the last
509 * block. This is needed, for example, to correctly set the end-of-stream
510 * marker in Ogg FLAC.
512 * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
513 * not really any reason to change it.
515 static const unsigned OVERREAD_ = 1;
517 /***********************************************************************
519 * Class constructor/destructor
522 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
524 FLAC__StreamEncoder *encoder;
527 FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
529 encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
534 encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
535 if(encoder->protected_ == 0) {
540 encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
541 if(encoder->private_ == 0) {
542 free(encoder->protected_);
547 encoder->private_->frame = FLAC__bitwriter_new();
548 if(encoder->private_->frame == 0) {
549 free(encoder->private_);
550 free(encoder->protected_);
555 encoder->private_->file = 0;
557 set_defaults_(encoder);
559 encoder->private_->is_being_deleted = false;
561 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
562 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
563 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
565 for(i = 0; i < 2; i++) {
566 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
567 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
569 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
570 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
571 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
573 for(i = 0; i < 2; i++) {
574 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
575 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
578 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
579 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
580 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
582 for(i = 0; i < 2; i++) {
583 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
584 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
586 for(i = 0; i < 2; i++)
587 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
589 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
594 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
598 FLAC__ASSERT(0 != encoder);
599 FLAC__ASSERT(0 != encoder->protected_);
600 FLAC__ASSERT(0 != encoder->private_);
601 FLAC__ASSERT(0 != encoder->private_->frame);
603 encoder->private_->is_being_deleted = true;
605 (void)FLAC__stream_encoder_finish(encoder);
607 if(0 != encoder->private_->verify.decoder)
608 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
610 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
611 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
612 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
614 for(i = 0; i < 2; i++) {
615 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
616 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
618 for(i = 0; i < 2; i++)
619 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
621 FLAC__bitwriter_delete(encoder->private_->frame);
622 free(encoder->private_);
623 free(encoder->protected_);
627 /***********************************************************************
629 * Public class methods
631 ***********************************************************************/
633 static FLAC__StreamEncoderInitStatus init_stream_internal_(
634 FLAC__StreamEncoder *encoder,
635 FLAC__StreamEncoderReadCallback read_callback,
636 FLAC__StreamEncoderWriteCallback write_callback,
637 FLAC__StreamEncoderSeekCallback seek_callback,
638 FLAC__StreamEncoderTellCallback tell_callback,
639 FLAC__StreamEncoderMetadataCallback metadata_callback,
645 FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
647 FLAC__ASSERT(0 != encoder);
649 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
650 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
654 return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
657 if(0 == write_callback || (seek_callback && 0 == tell_callback))
658 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
660 if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
661 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
663 if(encoder->protected_->channels != 2) {
664 encoder->protected_->do_mid_side_stereo = false;
665 encoder->protected_->loose_mid_side_stereo = false;
667 else if(!encoder->protected_->do_mid_side_stereo)
668 encoder->protected_->loose_mid_side_stereo = false;
670 if(encoder->protected_->bits_per_sample >= 32)
671 encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
673 if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
674 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
676 if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
677 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
679 if(encoder->protected_->blocksize == 0) {
680 if(encoder->protected_->max_lpc_order == 0)
681 encoder->protected_->blocksize = 1152;
683 encoder->protected_->blocksize = 4096;
686 if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
687 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
689 if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
690 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
692 if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
693 return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
695 if(encoder->protected_->qlp_coeff_precision == 0) {
696 if(encoder->protected_->bits_per_sample < 16) {
697 /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
698 /* @@@ until then we'll make a guess */
699 encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
701 else if(encoder->protected_->bits_per_sample == 16) {
702 if(encoder->protected_->blocksize <= 192)
703 encoder->protected_->qlp_coeff_precision = 7;
704 else if(encoder->protected_->blocksize <= 384)
705 encoder->protected_->qlp_coeff_precision = 8;
706 else if(encoder->protected_->blocksize <= 576)
707 encoder->protected_->qlp_coeff_precision = 9;
708 else if(encoder->protected_->blocksize <= 1152)
709 encoder->protected_->qlp_coeff_precision = 10;
710 else if(encoder->protected_->blocksize <= 2304)
711 encoder->protected_->qlp_coeff_precision = 11;
712 else if(encoder->protected_->blocksize <= 4608)
713 encoder->protected_->qlp_coeff_precision = 12;
715 encoder->protected_->qlp_coeff_precision = 13;
718 if(encoder->protected_->blocksize <= 384)
719 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
720 else if(encoder->protected_->blocksize <= 1152)
721 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
723 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
725 FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
727 else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
728 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
730 if(encoder->protected_->streamable_subset) {
732 encoder->protected_->blocksize != 192 &&
733 encoder->protected_->blocksize != 576 &&
734 encoder->protected_->blocksize != 1152 &&
735 encoder->protected_->blocksize != 2304 &&
736 encoder->protected_->blocksize != 4608 &&
737 encoder->protected_->blocksize != 256 &&
738 encoder->protected_->blocksize != 512 &&
739 encoder->protected_->blocksize != 1024 &&
740 encoder->protected_->blocksize != 2048 &&
741 encoder->protected_->blocksize != 4096 &&
742 encoder->protected_->blocksize != 8192 &&
743 encoder->protected_->blocksize != 16384
745 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
746 if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
747 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
749 encoder->protected_->bits_per_sample != 8 &&
750 encoder->protected_->bits_per_sample != 12 &&
751 encoder->protected_->bits_per_sample != 16 &&
752 encoder->protected_->bits_per_sample != 20 &&
753 encoder->protected_->bits_per_sample != 24
755 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
756 if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
757 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
759 encoder->protected_->sample_rate <= 48000 &&
761 encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
762 encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
765 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
769 if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
770 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
771 if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
772 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
775 /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
776 if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
778 for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
779 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
780 FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
782 encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
783 encoder->protected_->metadata[0] = vc;
789 /* keep track of any SEEKTABLE block */
790 if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
792 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
793 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
794 encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
795 break; /* take only the first one */
800 /* validate metadata */
801 if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
802 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
803 metadata_has_seektable = false;
804 metadata_has_vorbis_comment = false;
805 metadata_picture_has_type1 = false;
806 metadata_picture_has_type2 = false;
807 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
808 const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
809 if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
810 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
811 else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
812 if(metadata_has_seektable) /* only one is allowed */
813 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
814 metadata_has_seektable = true;
815 if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
816 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
818 else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
819 if(metadata_has_vorbis_comment) /* only one is allowed */
820 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
821 metadata_has_vorbis_comment = true;
823 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
824 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
825 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
827 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
828 if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
829 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
830 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
831 if(metadata_picture_has_type1) /* there should only be 1 per stream */
832 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
833 metadata_picture_has_type1 = true;
834 /* standard icon must be 32x32 pixel PNG */
836 m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
838 (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
839 m->data.picture.width != 32 ||
840 m->data.picture.height != 32
843 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
845 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
846 if(metadata_picture_has_type2) /* there should only be 1 per stream */
847 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
848 metadata_picture_has_type2 = true;
853 encoder->private_->input_capacity = 0;
854 for(i = 0; i < encoder->protected_->channels; i++) {
855 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
856 #ifndef FLAC__INTEGER_ONLY_LIBRARY
857 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
860 for(i = 0; i < 2; i++) {
861 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
862 #ifndef FLAC__INTEGER_ONLY_LIBRARY
863 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
866 #ifndef FLAC__INTEGER_ONLY_LIBRARY
867 for(i = 0; i < encoder->protected_->num_apodizations; i++)
868 encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
869 encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
871 for(i = 0; i < encoder->protected_->channels; i++) {
872 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
873 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
874 encoder->private_->best_subframe[i] = 0;
876 for(i = 0; i < 2; i++) {
877 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
878 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
879 encoder->private_->best_subframe_mid_side[i] = 0;
881 encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
882 encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
883 #ifndef FLAC__INTEGER_ONLY_LIBRARY
884 encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
886 /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
887 /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply÷ by hand */
888 FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
889 FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
890 FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
891 FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
892 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);
894 if(encoder->private_->loose_mid_side_stereo_frames == 0)
895 encoder->private_->loose_mid_side_stereo_frames = 1;
896 encoder->private_->loose_mid_side_stereo_frame_count = 0;
897 encoder->private_->current_sample_number = 0;
898 encoder->private_->current_frame_number = 0;
900 encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
901 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? */
902 encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
905 * get the CPU info and set the function pointers
907 FLAC__cpu_info(&encoder->private_->cpuinfo);
908 /* first default to the non-asm routines */
909 #ifndef FLAC__INTEGER_ONLY_LIBRARY
910 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
912 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
913 #ifndef FLAC__INTEGER_ONLY_LIBRARY
914 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
915 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
916 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
918 /* now override with asm where appropriate */
919 #ifndef FLAC__INTEGER_ONLY_LIBRARY
920 # ifndef FLAC__NO_ASM
921 if(encoder->private_->cpuinfo.use_asm) {
922 # ifdef FLAC__CPU_IA32
923 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
924 # ifdef FLAC__HAS_NASM
925 if(encoder->private_->cpuinfo.data.ia32.sse) {
926 if(encoder->protected_->max_lpc_order < 4)
927 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
928 else if(encoder->protected_->max_lpc_order < 8)
929 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
930 else if(encoder->protected_->max_lpc_order < 12)
931 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
933 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
935 else if(encoder->private_->cpuinfo.data.ia32._3dnow)
936 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
938 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
939 if(encoder->private_->cpuinfo.data.ia32.mmx) {
940 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
941 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
944 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
945 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
947 if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
948 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
949 # endif /* FLAC__HAS_NASM */
950 # endif /* FLAC__CPU_IA32 */
952 # endif /* !FLAC__NO_ASM */
953 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
954 /* finally override based on wide-ness if necessary */
955 if(encoder->private_->use_wide_by_block) {
956 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
959 /* set state to OK; from here on, errors are fatal and we'll override the state then */
960 encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
963 encoder->private_->is_ogg = is_ogg;
964 if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
965 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
966 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
970 encoder->private_->read_callback = read_callback;
971 encoder->private_->write_callback = write_callback;
972 encoder->private_->seek_callback = seek_callback;
973 encoder->private_->tell_callback = tell_callback;
974 encoder->private_->metadata_callback = metadata_callback;
975 encoder->private_->client_data = client_data;
977 if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
978 /* the above function sets the state for us in case of an error */
979 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
982 if(!FLAC__bitwriter_init(encoder->private_->frame)) {
983 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
984 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
988 * Set up the verify stuff if necessary
990 if(encoder->protected_->verify) {
992 * First, set up the fifo which will hold the
993 * original signal to compare against
995 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
996 for(i = 0; i < encoder->protected_->channels; i++) {
997 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))) {
998 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
999 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1002 encoder->private_->verify.input_fifo.tail = 0;
1005 * Now set up a stream decoder for verification
1007 encoder->private_->verify.decoder = FLAC__stream_decoder_new();
1008 if(0 == encoder->private_->verify.decoder) {
1009 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1010 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1013 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) {
1014 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1015 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1018 encoder->private_->verify.error_stats.absolute_sample = 0;
1019 encoder->private_->verify.error_stats.frame_number = 0;
1020 encoder->private_->verify.error_stats.channel = 0;
1021 encoder->private_->verify.error_stats.sample = 0;
1022 encoder->private_->verify.error_stats.expected = 0;
1023 encoder->private_->verify.error_stats.got = 0;
1026 * These must be done before we write any metadata, because that
1027 * calls the write_callback, which uses these values.
1029 encoder->private_->first_seekpoint_to_check = 0;
1030 encoder->private_->samples_written = 0;
1031 encoder->protected_->streaminfo_offset = 0;
1032 encoder->protected_->seektable_offset = 0;
1033 encoder->protected_->audio_offset = 0;
1036 * write the stream header
1038 if(encoder->protected_->verify)
1039 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1040 if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1041 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1042 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1044 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1045 /* the above function sets the state for us in case of an error */
1046 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1050 * write the STREAMINFO metadata block
1052 if(encoder->protected_->verify)
1053 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1054 encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1055 encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1056 encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1057 encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1058 encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1059 encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1060 encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1061 encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1062 encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1063 encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1064 encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1065 memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1066 if(encoder->protected_->do_md5)
1067 FLAC__MD5Init(&encoder->private_->md5context);
1068 if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1069 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1070 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1072 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1073 /* the above function sets the state for us in case of an error */
1074 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1078 * Now that the STREAMINFO block is written, we can init this to an
1079 * absurdly-high value...
1081 encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1082 /* ... and clear this to 0 */
1083 encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1086 * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1087 * if not, we will write an empty one (FLAC__add_metadata_block()
1088 * automatically supplies the vendor string).
1090 * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1091 * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
1092 * true it will have already insured that the metadata list is properly
1095 if(!metadata_has_vorbis_comment) {
1096 FLAC__StreamMetadata vorbis_comment;
1097 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1098 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1099 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1100 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1101 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1102 vorbis_comment.data.vorbis_comment.num_comments = 0;
1103 vorbis_comment.data.vorbis_comment.comments = 0;
1104 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1105 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1106 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1108 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1109 /* the above function sets the state for us in case of an error */
1110 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1115 * write the user's metadata blocks
1117 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1118 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1119 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1120 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1121 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1123 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1124 /* the above function sets the state for us in case of an error */
1125 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1129 /* now that all the metadata is written, we save the stream offset */
1130 if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &encoder->protected_->audio_offset, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) { /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
1131 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1132 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1135 if(encoder->protected_->verify)
1136 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1138 return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1141 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1142 FLAC__StreamEncoder *encoder,
1143 FLAC__StreamEncoderWriteCallback write_callback,
1144 FLAC__StreamEncoderSeekCallback seek_callback,
1145 FLAC__StreamEncoderTellCallback tell_callback,
1146 FLAC__StreamEncoderMetadataCallback metadata_callback,
1150 return init_stream_internal_(
1152 /*read_callback=*/0,
1162 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1163 FLAC__StreamEncoder *encoder,
1164 FLAC__StreamEncoderReadCallback read_callback,
1165 FLAC__StreamEncoderWriteCallback write_callback,
1166 FLAC__StreamEncoderSeekCallback seek_callback,
1167 FLAC__StreamEncoderTellCallback tell_callback,
1168 FLAC__StreamEncoderMetadataCallback metadata_callback,
1172 return init_stream_internal_(
1184 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1185 FLAC__StreamEncoder *encoder,
1187 FLAC__StreamEncoderProgressCallback progress_callback,
1192 FLAC__StreamEncoderInitStatus init_status;
1194 FLAC__ASSERT(0 != encoder);
1195 FLAC__ASSERT(0 != file);
1197 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1198 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1200 /* double protection */
1202 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1203 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1207 * To make sure that our file does not go unclosed after an error, we
1208 * must assign the FILE pointer before any further error can occur in
1212 file = get_binary_stdout_(); /* just to be safe */
1214 encoder->private_->file = file;
1216 encoder->private_->progress_callback = progress_callback;
1217 encoder->private_->bytes_written = 0;
1218 encoder->private_->samples_written = 0;
1219 encoder->private_->frames_written = 0;
1221 init_status = init_stream_internal_(
1223 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1224 file_write_callback_,
1225 encoder->private_->file == stdout? 0 : file_seek_callback_,
1226 encoder->private_->file == stdout? 0 : file_tell_callback_,
1227 /*metadata_callback=*/0,
1231 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1232 /* the above function sets the state for us in case of an error */
1237 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1239 FLAC__ASSERT(blocksize != 0);
1240 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1246 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1247 FLAC__StreamEncoder *encoder,
1249 FLAC__StreamEncoderProgressCallback progress_callback,
1253 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1256 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1257 FLAC__StreamEncoder *encoder,
1259 FLAC__StreamEncoderProgressCallback progress_callback,
1263 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1266 static FLAC__StreamEncoderInitStatus init_file_internal_(
1267 FLAC__StreamEncoder *encoder,
1268 const char *filename,
1269 FLAC__StreamEncoderProgressCallback progress_callback,
1276 FLAC__ASSERT(0 != encoder);
1279 * To make sure that our file does not go unclosed after an error, we
1280 * have to do the same entrance checks here that are later performed
1281 * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1283 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1284 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1286 file = filename? fopen(filename, "w+b") : stdout;
1289 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1290 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1293 return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1296 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1297 FLAC__StreamEncoder *encoder,
1298 const char *filename,
1299 FLAC__StreamEncoderProgressCallback progress_callback,
1303 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1306 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1307 FLAC__StreamEncoder *encoder,
1308 const char *filename,
1309 FLAC__StreamEncoderProgressCallback progress_callback,
1313 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1316 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1318 FLAC__bool error = false;
1320 FLAC__ASSERT(0 != encoder);
1321 FLAC__ASSERT(0 != encoder->private_);
1322 FLAC__ASSERT(0 != encoder->protected_);
1324 if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1327 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1328 if(encoder->private_->current_sample_number != 0) {
1329 const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1330 encoder->protected_->blocksize = encoder->private_->current_sample_number;
1331 if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1336 if(encoder->protected_->do_md5)
1337 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1339 if(!encoder->private_->is_being_deleted) {
1340 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1341 if(encoder->private_->seek_callback) {
1343 if(encoder->private_->is_ogg)
1344 update_ogg_metadata_(encoder);
1347 update_metadata_(encoder);
1349 /* check if an error occurred while updating metadata */
1350 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1353 if(encoder->private_->metadata_callback)
1354 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1357 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1359 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1364 if(0 != encoder->private_->file) {
1365 if(encoder->private_->file != stdout)
1366 fclose(encoder->private_->file);
1367 encoder->private_->file = 0;
1371 if(encoder->private_->is_ogg)
1372 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1376 set_defaults_(encoder);
1379 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1384 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1386 FLAC__ASSERT(0 != encoder);
1387 FLAC__ASSERT(0 != encoder->private_);
1388 FLAC__ASSERT(0 != encoder->protected_);
1389 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1392 /* can't check encoder->private_->is_ogg since that's not set until init time */
1393 FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1401 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1403 FLAC__ASSERT(0 != encoder);
1404 FLAC__ASSERT(0 != encoder->private_);
1405 FLAC__ASSERT(0 != encoder->protected_);
1406 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1408 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1409 encoder->protected_->verify = value;
1414 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1416 FLAC__ASSERT(0 != encoder);
1417 FLAC__ASSERT(0 != encoder->private_);
1418 FLAC__ASSERT(0 != encoder->protected_);
1419 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1421 encoder->protected_->streamable_subset = value;
1425 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
1427 FLAC__ASSERT(0 != encoder);
1428 FLAC__ASSERT(0 != encoder->private_);
1429 FLAC__ASSERT(0 != encoder->protected_);
1430 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1432 encoder->protected_->do_md5 = value;
1436 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1438 FLAC__ASSERT(0 != encoder);
1439 FLAC__ASSERT(0 != encoder->private_);
1440 FLAC__ASSERT(0 != encoder->protected_);
1441 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1443 encoder->protected_->channels = value;
1447 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1449 FLAC__ASSERT(0 != encoder);
1450 FLAC__ASSERT(0 != encoder->private_);
1451 FLAC__ASSERT(0 != encoder->protected_);
1452 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1454 encoder->protected_->bits_per_sample = value;
1458 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1460 FLAC__ASSERT(0 != encoder);
1461 FLAC__ASSERT(0 != encoder->private_);
1462 FLAC__ASSERT(0 != encoder->protected_);
1463 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1465 encoder->protected_->sample_rate = value;
1469 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1471 FLAC__bool ok = true;
1472 FLAC__ASSERT(0 != encoder);
1473 FLAC__ASSERT(0 != encoder->private_);
1474 FLAC__ASSERT(0 != encoder->protected_);
1475 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1477 if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1478 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1479 ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
1480 ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
1481 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1484 ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
1485 /* but it's too hard to specify the string in a locale-specific way */
1487 encoder->protected_->num_apodizations = 1;
1488 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1489 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1492 ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
1493 ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
1494 ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1495 ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
1496 ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
1497 ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1498 ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1499 ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
1503 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1505 FLAC__ASSERT(0 != encoder);
1506 FLAC__ASSERT(0 != encoder->private_);
1507 FLAC__ASSERT(0 != encoder->protected_);
1508 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1510 encoder->protected_->blocksize = value;
1514 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1516 FLAC__ASSERT(0 != encoder);
1517 FLAC__ASSERT(0 != encoder->private_);
1518 FLAC__ASSERT(0 != encoder->protected_);
1519 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1521 encoder->protected_->do_mid_side_stereo = value;
1525 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1527 FLAC__ASSERT(0 != encoder);
1528 FLAC__ASSERT(0 != encoder->private_);
1529 FLAC__ASSERT(0 != encoder->protected_);
1530 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1532 encoder->protected_->loose_mid_side_stereo = value;
1536 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1538 FLAC__ASSERT(0 != encoder);
1539 FLAC__ASSERT(0 != encoder->private_);
1540 FLAC__ASSERT(0 != encoder->protected_);
1541 FLAC__ASSERT(0 != specification);
1542 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1544 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1545 (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1547 encoder->protected_->num_apodizations = 0;
1549 const char *s = strchr(specification, ';');
1550 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1551 if (n==8 && 0 == strncmp("bartlett" , specification, n))
1552 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1553 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1554 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1555 else if(n==8 && 0 == strncmp("blackman" , specification, n))
1556 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1557 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1558 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1559 else if(n==6 && 0 == strncmp("connes" , specification, n))
1560 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1561 else if(n==7 && 0 == strncmp("flattop" , specification, n))
1562 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1563 else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
1564 FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1565 if (stddev > 0.0 && stddev <= 0.5) {
1566 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1567 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1570 else if(n==7 && 0 == strncmp("hamming" , specification, n))
1571 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1572 else if(n==4 && 0 == strncmp("hann" , specification, n))
1573 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1574 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1575 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1576 else if(n==7 && 0 == strncmp("nuttall" , specification, n))
1577 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1578 else if(n==9 && 0 == strncmp("rectangle" , specification, n))
1579 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1580 else if(n==8 && 0 == strncmp("triangle" , specification, n))
1581 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1582 else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
1583 FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1584 if (p >= 0.0 && p <= 1.0) {
1585 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1586 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1589 else if(n==5 && 0 == strncmp("welch" , specification, n))
1590 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1591 if (encoder->protected_->num_apodizations == 32)
1594 specification = s+1;
1598 if(encoder->protected_->num_apodizations == 0) {
1599 encoder->protected_->num_apodizations = 1;
1600 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1601 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1607 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1609 FLAC__ASSERT(0 != encoder);
1610 FLAC__ASSERT(0 != encoder->private_);
1611 FLAC__ASSERT(0 != encoder->protected_);
1612 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1614 encoder->protected_->max_lpc_order = value;
1618 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1620 FLAC__ASSERT(0 != encoder);
1621 FLAC__ASSERT(0 != encoder->private_);
1622 FLAC__ASSERT(0 != encoder->protected_);
1623 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1625 encoder->protected_->qlp_coeff_precision = value;
1629 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1631 FLAC__ASSERT(0 != encoder);
1632 FLAC__ASSERT(0 != encoder->private_);
1633 FLAC__ASSERT(0 != encoder->protected_);
1634 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1636 encoder->protected_->do_qlp_coeff_prec_search = value;
1640 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1642 FLAC__ASSERT(0 != encoder);
1643 FLAC__ASSERT(0 != encoder->private_);
1644 FLAC__ASSERT(0 != encoder->protected_);
1645 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1648 /*@@@ deprecated: */
1649 encoder->protected_->do_escape_coding = value;
1656 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1658 FLAC__ASSERT(0 != encoder);
1659 FLAC__ASSERT(0 != encoder->private_);
1660 FLAC__ASSERT(0 != encoder->protected_);
1661 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1663 encoder->protected_->do_exhaustive_model_search = value;
1667 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1669 FLAC__ASSERT(0 != encoder);
1670 FLAC__ASSERT(0 != encoder->private_);
1671 FLAC__ASSERT(0 != encoder->protected_);
1672 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1674 encoder->protected_->min_residual_partition_order = value;
1678 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1680 FLAC__ASSERT(0 != encoder);
1681 FLAC__ASSERT(0 != encoder->private_);
1682 FLAC__ASSERT(0 != encoder->protected_);
1683 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1685 encoder->protected_->max_residual_partition_order = value;
1689 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1691 FLAC__ASSERT(0 != encoder);
1692 FLAC__ASSERT(0 != encoder->private_);
1693 FLAC__ASSERT(0 != encoder->protected_);
1694 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1697 /*@@@ deprecated: */
1698 encoder->protected_->rice_parameter_search_dist = value;
1705 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1707 FLAC__ASSERT(0 != encoder);
1708 FLAC__ASSERT(0 != encoder->private_);
1709 FLAC__ASSERT(0 != encoder->protected_);
1710 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1712 encoder->protected_->total_samples_estimate = value;
1716 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1718 FLAC__ASSERT(0 != encoder);
1719 FLAC__ASSERT(0 != encoder->private_);
1720 FLAC__ASSERT(0 != encoder->protected_);
1721 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1727 /* realloc() does not do exactly what we want so... */
1728 if(encoder->protected_->metadata) {
1729 free(encoder->protected_->metadata);
1730 encoder->protected_->metadata = 0;
1731 encoder->protected_->num_metadata_blocks = 0;
1734 FLAC__StreamMetadata **m;
1735 if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
1737 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1738 encoder->protected_->metadata = m;
1739 encoder->protected_->num_metadata_blocks = num_blocks;
1742 if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1749 * These three functions are not static, but not publically exposed in
1750 * include/FLAC/ either. They are used by the test suite.
1752 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1754 FLAC__ASSERT(0 != encoder);
1755 FLAC__ASSERT(0 != encoder->private_);
1756 FLAC__ASSERT(0 != encoder->protected_);
1757 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1759 encoder->private_->disable_constant_subframes = value;
1763 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1765 FLAC__ASSERT(0 != encoder);
1766 FLAC__ASSERT(0 != encoder->private_);
1767 FLAC__ASSERT(0 != encoder->protected_);
1768 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1770 encoder->private_->disable_fixed_subframes = value;
1774 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1776 FLAC__ASSERT(0 != encoder);
1777 FLAC__ASSERT(0 != encoder->private_);
1778 FLAC__ASSERT(0 != encoder->protected_);
1779 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1781 encoder->private_->disable_verbatim_subframes = value;
1785 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1787 FLAC__ASSERT(0 != encoder);
1788 FLAC__ASSERT(0 != encoder->private_);
1789 FLAC__ASSERT(0 != encoder->protected_);
1790 return encoder->protected_->state;
1793 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1795 FLAC__ASSERT(0 != encoder);
1796 FLAC__ASSERT(0 != encoder->private_);
1797 FLAC__ASSERT(0 != encoder->protected_);
1798 if(encoder->protected_->verify)
1799 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1801 return FLAC__STREAM_DECODER_UNINITIALIZED;
1804 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1806 FLAC__ASSERT(0 != encoder);
1807 FLAC__ASSERT(0 != encoder->private_);
1808 FLAC__ASSERT(0 != encoder->protected_);
1809 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1810 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1812 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1815 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)
1817 FLAC__ASSERT(0 != encoder);
1818 FLAC__ASSERT(0 != encoder->private_);
1819 FLAC__ASSERT(0 != encoder->protected_);
1820 if(0 != absolute_sample)
1821 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1822 if(0 != frame_number)
1823 *frame_number = encoder->private_->verify.error_stats.frame_number;
1825 *channel = encoder->private_->verify.error_stats.channel;
1827 *sample = encoder->private_->verify.error_stats.sample;
1829 *expected = encoder->private_->verify.error_stats.expected;
1831 *got = encoder->private_->verify.error_stats.got;
1834 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1836 FLAC__ASSERT(0 != encoder);
1837 FLAC__ASSERT(0 != encoder->private_);
1838 FLAC__ASSERT(0 != encoder->protected_);
1839 return encoder->protected_->verify;
1842 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1844 FLAC__ASSERT(0 != encoder);
1845 FLAC__ASSERT(0 != encoder->private_);
1846 FLAC__ASSERT(0 != encoder->protected_);
1847 return encoder->protected_->streamable_subset;
1850 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
1852 FLAC__ASSERT(0 != encoder);
1853 FLAC__ASSERT(0 != encoder->private_);
1854 FLAC__ASSERT(0 != encoder->protected_);
1855 return encoder->protected_->do_md5;
1858 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1860 FLAC__ASSERT(0 != encoder);
1861 FLAC__ASSERT(0 != encoder->private_);
1862 FLAC__ASSERT(0 != encoder->protected_);
1863 return encoder->protected_->channels;
1866 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1868 FLAC__ASSERT(0 != encoder);
1869 FLAC__ASSERT(0 != encoder->private_);
1870 FLAC__ASSERT(0 != encoder->protected_);
1871 return encoder->protected_->bits_per_sample;
1874 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1876 FLAC__ASSERT(0 != encoder);
1877 FLAC__ASSERT(0 != encoder->private_);
1878 FLAC__ASSERT(0 != encoder->protected_);
1879 return encoder->protected_->sample_rate;
1882 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1884 FLAC__ASSERT(0 != encoder);
1885 FLAC__ASSERT(0 != encoder->private_);
1886 FLAC__ASSERT(0 != encoder->protected_);
1887 return encoder->protected_->blocksize;
1890 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1892 FLAC__ASSERT(0 != encoder);
1893 FLAC__ASSERT(0 != encoder->private_);
1894 FLAC__ASSERT(0 != encoder->protected_);
1895 return encoder->protected_->do_mid_side_stereo;
1898 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1900 FLAC__ASSERT(0 != encoder);
1901 FLAC__ASSERT(0 != encoder->private_);
1902 FLAC__ASSERT(0 != encoder->protected_);
1903 return encoder->protected_->loose_mid_side_stereo;
1906 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1908 FLAC__ASSERT(0 != encoder);
1909 FLAC__ASSERT(0 != encoder->private_);
1910 FLAC__ASSERT(0 != encoder->protected_);
1911 return encoder->protected_->max_lpc_order;
1914 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1916 FLAC__ASSERT(0 != encoder);
1917 FLAC__ASSERT(0 != encoder->private_);
1918 FLAC__ASSERT(0 != encoder->protected_);
1919 return encoder->protected_->qlp_coeff_precision;
1922 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1924 FLAC__ASSERT(0 != encoder);
1925 FLAC__ASSERT(0 != encoder->private_);
1926 FLAC__ASSERT(0 != encoder->protected_);
1927 return encoder->protected_->do_qlp_coeff_prec_search;
1930 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1932 FLAC__ASSERT(0 != encoder);
1933 FLAC__ASSERT(0 != encoder->private_);
1934 FLAC__ASSERT(0 != encoder->protected_);
1935 return encoder->protected_->do_escape_coding;
1938 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1940 FLAC__ASSERT(0 != encoder);
1941 FLAC__ASSERT(0 != encoder->private_);
1942 FLAC__ASSERT(0 != encoder->protected_);
1943 return encoder->protected_->do_exhaustive_model_search;
1946 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1948 FLAC__ASSERT(0 != encoder);
1949 FLAC__ASSERT(0 != encoder->private_);
1950 FLAC__ASSERT(0 != encoder->protected_);
1951 return encoder->protected_->min_residual_partition_order;
1954 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1956 FLAC__ASSERT(0 != encoder);
1957 FLAC__ASSERT(0 != encoder->private_);
1958 FLAC__ASSERT(0 != encoder->protected_);
1959 return encoder->protected_->max_residual_partition_order;
1962 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1964 FLAC__ASSERT(0 != encoder);
1965 FLAC__ASSERT(0 != encoder->private_);
1966 FLAC__ASSERT(0 != encoder->protected_);
1967 return encoder->protected_->rice_parameter_search_dist;
1970 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1972 FLAC__ASSERT(0 != encoder);
1973 FLAC__ASSERT(0 != encoder->private_);
1974 FLAC__ASSERT(0 != encoder->protected_);
1975 return encoder->protected_->total_samples_estimate;
1978 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1980 unsigned i, j = 0, channel;
1981 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1983 FLAC__ASSERT(0 != encoder);
1984 FLAC__ASSERT(0 != encoder->private_);
1985 FLAC__ASSERT(0 != encoder->protected_);
1986 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1989 const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
1991 if(encoder->protected_->verify)
1992 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
1994 for(channel = 0; channel < channels; channel++)
1995 memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
1997 if(encoder->protected_->do_mid_side_stereo) {
1998 FLAC__ASSERT(channels == 2);
1999 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2000 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2001 encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
2002 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' ! */
2008 encoder->private_->current_sample_number += n;
2010 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2011 if(encoder->private_->current_sample_number > blocksize) {
2012 FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
2013 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2014 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2016 /* move unprocessed overread samples to beginnings of arrays */
2017 for(channel = 0; channel < channels; channel++)
2018 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2019 if(encoder->protected_->do_mid_side_stereo) {
2020 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2021 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2023 encoder->private_->current_sample_number = 1;
2025 } while(j < samples);
2030 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2032 unsigned i, j, k, channel;
2033 FLAC__int32 x, mid, side;
2034 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2036 FLAC__ASSERT(0 != encoder);
2037 FLAC__ASSERT(0 != encoder->private_);
2038 FLAC__ASSERT(0 != encoder->protected_);
2039 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2043 * we have several flavors of the same basic loop, optimized for
2044 * different conditions:
2046 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2048 * stereo coding: unroll channel loop
2051 if(encoder->protected_->verify)
2052 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2054 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2055 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2056 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2058 encoder->private_->integer_signal[1][i] = x;
2061 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2062 encoder->private_->integer_signal_mid_side[1][i] = side;
2063 encoder->private_->integer_signal_mid_side[0][i] = mid;
2065 encoder->private_->current_sample_number = i;
2066 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2068 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2070 /* move unprocessed overread samples to beginnings of arrays */
2071 FLAC__ASSERT(i == blocksize+OVERREAD_);
2072 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2073 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
2074 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
2075 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2076 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2077 encoder->private_->current_sample_number = 1;
2079 } while(j < samples);
2083 * independent channel coding: buffer each channel in inner loop
2086 if(encoder->protected_->verify)
2087 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2089 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2090 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2091 for(channel = 0; channel < channels; channel++)
2092 encoder->private_->integer_signal[channel][i] = buffer[k++];
2094 encoder->private_->current_sample_number = i;
2095 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2097 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2099 /* move unprocessed overread samples to beginnings of arrays */
2100 FLAC__ASSERT(i == blocksize+OVERREAD_);
2101 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2102 for(channel = 0; channel < channels; channel++)
2103 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2104 encoder->private_->current_sample_number = 1;
2106 } while(j < samples);
2112 /***********************************************************************
2114 * Private class methods
2116 ***********************************************************************/
2118 void set_defaults_(FLAC__StreamEncoder *encoder)
2120 FLAC__ASSERT(0 != encoder);
2122 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2123 encoder->protected_->verify = true;
2125 encoder->protected_->verify = false;
2127 encoder->protected_->streamable_subset = true;
2128 encoder->protected_->do_md5 = true;
2129 encoder->protected_->do_mid_side_stereo = false;
2130 encoder->protected_->loose_mid_side_stereo = false;
2131 encoder->protected_->channels = 2;
2132 encoder->protected_->bits_per_sample = 16;
2133 encoder->protected_->sample_rate = 44100;
2134 encoder->protected_->blocksize = 0;
2135 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2136 encoder->protected_->num_apodizations = 1;
2137 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2138 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2140 encoder->protected_->max_lpc_order = 0;
2141 encoder->protected_->qlp_coeff_precision = 0;
2142 encoder->protected_->do_qlp_coeff_prec_search = false;
2143 encoder->protected_->do_exhaustive_model_search = false;
2144 encoder->protected_->do_escape_coding = false;
2145 encoder->protected_->min_residual_partition_order = 0;
2146 encoder->protected_->max_residual_partition_order = 0;
2147 encoder->protected_->rice_parameter_search_dist = 0;
2148 encoder->protected_->total_samples_estimate = 0;
2149 encoder->protected_->metadata = 0;
2150 encoder->protected_->num_metadata_blocks = 0;
2152 encoder->private_->seek_table = 0;
2153 encoder->private_->disable_constant_subframes = false;
2154 encoder->private_->disable_fixed_subframes = false;
2155 encoder->private_->disable_verbatim_subframes = false;
2157 encoder->private_->is_ogg = false;
2159 encoder->private_->read_callback = 0;
2160 encoder->private_->write_callback = 0;
2161 encoder->private_->seek_callback = 0;
2162 encoder->private_->tell_callback = 0;
2163 encoder->private_->metadata_callback = 0;
2164 encoder->private_->progress_callback = 0;
2165 encoder->private_->client_data = 0;
2168 FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2172 void free_(FLAC__StreamEncoder *encoder)
2174 unsigned i, channel;
2176 FLAC__ASSERT(0 != encoder);
2177 if(encoder->protected_->metadata) {
2178 free(encoder->protected_->metadata);
2179 encoder->protected_->metadata = 0;
2180 encoder->protected_->num_metadata_blocks = 0;
2182 for(i = 0; i < encoder->protected_->channels; i++) {
2183 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2184 free(encoder->private_->integer_signal_unaligned[i]);
2185 encoder->private_->integer_signal_unaligned[i] = 0;
2187 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2188 if(0 != encoder->private_->real_signal_unaligned[i]) {
2189 free(encoder->private_->real_signal_unaligned[i]);
2190 encoder->private_->real_signal_unaligned[i] = 0;
2194 for(i = 0; i < 2; i++) {
2195 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2196 free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2197 encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2199 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2200 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2201 free(encoder->private_->real_signal_mid_side_unaligned[i]);
2202 encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2206 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2207 for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2208 if(0 != encoder->private_->window_unaligned[i]) {
2209 free(encoder->private_->window_unaligned[i]);
2210 encoder->private_->window_unaligned[i] = 0;
2213 if(0 != encoder->private_->windowed_signal_unaligned) {
2214 free(encoder->private_->windowed_signal_unaligned);
2215 encoder->private_->windowed_signal_unaligned = 0;
2218 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2219 for(i = 0; i < 2; i++) {
2220 if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2221 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2222 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2226 for(channel = 0; channel < 2; channel++) {
2227 for(i = 0; i < 2; i++) {
2228 if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2229 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2230 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2234 if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2235 free(encoder->private_->abs_residual_partition_sums_unaligned);
2236 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2238 if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2239 free(encoder->private_->raw_bits_per_partition_unaligned);
2240 encoder->private_->raw_bits_per_partition_unaligned = 0;
2242 if(encoder->protected_->verify) {
2243 for(i = 0; i < encoder->protected_->channels; i++) {
2244 if(0 != encoder->private_->verify.input_fifo.data[i]) {
2245 free(encoder->private_->verify.input_fifo.data[i]);
2246 encoder->private_->verify.input_fifo.data[i] = 0;
2250 FLAC__bitwriter_free(encoder->private_->frame);
2253 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2256 unsigned i, channel;
2258 FLAC__ASSERT(new_blocksize > 0);
2259 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2260 FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2262 /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2263 if(new_blocksize <= encoder->private_->input_capacity)
2268 /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
2269 * requires that the input arrays (in our case the integer signals)
2270 * have a buffer of up to 3 zeroes in front (at negative indices) for
2271 * alignment purposes; we use 4 in front to keep the data well-aligned.
2274 for(i = 0; ok && i < encoder->protected_->channels; i++) {
2275 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2276 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2277 encoder->private_->integer_signal[i] += 4;
2278 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2279 #if 0 /* @@@ currently unused */
2280 if(encoder->protected_->max_lpc_order > 0)
2281 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2285 for(i = 0; ok && i < 2; i++) {
2286 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]);
2287 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2288 encoder->private_->integer_signal_mid_side[i] += 4;
2289 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2290 #if 0 /* @@@ currently unused */
2291 if(encoder->protected_->max_lpc_order > 0)
2292 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]);
2296 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2297 if(ok && encoder->protected_->max_lpc_order > 0) {
2298 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2299 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2300 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2303 for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2304 for(i = 0; ok && i < 2; i++) {
2305 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2308 for(channel = 0; ok && channel < 2; channel++) {
2309 for(i = 0; ok && i < 2; i++) {
2310 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]);
2313 /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2314 /*@@@ 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) */
2315 ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2316 if(encoder->protected_->do_escape_coding)
2317 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2319 /* now adjust the windows if the blocksize has changed */
2320 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2321 if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2322 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2323 switch(encoder->protected_->apodizations[i].type) {
2324 case FLAC__APODIZATION_BARTLETT:
2325 FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2327 case FLAC__APODIZATION_BARTLETT_HANN:
2328 FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2330 case FLAC__APODIZATION_BLACKMAN:
2331 FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2333 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2334 FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2336 case FLAC__APODIZATION_CONNES:
2337 FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2339 case FLAC__APODIZATION_FLATTOP:
2340 FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2342 case FLAC__APODIZATION_GAUSS:
2343 FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2345 case FLAC__APODIZATION_HAMMING:
2346 FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2348 case FLAC__APODIZATION_HANN:
2349 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2351 case FLAC__APODIZATION_KAISER_BESSEL:
2352 FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2354 case FLAC__APODIZATION_NUTTALL:
2355 FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2357 case FLAC__APODIZATION_RECTANGLE:
2358 FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2360 case FLAC__APODIZATION_TRIANGLE:
2361 FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2363 case FLAC__APODIZATION_TUKEY:
2364 FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2366 case FLAC__APODIZATION_WELCH:
2367 FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2371 /* double protection */
2372 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2380 encoder->private_->input_capacity = new_blocksize;
2382 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2387 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2389 const FLAC__byte *buffer;
2392 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2394 if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2395 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2399 if(encoder->protected_->verify) {
2400 encoder->private_->verify.output.data = buffer;
2401 encoder->private_->verify.output.bytes = bytes;
2402 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2403 encoder->private_->verify.needs_magic_hack = true;
2406 if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2407 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2408 FLAC__bitwriter_clear(encoder->private_->frame);
2409 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2410 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2416 if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2417 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2418 FLAC__bitwriter_clear(encoder->private_->frame);
2419 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2423 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2424 FLAC__bitwriter_clear(encoder->private_->frame);
2427 encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2428 encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2434 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2436 FLAC__StreamEncoderWriteStatus status;
2437 FLAC__uint64 output_position = 0;
2439 /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2440 if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2441 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2442 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2446 * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2449 FLAC__MetadataType type = (buffer[0] & 0x7f);
2450 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2451 encoder->protected_->streaminfo_offset = output_position;
2452 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2453 encoder->protected_->seektable_offset = output_position;
2457 * Mark the current seek point if hit (if audio_offset == 0 that
2458 * means we're still writing metadata and haven't hit the first
2461 if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2462 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2463 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2464 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2465 FLAC__uint64 test_sample;
2467 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2468 test_sample = encoder->private_->seek_table->points[i].sample_number;
2469 if(test_sample > frame_last_sample) {
2472 else if(test_sample >= frame_first_sample) {
2473 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2474 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2475 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2476 encoder->private_->first_seekpoint_to_check++;
2477 /* DO NOT: "break;" and here's why:
2478 * The seektable template may contain more than one target
2479 * sample for any given frame; we will keep looping, generating
2480 * duplicate seekpoints for them, and we'll clean it up later,
2481 * just before writing the seektable back to the metadata.
2485 encoder->private_->first_seekpoint_to_check++;
2491 if(encoder->private_->is_ogg) {
2492 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2493 &encoder->protected_->ogg_encoder_aspect,
2497 encoder->private_->current_frame_number,
2499 (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2501 encoder->private_->client_data
2506 status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2508 if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2509 encoder->private_->bytes_written += bytes;
2510 encoder->private_->samples_written += samples;
2511 /* we keep a high watermark on the number of frames written because
2512 * when the encoder goes back to write metadata, 'current_frame'
2513 * will drop back to 0.
2515 encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2518 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2523 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2524 void update_metadata_(const FLAC__StreamEncoder *encoder)
2526 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2527 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2528 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2529 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2530 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2531 const unsigned bps = metadata->data.stream_info.bits_per_sample;
2532 FLAC__StreamEncoderSeekStatus seek_status;
2534 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2536 /* All this is based on intimate knowledge of the stream header
2537 * layout, but a change to the header format that would break this
2538 * would also break all streams encoded in the previous format.
2542 * Write MD5 signature
2545 const unsigned md5_offset =
2546 FLAC__STREAM_METADATA_HEADER_LENGTH +
2548 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2549 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2550 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2551 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2552 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2553 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2554 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2555 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2558 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2559 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2560 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2563 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2564 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2570 * Write total samples
2573 const unsigned total_samples_byte_offset =
2574 FLAC__STREAM_METADATA_HEADER_LENGTH +
2576 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2577 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2578 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2579 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2580 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2581 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2582 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2586 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2587 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2588 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2589 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2590 b[4] = (FLAC__byte)(samples & 0xFF);
2591 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) {
2592 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2593 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2596 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2597 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2603 * Write min/max framesize
2606 const unsigned min_framesize_offset =
2607 FLAC__STREAM_METADATA_HEADER_LENGTH +
2609 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2610 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2613 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2614 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2615 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2616 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2617 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2618 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2619 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) {
2620 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2621 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2624 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2625 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2633 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2636 FLAC__format_seektable_sort(encoder->private_->seek_table);
2638 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2640 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) {
2641 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2642 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2646 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2649 xx = encoder->private_->seek_table->points[i].sample_number;
2650 b[7] = (FLAC__byte)xx; xx >>= 8;
2651 b[6] = (FLAC__byte)xx; xx >>= 8;
2652 b[5] = (FLAC__byte)xx; xx >>= 8;
2653 b[4] = (FLAC__byte)xx; xx >>= 8;
2654 b[3] = (FLAC__byte)xx; xx >>= 8;
2655 b[2] = (FLAC__byte)xx; xx >>= 8;
2656 b[1] = (FLAC__byte)xx; xx >>= 8;
2657 b[0] = (FLAC__byte)xx; xx >>= 8;
2658 xx = encoder->private_->seek_table->points[i].stream_offset;
2659 b[15] = (FLAC__byte)xx; xx >>= 8;
2660 b[14] = (FLAC__byte)xx; xx >>= 8;
2661 b[13] = (FLAC__byte)xx; xx >>= 8;
2662 b[12] = (FLAC__byte)xx; xx >>= 8;
2663 b[11] = (FLAC__byte)xx; xx >>= 8;
2664 b[10] = (FLAC__byte)xx; xx >>= 8;
2665 b[9] = (FLAC__byte)xx; xx >>= 8;
2666 b[8] = (FLAC__byte)xx; xx >>= 8;
2667 x = encoder->private_->seek_table->points[i].frame_samples;
2668 b[17] = (FLAC__byte)x; x >>= 8;
2669 b[16] = (FLAC__byte)x; x >>= 8;
2670 if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2671 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2679 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2680 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2682 /* the # of bytes in the 1st packet that precede the STREAMINFO */
2683 static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2684 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2685 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2686 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2687 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2688 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2689 FLAC__STREAM_SYNC_LENGTH
2691 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2692 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2693 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2694 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2695 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2698 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2699 FLAC__ASSERT(0 != encoder->private_->seek_callback);
2701 /* Pre-check that client supports seeking, since we don't want the
2702 * ogg_helper code to ever have to deal with this condition.
2704 if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2707 /* All this is based on intimate knowledge of the stream header
2708 * layout, but a change to the header format that would break this
2709 * would also break all streams encoded in the previous format.
2713 ** Write STREAMINFO stats
2715 simple_ogg_page__init(&page);
2716 if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2717 simple_ogg_page__clear(&page);
2718 return; /* state already set */
2722 * Write MD5 signature
2725 const unsigned md5_offset =
2726 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2727 FLAC__STREAM_METADATA_HEADER_LENGTH +
2729 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2730 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2731 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2732 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2733 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2734 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2735 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2736 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2739 if(md5_offset + 16 > (unsigned)page.body_len) {
2740 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2741 simple_ogg_page__clear(&page);
2744 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2748 * Write total samples
2751 const unsigned total_samples_byte_offset =
2752 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2753 FLAC__STREAM_METADATA_HEADER_LENGTH +
2755 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2756 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2757 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2758 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2759 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2760 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2761 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2765 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2766 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2767 simple_ogg_page__clear(&page);
2770 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2771 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2772 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2773 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2774 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2775 b[4] = (FLAC__byte)(samples & 0xFF);
2776 memcpy(page.body + total_samples_byte_offset, b, 5);
2780 * Write min/max framesize
2783 const unsigned min_framesize_offset =
2784 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2785 FLAC__STREAM_METADATA_HEADER_LENGTH +
2787 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2788 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2791 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2792 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2793 simple_ogg_page__clear(&page);
2796 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2797 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2798 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2799 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2800 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2801 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2802 memcpy(page.body + min_framesize_offset, b, 6);
2804 if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2805 simple_ogg_page__clear(&page);
2806 return; /* state already set */
2808 simple_ogg_page__clear(&page);
2813 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2817 FLAC__format_seektable_sort(encoder->private_->seek_table);
2819 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2821 simple_ogg_page__init(&page);
2822 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2823 simple_ogg_page__clear(&page);
2824 return; /* state already set */
2827 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
2828 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2829 simple_ogg_page__clear(&page);
2833 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
2836 xx = encoder->private_->seek_table->points[i].sample_number;
2837 b[7] = (FLAC__byte)xx; xx >>= 8;
2838 b[6] = (FLAC__byte)xx; xx >>= 8;
2839 b[5] = (FLAC__byte)xx; xx >>= 8;
2840 b[4] = (FLAC__byte)xx; xx >>= 8;
2841 b[3] = (FLAC__byte)xx; xx >>= 8;
2842 b[2] = (FLAC__byte)xx; xx >>= 8;
2843 b[1] = (FLAC__byte)xx; xx >>= 8;
2844 b[0] = (FLAC__byte)xx; xx >>= 8;
2845 xx = encoder->private_->seek_table->points[i].stream_offset;
2846 b[15] = (FLAC__byte)xx; xx >>= 8;
2847 b[14] = (FLAC__byte)xx; xx >>= 8;
2848 b[13] = (FLAC__byte)xx; xx >>= 8;
2849 b[12] = (FLAC__byte)xx; xx >>= 8;
2850 b[11] = (FLAC__byte)xx; xx >>= 8;
2851 b[10] = (FLAC__byte)xx; xx >>= 8;
2852 b[9] = (FLAC__byte)xx; xx >>= 8;
2853 b[8] = (FLAC__byte)xx; xx >>= 8;
2854 x = encoder->private_->seek_table->points[i].frame_samples;
2855 b[17] = (FLAC__byte)x; x >>= 8;
2856 b[16] = (FLAC__byte)x; x >>= 8;
2860 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2861 simple_ogg_page__clear(&page);
2862 return; /* state already set */
2864 simple_ogg_page__clear(&page);
2869 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
2872 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2875 * Accumulate raw signal to the MD5 signature
2877 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)) {
2878 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2883 * Process the frame header and subframes into the frame bitbuffer
2885 if(!process_subframes_(encoder, is_fractional_block)) {
2886 /* the above function sets the state for us in case of an error */
2891 * Zero-pad the frame to a byte_boundary
2893 if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
2894 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2899 * CRC-16 the whole thing
2901 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2903 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
2904 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
2906 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2913 if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
2914 /* the above function sets the state for us in case of an error */
2919 * Get ready for the next frame
2921 encoder->private_->current_sample_number = 0;
2922 encoder->private_->current_frame_number++;
2923 encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
2928 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
2930 FLAC__FrameHeader frame_header;
2931 unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
2932 FLAC__bool do_independent, do_mid_side;
2935 * Calculate the min,max Rice partition orders
2937 if(is_fractional_block) {
2938 max_partition_order = 0;
2941 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
2942 max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
2944 min_partition_order = min(min_partition_order, max_partition_order);
2949 frame_header.blocksize = encoder->protected_->blocksize;
2950 frame_header.sample_rate = encoder->protected_->sample_rate;
2951 frame_header.channels = encoder->protected_->channels;
2952 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
2953 frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
2954 frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2955 frame_header.number.frame_number = encoder->private_->current_frame_number;
2958 * Figure out what channel assignments to try
2960 if(encoder->protected_->do_mid_side_stereo) {
2961 if(encoder->protected_->loose_mid_side_stereo) {
2962 if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
2963 do_independent = true;
2967 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
2968 do_mid_side = !do_independent;
2972 do_independent = true;
2977 do_independent = true;
2978 do_mid_side = false;
2981 FLAC__ASSERT(do_independent || do_mid_side);
2984 * Check for wasted bits; set effective bps for each subframe
2986 if(do_independent) {
2987 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2988 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
2989 encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
2990 encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
2994 FLAC__ASSERT(encoder->protected_->channels == 2);
2995 for(channel = 0; channel < 2; channel++) {
2996 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
2997 encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
2998 encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
3003 * First do a normal encoding pass of each independent channel
3005 if(do_independent) {
3006 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3010 min_partition_order,
3011 max_partition_order,
3013 encoder->private_->subframe_bps[channel],
3014 encoder->private_->integer_signal[channel],
3015 encoder->private_->subframe_workspace_ptr[channel],
3016 encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3017 encoder->private_->residual_workspace[channel],
3018 encoder->private_->best_subframe+channel,
3019 encoder->private_->best_subframe_bits+channel
3027 * Now do mid and side channels if requested
3030 FLAC__ASSERT(encoder->protected_->channels == 2);
3032 for(channel = 0; channel < 2; channel++) {
3036 min_partition_order,
3037 max_partition_order,
3039 encoder->private_->subframe_bps_mid_side[channel],
3040 encoder->private_->integer_signal_mid_side[channel],
3041 encoder->private_->subframe_workspace_ptr_mid_side[channel],
3042 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3043 encoder->private_->residual_workspace_mid_side[channel],
3044 encoder->private_->best_subframe_mid_side+channel,
3045 encoder->private_->best_subframe_bits_mid_side+channel
3053 * Compose the frame bitbuffer
3056 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3057 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3058 FLAC__ChannelAssignment channel_assignment;
3060 FLAC__ASSERT(encoder->protected_->channels == 2);
3062 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3063 channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3066 unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3070 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3071 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
3072 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
3073 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
3074 FLAC__ASSERT(do_independent && do_mid_side);
3076 /* We have to figure out which channel assignent results in the smallest frame */
3077 bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
3078 bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
3079 bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
3080 bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3082 channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3083 min_bits = bits[channel_assignment];
3084 for(ca = 1; ca <= 3; ca++) {
3085 if(bits[ca] < min_bits) {
3086 min_bits = bits[ca];
3087 channel_assignment = (FLAC__ChannelAssignment)ca;
3092 frame_header.channel_assignment = channel_assignment;
3094 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3095 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3099 switch(channel_assignment) {
3100 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3101 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3102 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3104 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3105 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3106 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3108 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3109 left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3110 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3112 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3113 left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3114 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3120 switch(channel_assignment) {
3121 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3122 left_bps = encoder->private_->subframe_bps [0];
3123 right_bps = encoder->private_->subframe_bps [1];
3125 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3126 left_bps = encoder->private_->subframe_bps [0];
3127 right_bps = encoder->private_->subframe_bps_mid_side[1];
3129 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3130 left_bps = encoder->private_->subframe_bps_mid_side[1];
3131 right_bps = encoder->private_->subframe_bps [1];
3133 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3134 left_bps = encoder->private_->subframe_bps_mid_side[0];
3135 right_bps = encoder->private_->subframe_bps_mid_side[1];
3141 /* note that encoder_add_subframe_ sets the state for us in case of an error */
3142 if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3144 if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3148 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3149 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3153 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3154 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)) {
3155 /* the above function sets the state for us in case of an error */
3161 if(encoder->protected_->loose_mid_side_stereo) {
3162 encoder->private_->loose_mid_side_stereo_frame_count++;
3163 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3164 encoder->private_->loose_mid_side_stereo_frame_count = 0;
3167 encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3172 FLAC__bool process_subframe_(
3173 FLAC__StreamEncoder *encoder,
3174 unsigned min_partition_order,
3175 unsigned max_partition_order,
3176 const FLAC__FrameHeader *frame_header,
3177 unsigned subframe_bps,
3178 const FLAC__int32 integer_signal[],
3179 FLAC__Subframe *subframe[2],
3180 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3181 FLAC__int32 *residual[2],
3182 unsigned *best_subframe,
3186 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3187 FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3189 FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3191 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3192 FLAC__double lpc_residual_bits_per_sample;
3193 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 */
3194 FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3195 unsigned min_lpc_order, max_lpc_order, lpc_order;
3196 unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3198 unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3199 unsigned rice_parameter;
3200 unsigned _candidate_bits, _best_bits;
3201 unsigned _best_subframe;
3202 /* only use RICE2 partitions if stream bps > 16 */
3203 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;
3205 FLAC__ASSERT(frame_header->blocksize > 0);
3207 /* verbatim subframe is the baseline against which we measure other compressed subframes */
3209 if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3210 _best_bits = UINT_MAX;
3212 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3214 if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3215 unsigned signal_is_constant = false;
3216 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);
3217 /* check for constant subframe */
3219 !encoder->private_->disable_constant_subframes &&
3220 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3221 fixed_residual_bits_per_sample[1] == 0.0
3223 fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3226 /* the above means it's possible all samples are the same value; now double-check it: */
3228 signal_is_constant = true;
3229 for(i = 1; i < frame_header->blocksize; i++) {
3230 if(integer_signal[0] != integer_signal[i]) {
3231 signal_is_constant = false;
3236 if(signal_is_constant) {
3237 _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3238 if(_candidate_bits < _best_bits) {
3239 _best_subframe = !_best_subframe;
3240 _best_bits = _candidate_bits;
3244 if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3246 if(encoder->protected_->do_exhaustive_model_search) {
3247 min_fixed_order = 0;
3248 max_fixed_order = FLAC__MAX_FIXED_ORDER;
3251 min_fixed_order = max_fixed_order = guess_fixed_order;
3253 if(max_fixed_order >= frame_header->blocksize)
3254 max_fixed_order = frame_header->blocksize - 1;
3255 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3256 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3257 if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3258 continue; /* don't even try */
3259 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 */
3261 if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3262 continue; /* don't even try */
3263 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 */
3265 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3266 if(rice_parameter >= rice_parameter_limit) {
3267 #ifdef DEBUG_VERBOSE
3268 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
3270 rice_parameter = rice_parameter_limit - 1;
3273 evaluate_fixed_subframe_(
3276 residual[!_best_subframe],
3277 encoder->private_->abs_residual_partition_sums,
3278 encoder->private_->raw_bits_per_partition,
3279 frame_header->blocksize,
3283 rice_parameter_limit,
3284 min_partition_order,
3285 max_partition_order,
3286 encoder->protected_->do_escape_coding,
3287 encoder->protected_->rice_parameter_search_dist,
3288 subframe[!_best_subframe],
3289 partitioned_rice_contents[!_best_subframe]
3291 if(_candidate_bits < _best_bits) {
3292 _best_subframe = !_best_subframe;
3293 _best_bits = _candidate_bits;
3298 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3300 if(encoder->protected_->max_lpc_order > 0) {
3301 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3302 max_lpc_order = frame_header->blocksize-1;
3304 max_lpc_order = encoder->protected_->max_lpc_order;
3305 if(max_lpc_order > 0) {
3307 for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3308 FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3309 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3310 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3311 if(autoc[0] != 0.0) {
3312 FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3313 if(encoder->protected_->do_exhaustive_model_search) {
3317 const unsigned guess_lpc_order =
3318 FLAC__lpc_compute_best_order(
3321 frame_header->blocksize,
3323 encoder->protected_->do_qlp_coeff_prec_search?
3324 FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
3325 encoder->protected_->qlp_coeff_precision
3328 min_lpc_order = max_lpc_order = guess_lpc_order;
3330 if(max_lpc_order >= frame_header->blocksize)
3331 max_lpc_order = frame_header->blocksize - 1;
3332 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
3333 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
3334 if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
3335 continue; /* don't even try */
3336 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
3337 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3338 if(rice_parameter >= rice_parameter_limit) {
3339 #ifdef DEBUG_VERBOSE
3340 fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
3342 rice_parameter = rice_parameter_limit - 1;
3344 if(encoder->protected_->do_qlp_coeff_prec_search) {
3345 min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
3346 /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
3347 if(subframe_bps <= 17) {
3348 max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
3349 max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
3352 max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
3355 min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
3357 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
3359 evaluate_lpc_subframe_(
3362 residual[!_best_subframe],
3363 encoder->private_->abs_residual_partition_sums,
3364 encoder->private_->raw_bits_per_partition,
3365 encoder->private_->lp_coeff[lpc_order-1],
3366 frame_header->blocksize,
3369 qlp_coeff_precision,
3371 rice_parameter_limit,
3372 min_partition_order,
3373 max_partition_order,
3374 encoder->protected_->do_escape_coding,
3375 encoder->protected_->rice_parameter_search_dist,
3376 subframe[!_best_subframe],
3377 partitioned_rice_contents[!_best_subframe]
3379 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
3380 if(_candidate_bits < _best_bits) {
3381 _best_subframe = !_best_subframe;
3382 _best_bits = _candidate_bits;
3391 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3395 /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3396 if(_best_bits == UINT_MAX) {
3397 FLAC__ASSERT(_best_subframe == 0);
3398 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3401 *best_subframe = _best_subframe;
3402 *best_bits = _best_bits;
3407 FLAC__bool add_subframe_(
3408 FLAC__StreamEncoder *encoder,
3410 unsigned subframe_bps,
3411 const FLAC__Subframe *subframe,
3412 FLAC__BitWriter *frame
3415 switch(subframe->type) {
3416 case FLAC__SUBFRAME_TYPE_CONSTANT:
3417 if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3418 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3422 case FLAC__SUBFRAME_TYPE_FIXED:
3423 if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3424 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3428 case FLAC__SUBFRAME_TYPE_LPC:
3429 if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3430 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3434 case FLAC__SUBFRAME_TYPE_VERBATIM:
3435 if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3436 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3447 #define SPOTCHECK_ESTIMATE 0
3448 #if SPOTCHECK_ESTIMATE
3449 static void spotcheck_subframe_estimate_(
3450 FLAC__StreamEncoder *encoder,
3452 unsigned subframe_bps,
3453 const FLAC__Subframe *subframe,
3458 FLAC__BitWriter *frame = FLAC__bitwriter_new();
3460 fprintf(stderr, "EST: can't allocate frame\n");
3463 if(!FLAC__bitwriter_init(frame)) {
3464 fprintf(stderr, "EST: can't init frame\n");
3467 ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
3470 const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
3471 if(estimate != actual)
3472 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);
3474 FLAC__bitwriter_delete(frame);
3478 unsigned evaluate_constant_subframe_(
3479 FLAC__StreamEncoder *encoder,
3480 const FLAC__int32 signal,
3482 unsigned subframe_bps,
3483 FLAC__Subframe *subframe
3487 subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3488 subframe->data.constant.value = signal;
3490 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
3492 #if SPOTCHECK_ESTIMATE
3493 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3495 (void)encoder, (void)blocksize;
3501 unsigned evaluate_fixed_subframe_(
3502 FLAC__StreamEncoder *encoder,
3503 const FLAC__int32 signal[],
3504 FLAC__int32 residual[],
3505 FLAC__uint64 abs_residual_partition_sums[],
3506 unsigned raw_bits_per_partition[],
3508 unsigned subframe_bps,
3510 unsigned rice_parameter,
3511 unsigned rice_parameter_limit,
3512 unsigned min_partition_order,
3513 unsigned max_partition_order,
3514 FLAC__bool do_escape_coding,
3515 unsigned rice_parameter_search_dist,
3516 FLAC__Subframe *subframe,
3517 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3520 unsigned i, residual_bits, estimate;
3521 const unsigned residual_samples = blocksize - order;
3523 FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3525 subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3527 subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3528 subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3529 subframe->data.fixed.residual = residual;
3532 find_best_partition_order_(
3535 abs_residual_partition_sums,
3536 raw_bits_per_partition,
3540 rice_parameter_limit,
3541 min_partition_order,
3542 max_partition_order,
3545 rice_parameter_search_dist,
3546 &subframe->data.fixed.entropy_coding_method
3549 subframe->data.fixed.order = order;
3550 for(i = 0; i < order; i++)
3551 subframe->data.fixed.warmup[i] = signal[i];
3553 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
3555 #if SPOTCHECK_ESTIMATE
3556 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3562 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3563 unsigned evaluate_lpc_subframe_(
3564 FLAC__StreamEncoder *encoder,
3565 const FLAC__int32 signal[],
3566 FLAC__int32 residual[],
3567 FLAC__uint64 abs_residual_partition_sums[],
3568 unsigned raw_bits_per_partition[],
3569 const FLAC__real lp_coeff[],
3571 unsigned subframe_bps,
3573 unsigned qlp_coeff_precision,
3574 unsigned rice_parameter,
3575 unsigned rice_parameter_limit,
3576 unsigned min_partition_order,
3577 unsigned max_partition_order,
3578 FLAC__bool do_escape_coding,
3579 unsigned rice_parameter_search_dist,
3580 FLAC__Subframe *subframe,
3581 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3584 FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
3585 unsigned i, residual_bits, estimate;
3586 int quantization, ret;
3587 const unsigned residual_samples = blocksize - order;
3589 /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3590 if(subframe_bps <= 16) {
3591 FLAC__ASSERT(order > 0);
3592 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3593 qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3596 ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3598 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3600 if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3601 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3602 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3604 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3606 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3608 subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3610 subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3611 subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3612 subframe->data.lpc.residual = residual;
3615 find_best_partition_order_(
3618 abs_residual_partition_sums,
3619 raw_bits_per_partition,
3623 rice_parameter_limit,
3624 min_partition_order,
3625 max_partition_order,
3628 rice_parameter_search_dist,
3629 &subframe->data.lpc.entropy_coding_method
3632 subframe->data.lpc.order = order;
3633 subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3634 subframe->data.lpc.quantization_level = quantization;
3635 memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3636 for(i = 0; i < order; i++)
3637 subframe->data.lpc.warmup[i] = signal[i];
3639 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;
3641 #if SPOTCHECK_ESTIMATE
3642 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3649 unsigned evaluate_verbatim_subframe_(
3650 FLAC__StreamEncoder *encoder,
3651 const FLAC__int32 signal[],
3653 unsigned subframe_bps,
3654 FLAC__Subframe *subframe
3659 subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3661 subframe->data.verbatim.data = signal;
3663 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
3665 #if SPOTCHECK_ESTIMATE
3666 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3674 unsigned find_best_partition_order_(
3675 FLAC__StreamEncoderPrivate *private_,
3676 const FLAC__int32 residual[],
3677 FLAC__uint64 abs_residual_partition_sums[],
3678 unsigned raw_bits_per_partition[],
3679 unsigned residual_samples,
3680 unsigned predictor_order,
3681 unsigned rice_parameter,
3682 unsigned rice_parameter_limit,
3683 unsigned min_partition_order,
3684 unsigned max_partition_order,
3686 FLAC__bool do_escape_coding,
3687 unsigned rice_parameter_search_dist,
3688 FLAC__EntropyCodingMethod *best_ecm
3691 unsigned residual_bits, best_residual_bits = 0;
3692 unsigned best_parameters_index = 0;
3693 unsigned best_partition_order = 0;
3694 const unsigned blocksize = residual_samples + predictor_order;
3696 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3697 min_partition_order = min(min_partition_order, max_partition_order);
3699 precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
3701 if(do_escape_coding)
3702 precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3705 int partition_order;
3708 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3710 set_partitioned_rice_(
3711 #ifdef EXACT_RICE_BITS_CALCULATION
3714 abs_residual_partition_sums+sum,
3715 raw_bits_per_partition+sum,
3719 rice_parameter_limit,
3720 rice_parameter_search_dist,
3721 (unsigned)partition_order,
3723 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3728 FLAC__ASSERT(best_residual_bits != 0);
3731 sum += 1u << partition_order;
3732 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3733 best_residual_bits = residual_bits;
3734 best_parameters_index = !best_parameters_index;
3735 best_partition_order = partition_order;
3740 best_ecm->data.partitioned_rice.order = best_partition_order;
3744 * We are allowed to de-const the pointer based on our special
3745 * knowledge; it is const to the outside world.
3747 FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
3750 /* save best parameters and raw_bits */
3751 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
3752 memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
3753 if(do_escape_coding)
3754 memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
3756 * Now need to check if the type should be changed to
3757 * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
3758 * size of the rice parameters.
3760 for(partition = 0; partition < (1u<<best_partition_order); partition++) {
3761 if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3762 best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
3768 return best_residual_bits;
3771 #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
3772 extern void precompute_partition_info_sums_32bit_asm_ia32_(
3773 const FLAC__int32 residual[],
3774 FLAC__uint64 abs_residual_partition_sums[],
3776 unsigned predictor_order,
3777 unsigned min_partition_order,
3778 unsigned max_partition_order
3782 void precompute_partition_info_sums_(
3783 const FLAC__int32 residual[],
3784 FLAC__uint64 abs_residual_partition_sums[],
3785 unsigned residual_samples,
3786 unsigned predictor_order,
3787 unsigned min_partition_order,
3788 unsigned max_partition_order,
3792 const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
3793 unsigned partitions = 1u << max_partition_order;
3795 FLAC__ASSERT(default_partition_samples > predictor_order);
3797 #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
3798 /* slightly pessimistic but still catches all common cases */
3799 /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
3800 if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
3801 precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
3806 /* first do max_partition_order */
3808 unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
3809 /* slightly pessimistic but still catches all common cases */
3810 /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
3811 if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
3812 FLAC__uint32 abs_residual_partition_sum;
3814 for(partition = residual_sample = 0; partition < partitions; partition++) {
3815 end += default_partition_samples;
3816 abs_residual_partition_sum = 0;
3817 for( ; residual_sample < end; residual_sample++)
3818 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3819 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3822 else { /* have to pessimistically use 64 bits for accumulator */
3823 FLAC__uint64 abs_residual_partition_sum;
3825 for(partition = residual_sample = 0; partition < partitions; partition++) {
3826 end += default_partition_samples;
3827 abs_residual_partition_sum = 0;
3828 for( ; residual_sample < end; residual_sample++)
3829 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3830 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3835 /* now merge partitions for lower orders */
3837 unsigned from_partition = 0, to_partition = partitions;
3838 int partition_order;
3839 for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
3842 for(i = 0; i < partitions; i++) {
3843 abs_residual_partition_sums[to_partition++] =
3844 abs_residual_partition_sums[from_partition ] +
3845 abs_residual_partition_sums[from_partition+1];
3846 from_partition += 2;
3852 void precompute_partition_info_escapes_(
3853 const FLAC__int32 residual[],
3854 unsigned raw_bits_per_partition[],
3855 unsigned residual_samples,
3856 unsigned predictor_order,
3857 unsigned min_partition_order,
3858 unsigned max_partition_order
3861 int partition_order;
3862 unsigned from_partition, to_partition = 0;
3863 const unsigned blocksize = residual_samples + predictor_order;
3865 /* first do max_partition_order */
3866 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3869 unsigned partition, partition_sample, partition_samples, residual_sample;
3870 const unsigned partitions = 1u << partition_order;
3871 const unsigned default_partition_samples = blocksize >> partition_order;
3873 FLAC__ASSERT(default_partition_samples > predictor_order);
3875 for(partition = residual_sample = 0; partition < partitions; partition++) {
3876 partition_samples = default_partition_samples;
3878 partition_samples -= predictor_order;
3880 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
3881 r = residual[residual_sample++];
3882 /* OPT: maybe faster: rmax |= r ^ (r>>31) */
3888 /* now we know all residual values are in the range [-rmax-1,rmax] */
3889 raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
3891 to_partition = partitions;
3892 break; /*@@@ yuck, should remove the 'for' loop instead */
3895 /* now merge partitions for lower orders */
3896 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
3899 const unsigned partitions = 1u << partition_order;
3900 for(i = 0; i < partitions; i++) {
3901 m = raw_bits_per_partition[from_partition];
3903 raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
3910 #ifdef EXACT_RICE_BITS_CALCULATION
3911 static FLaC__INLINE unsigned count_rice_bits_in_partition_(
3912 const unsigned rice_parameter,
3913 const unsigned partition_samples,
3914 const FLAC__int32 *residual
3917 unsigned i, partition_bits =
3918 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 */
3919 (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
3921 for(i = 0; i < partition_samples; i++)
3922 partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
3923 return partition_bits;
3926 static FLaC__INLINE unsigned count_rice_bits_in_partition_(
3927 const unsigned rice_parameter,
3928 const unsigned partition_samples,
3929 const FLAC__uint64 abs_residual_partition_sum
3933 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 */
3934 (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
3937 (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
3938 : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
3940 - (partition_samples >> 1)
3941 /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
3942 * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
3943 * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
3944 * So the subtraction term tries to guess how many extra bits were contributed.
3945 * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
3951 FLAC__bool set_partitioned_rice_(
3952 #ifdef EXACT_RICE_BITS_CALCULATION
3953 const FLAC__int32 residual[],
3955 const FLAC__uint64 abs_residual_partition_sums[],
3956 const unsigned raw_bits_per_partition[],
3957 const unsigned residual_samples,
3958 const unsigned predictor_order,
3959 const unsigned suggested_rice_parameter,
3960 const unsigned rice_parameter_limit,
3961 const unsigned rice_parameter_search_dist,
3962 const unsigned partition_order,
3963 const FLAC__bool search_for_escapes,
3964 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3968 unsigned rice_parameter, partition_bits;
3969 unsigned best_partition_bits, best_rice_parameter = 0;
3970 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
3971 unsigned *parameters, *raw_bits;
3972 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3973 unsigned min_rice_parameter, max_rice_parameter;
3975 (void)rice_parameter_search_dist;
3978 FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
3979 FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
3981 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
3982 parameters = partitioned_rice_contents->parameters;
3983 raw_bits = partitioned_rice_contents->raw_bits;
3985 if(partition_order == 0) {
3986 best_partition_bits = (unsigned)(-1);
3987 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3988 if(rice_parameter_search_dist) {
3989 if(suggested_rice_parameter < rice_parameter_search_dist)
3990 min_rice_parameter = 0;
3992 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
3993 max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
3994 if(max_rice_parameter >= rice_parameter_limit) {
3995 #ifdef DEBUG_VERBOSE
3996 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
3998 max_rice_parameter = rice_parameter_limit - 1;
4002 min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
4004 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4006 rice_parameter = suggested_rice_parameter;
4008 #ifdef EXACT_RICE_BITS_CALCULATION
4009 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
4011 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
4013 if(partition_bits < best_partition_bits) {
4014 best_rice_parameter = rice_parameter;
4015 best_partition_bits = partition_bits;
4017 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4020 if(search_for_escapes) {
4021 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;
4022 if(partition_bits <= best_partition_bits) {
4023 raw_bits[0] = raw_bits_per_partition[0];
4024 best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4025 best_partition_bits = partition_bits;
4030 parameters[0] = best_rice_parameter;
4031 bits_ += best_partition_bits;
4034 unsigned partition, residual_sample;
4035 unsigned partition_samples;
4036 FLAC__uint64 mean, k;
4037 const unsigned partitions = 1u << partition_order;
4038 for(partition = residual_sample = 0; partition < partitions; partition++) {
4039 partition_samples = (residual_samples+predictor_order) >> partition_order;
4040 if(partition == 0) {
4041 if(partition_samples <= predictor_order)
4044 partition_samples -= predictor_order;
4046 mean = abs_residual_partition_sums[partition];
4047 /* we are basically calculating the size in bits of the
4048 * average residual magnitude in the partition:
4049 * rice_parameter = floor(log2(mean/partition_samples))
4050 * 'mean' is not a good name for the variable, it is
4051 * actually the sum of magnitudes of all residual values
4052 * in the partition, so the actual mean is
4053 * mean/partition_samples
4055 for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
4057 if(rice_parameter >= rice_parameter_limit) {
4058 #ifdef DEBUG_VERBOSE
4059 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
4061 rice_parameter = rice_parameter_limit - 1;
4064 best_partition_bits = (unsigned)(-1);
4065 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4066 if(rice_parameter_search_dist) {
4067 if(rice_parameter < rice_parameter_search_dist)
4068 min_rice_parameter = 0;
4070 min_rice_parameter = rice_parameter - rice_parameter_search_dist;
4071 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
4072 if(max_rice_parameter >= rice_parameter_limit) {
4073 #ifdef DEBUG_VERBOSE
4074 fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
4076 max_rice_parameter = rice_parameter_limit - 1;
4080 min_rice_parameter = max_rice_parameter = rice_parameter;
4082 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4084 #ifdef EXACT_RICE_BITS_CALCULATION
4085 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
4087 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
4089 if(partition_bits < best_partition_bits) {
4090 best_rice_parameter = rice_parameter;
4091 best_partition_bits = partition_bits;
4093 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4096 if(search_for_escapes) {
4097 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;
4098 if(partition_bits <= best_partition_bits) {
4099 raw_bits[partition] = raw_bits_per_partition[partition];
4100 best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4101 best_partition_bits = partition_bits;
4104 raw_bits[partition] = 0;
4106 parameters[partition] = best_rice_parameter;
4107 bits_ += best_partition_bits;
4108 residual_sample += partition_samples;
4116 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
4121 for(i = 0; i < samples && !(x&1); i++)
4128 for(shift = 0; !(x&1); shift++)
4133 for(i = 0; i < samples; i++)
4134 signal[i] >>= shift;
4140 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4144 for(channel = 0; channel < channels; channel++)
4145 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
4147 fifo->tail += wide_samples;
4149 FLAC__ASSERT(fifo->tail <= fifo->size);
4152 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4155 unsigned sample, wide_sample;
4156 unsigned tail = fifo->tail;
4158 sample = input_offset * channels;
4159 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
4160 for(channel = 0; channel < channels; channel++)
4161 fifo->data[channel][tail] = input[sample++];
4166 FLAC__ASSERT(fifo->tail <= fifo->size);
4169 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4171 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4172 const size_t encoded_bytes = encoder->private_->verify.output.bytes;
4175 if(encoder->private_->verify.needs_magic_hack) {
4176 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
4177 *bytes = FLAC__STREAM_SYNC_LENGTH;
4178 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
4179 encoder->private_->verify.needs_magic_hack = false;
4182 if(encoded_bytes == 0) {
4184 * If we get here, a FIFO underflow has occurred,
4185 * which means there is a bug somewhere.
4188 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
4190 else if(encoded_bytes < *bytes)
4191 *bytes = encoded_bytes;
4192 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
4193 encoder->private_->verify.output.data += *bytes;
4194 encoder->private_->verify.output.bytes -= *bytes;
4197 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
4200 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
4202 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
4204 const unsigned channels = frame->header.channels;
4205 const unsigned blocksize = frame->header.blocksize;
4206 const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
4210 for(channel = 0; channel < channels; channel++) {
4211 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
4212 unsigned i, sample = 0;
4213 FLAC__int32 expect = 0, got = 0;
4215 for(i = 0; i < blocksize; i++) {
4216 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
4218 expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
4219 got = (FLAC__int32)buffer[channel][i];
4223 FLAC__ASSERT(i < blocksize);
4224 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
4225 encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
4226 encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
4227 encoder->private_->verify.error_stats.channel = channel;
4228 encoder->private_->verify.error_stats.sample = sample;
4229 encoder->private_->verify.error_stats.expected = expect;
4230 encoder->private_->verify.error_stats.got = got;
4231 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
4232 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
4235 /* dequeue the frame from the fifo */
4236 encoder->private_->verify.input_fifo.tail -= blocksize;
4237 FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
4238 for(channel = 0; channel < channels; channel++)
4239 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]));
4240 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4243 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4245 (void)decoder, (void)metadata, (void)client_data;
4248 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4250 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4251 (void)decoder, (void)status;
4252 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4255 FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4259 *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
4261 if (feof(encoder->private_->file))
4262 return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
4263 else if (ferror(encoder->private_->file))
4264 return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
4266 return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
4269 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4273 if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
4274 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4276 return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4279 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4285 offset = ftello(encoder->private_->file);
4288 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4291 *absolute_byte_offset = (FLAC__uint64)offset;
4292 return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4296 #ifdef FLAC__VALGRIND_TESTING
4297 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4299 size_t ret = fwrite(ptr, size, nmemb, stream);
4305 #define local__fwrite fwrite
4308 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
4310 (void)client_data, (void)current_frame;
4312 if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4313 FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
4315 /* We would like to be able to use 'samples > 0' in the
4316 * clause here but currently because of the nature of our
4317 * Ogg writing implementation, 'samples' is always 0 (see
4318 * ogg_encoder_aspect.c). The downside is extra progress
4321 encoder->private_->is_ogg? true :
4326 /* NOTE: We have to add +bytes, +samples, and +1 to the stats
4327 * because at this point in the callback chain, the stats
4328 * have not been updated. Only after we return and control
4329 * gets back to write_frame_() are the stats updated
4331 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);
4333 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4336 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4340 * This will forcibly set stdout to binary mode (for OSes that require it)
4342 FILE *get_binary_stdout_(void)
4344 /* if something breaks here it is probably due to the presence or
4345 * absence of an underscore before the identifiers 'setmode',
4346 * 'fileno', and/or 'O_BINARY'; check your system header files.
4348 #if defined _MSC_VER || defined __MINGW32__
4349 _setmode(_fileno(stdout), _O_BINARY);
4350 #elif defined __CYGWIN__
4351 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4352 setmode(_fileno(stdout), _O_BINARY);
4353 #elif defined __EMX__
4354 setmode(fileno(stdout), O_BINARY);