1 /* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008,2009 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] */
59 #include "FLAC/assert.h"
60 #include "FLAC/stream_decoder.h"
61 #include "share/alloc.h"
62 #include "protected/stream_encoder.h"
63 #include "private/bitwriter.h"
64 #include "private/bitmath.h"
65 #include "private/crc.h"
66 #include "private/cpu.h"
67 #include "private/fixed.h"
68 #include "private/format.h"
69 #include "private/lpc.h"
70 #include "private/md5.h"
71 #include "private/memory.h"
73 #include "private/ogg_helper.h"
74 #include "private/ogg_mapping.h"
76 #include "private/stream_encoder_framing.h"
77 #include "private/window.h"
86 #define min(x,y) ((x)<(y)?(x):(y))
91 #define max(x,y) ((x)>(y)?(x):(y))
93 /* Exact Rice codeword length calculation is off by default. The simple
94 * (and fast) estimation (of how many bits a residual value will be
95 * encoded with) in this encoder is very good, almost always yielding
96 * compression within 0.1% of exact calculation.
98 #undef EXACT_RICE_BITS_CALCULATION
99 /* Rice parameter searching is off by default. The simple (and fast)
100 * parameter estimation in this encoder is very good, almost always
101 * yielding compression within 0.1% of the optimal parameters.
103 #undef ENABLE_RICE_PARAMETER_SEARCH
107 FLAC__int32 *data[FLAC__MAX_CHANNELS];
108 unsigned size; /* of each data[] in samples */
113 const FLAC__byte *data;
119 ENCODER_IN_MAGIC = 0,
120 ENCODER_IN_METADATA = 1,
124 static struct CompressionLevels {
125 FLAC__bool do_mid_side_stereo;
126 FLAC__bool loose_mid_side_stereo;
127 unsigned max_lpc_order;
128 unsigned qlp_coeff_precision;
129 FLAC__bool do_qlp_coeff_prec_search;
130 FLAC__bool do_escape_coding;
131 FLAC__bool do_exhaustive_model_search;
132 unsigned min_residual_partition_order;
133 unsigned max_residual_partition_order;
134 unsigned rice_parameter_search_dist;
135 } compression_levels_[] = {
136 { false, false, 0, 0, false, false, false, 0, 3, 0 },
137 { true , true , 0, 0, false, false, false, 0, 3, 0 },
138 { true , false, 0, 0, false, false, false, 0, 3, 0 },
139 { false, false, 6, 0, false, false, false, 0, 4, 0 },
140 { true , true , 8, 0, false, false, false, 0, 4, 0 },
141 { true , false, 8, 0, false, false, false, 0, 5, 0 },
142 { true , false, 8, 0, false, false, false, 0, 6, 0 },
143 { true , false, 8, 0, false, false, true , 0, 6, 0 },
144 { true , false, 12, 0, false, false, true , 0, 6, 0 }
148 /***********************************************************************
150 * Private class method prototypes
152 ***********************************************************************/
154 static void set_defaults_(FLAC__StreamEncoder *encoder);
155 static void free_(FLAC__StreamEncoder *encoder);
156 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
157 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
158 static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
159 static void update_metadata_(const FLAC__StreamEncoder *encoder);
161 static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
163 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
164 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
166 static FLAC__bool process_subframe_(
167 FLAC__StreamEncoder *encoder,
168 unsigned min_partition_order,
169 unsigned max_partition_order,
170 const FLAC__FrameHeader *frame_header,
171 unsigned subframe_bps,
172 const FLAC__int32 integer_signal[],
173 FLAC__Subframe *subframe[2],
174 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
175 FLAC__int32 *residual[2],
176 unsigned *best_subframe,
180 static FLAC__bool add_subframe_(
181 FLAC__StreamEncoder *encoder,
183 unsigned subframe_bps,
184 const FLAC__Subframe *subframe,
185 FLAC__BitWriter *frame
188 static unsigned evaluate_constant_subframe_(
189 FLAC__StreamEncoder *encoder,
190 const FLAC__int32 signal,
192 unsigned subframe_bps,
193 FLAC__Subframe *subframe
196 static unsigned evaluate_fixed_subframe_(
197 FLAC__StreamEncoder *encoder,
198 const FLAC__int32 signal[],
199 FLAC__int32 residual[],
200 FLAC__uint64 abs_residual_partition_sums[],
201 unsigned raw_bits_per_partition[],
203 unsigned subframe_bps,
205 unsigned rice_parameter,
206 unsigned rice_parameter_limit,
207 unsigned min_partition_order,
208 unsigned max_partition_order,
209 FLAC__bool do_escape_coding,
210 unsigned rice_parameter_search_dist,
211 FLAC__Subframe *subframe,
212 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
215 #ifndef FLAC__INTEGER_ONLY_LIBRARY
216 static unsigned evaluate_lpc_subframe_(
217 FLAC__StreamEncoder *encoder,
218 const FLAC__int32 signal[],
219 FLAC__int32 residual[],
220 FLAC__uint64 abs_residual_partition_sums[],
221 unsigned raw_bits_per_partition[],
222 const FLAC__real lp_coeff[],
224 unsigned subframe_bps,
226 unsigned qlp_coeff_precision,
227 unsigned rice_parameter,
228 unsigned rice_parameter_limit,
229 unsigned min_partition_order,
230 unsigned max_partition_order,
231 FLAC__bool do_escape_coding,
232 unsigned rice_parameter_search_dist,
233 FLAC__Subframe *subframe,
234 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
238 static unsigned evaluate_verbatim_subframe_(
239 FLAC__StreamEncoder *encoder,
240 const FLAC__int32 signal[],
242 unsigned subframe_bps,
243 FLAC__Subframe *subframe
246 static unsigned find_best_partition_order_(
247 struct FLAC__StreamEncoderPrivate *private_,
248 const FLAC__int32 residual[],
249 FLAC__uint64 abs_residual_partition_sums[],
250 unsigned raw_bits_per_partition[],
251 unsigned residual_samples,
252 unsigned predictor_order,
253 unsigned rice_parameter,
254 unsigned rice_parameter_limit,
255 unsigned min_partition_order,
256 unsigned max_partition_order,
258 FLAC__bool do_escape_coding,
259 unsigned rice_parameter_search_dist,
260 FLAC__EntropyCodingMethod *best_ecm
263 static void precompute_partition_info_sums_(
264 const FLAC__int32 residual[],
265 FLAC__uint64 abs_residual_partition_sums[],
266 unsigned residual_samples,
267 unsigned predictor_order,
268 unsigned min_partition_order,
269 unsigned max_partition_order,
273 static void precompute_partition_info_escapes_(
274 const FLAC__int32 residual[],
275 unsigned raw_bits_per_partition[],
276 unsigned residual_samples,
277 unsigned predictor_order,
278 unsigned min_partition_order,
279 unsigned max_partition_order
282 static FLAC__bool set_partitioned_rice_(
283 #ifdef EXACT_RICE_BITS_CALCULATION
284 const FLAC__int32 residual[],
286 const FLAC__uint64 abs_residual_partition_sums[],
287 const unsigned raw_bits_per_partition[],
288 const unsigned residual_samples,
289 const unsigned predictor_order,
290 const unsigned suggested_rice_parameter,
291 const unsigned rice_parameter_limit,
292 const unsigned rice_parameter_search_dist,
293 const unsigned partition_order,
294 const FLAC__bool search_for_escapes,
295 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
299 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
301 /* verify-related routines: */
302 static void append_to_verify_fifo_(
303 verify_input_fifo *fifo,
304 const FLAC__int32 * const input[],
305 unsigned input_offset,
307 unsigned wide_samples
310 static void append_to_verify_fifo_interleaved_(
311 verify_input_fifo *fifo,
312 const FLAC__int32 input[],
313 unsigned input_offset,
315 unsigned wide_samples
318 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
319 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
320 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
321 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
323 static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
324 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
325 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
326 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);
327 static FILE *get_binary_stdout_(void);
330 /***********************************************************************
334 ***********************************************************************/
336 typedef struct FLAC__StreamEncoderPrivate {
337 unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
338 FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
339 FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
340 #ifndef FLAC__INTEGER_ONLY_LIBRARY
341 FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
342 FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
343 FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
344 FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
346 unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
347 unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
348 FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
349 FLAC__int32 *residual_workspace_mid_side[2][2];
350 FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
351 FLAC__Subframe subframe_workspace_mid_side[2][2];
352 FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
353 FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
354 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
355 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
356 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
357 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
358 unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
359 unsigned best_subframe_mid_side[2];
360 unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
361 unsigned best_subframe_bits_mid_side[2];
362 FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
363 unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
364 FLAC__BitWriter *frame; /* the current frame being worked on */
365 unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
366 unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
367 FLAC__ChannelAssignment last_channel_assignment;
368 FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
369 FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
370 unsigned current_sample_number;
371 unsigned current_frame_number;
372 FLAC__MD5Context md5context;
373 FLAC__CPUInfo cpuinfo;
374 #ifndef FLAC__INTEGER_ONLY_LIBRARY
375 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
377 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
379 #ifndef FLAC__INTEGER_ONLY_LIBRARY
380 void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
381 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[]);
382 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[]);
383 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[]);
385 FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
386 FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
387 FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
388 FLAC__bool disable_constant_subframes;
389 FLAC__bool disable_fixed_subframes;
390 FLAC__bool disable_verbatim_subframes;
394 FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
395 FLAC__StreamEncoderSeekCallback seek_callback;
396 FLAC__StreamEncoderTellCallback tell_callback;
397 FLAC__StreamEncoderWriteCallback write_callback;
398 FLAC__StreamEncoderMetadataCallback metadata_callback;
399 FLAC__StreamEncoderProgressCallback progress_callback;
401 unsigned first_seekpoint_to_check;
402 FILE *file; /* only used when encoding to a file */
403 FLAC__uint64 bytes_written;
404 FLAC__uint64 samples_written;
405 unsigned frames_written;
406 unsigned total_frames_estimate;
407 /* unaligned (original) pointers to allocated data */
408 FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
409 FLAC__int32 *integer_signal_mid_side_unaligned[2];
410 #ifndef FLAC__INTEGER_ONLY_LIBRARY
411 FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
412 FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
413 FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
414 FLAC__real *windowed_signal_unaligned;
416 FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
417 FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
418 FLAC__uint64 *abs_residual_partition_sums_unaligned;
419 unsigned *raw_bits_per_partition_unaligned;
421 * These fields have been moved here from private function local
422 * declarations merely to save stack space during encoding.
424 #ifndef FLAC__INTEGER_ONLY_LIBRARY
425 FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
427 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
429 * The data for the verify section
432 FLAC__StreamDecoder *decoder;
433 EncoderStateHint state_hint;
434 FLAC__bool needs_magic_hack;
435 verify_input_fifo input_fifo;
436 verify_output output;
438 FLAC__uint64 absolute_sample;
439 unsigned frame_number;
442 FLAC__int32 expected;
446 FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
447 } FLAC__StreamEncoderPrivate;
449 /***********************************************************************
451 * Public static class data
453 ***********************************************************************/
455 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
456 "FLAC__STREAM_ENCODER_OK",
457 "FLAC__STREAM_ENCODER_UNINITIALIZED",
458 "FLAC__STREAM_ENCODER_OGG_ERROR",
459 "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
460 "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
461 "FLAC__STREAM_ENCODER_CLIENT_ERROR",
462 "FLAC__STREAM_ENCODER_IO_ERROR",
463 "FLAC__STREAM_ENCODER_FRAMING_ERROR",
464 "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
467 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
468 "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
469 "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
470 "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
471 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
472 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
473 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
474 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
475 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
476 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
477 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
478 "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
479 "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
480 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
481 "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
484 FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
485 "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
486 "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
487 "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
488 "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
491 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
492 "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
493 "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
496 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
497 "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
498 "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
499 "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
502 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
503 "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
504 "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
505 "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
508 /* Number of samples that will be overread to watch for end of stream. By
509 * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
510 * always try to read blocksize+1 samples before encoding a block, so that
511 * even if the stream has a total sample count that is an integral multiple
512 * of the blocksize, we will still notice when we are encoding the last
513 * block. This is needed, for example, to correctly set the end-of-stream
514 * marker in Ogg FLAC.
516 * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
517 * not really any reason to change it.
519 static const unsigned OVERREAD_ = 1;
521 /***********************************************************************
523 * Class constructor/destructor
526 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
528 FLAC__StreamEncoder *encoder;
531 FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
533 encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
538 encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
539 if(encoder->protected_ == 0) {
544 encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
545 if(encoder->private_ == 0) {
546 free(encoder->protected_);
551 encoder->private_->frame = FLAC__bitwriter_new();
552 if(encoder->private_->frame == 0) {
553 free(encoder->private_);
554 free(encoder->protected_);
559 encoder->private_->file = 0;
561 set_defaults_(encoder);
563 encoder->private_->is_being_deleted = false;
565 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
566 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
567 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
569 for(i = 0; i < 2; i++) {
570 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
571 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
573 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
574 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
575 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
577 for(i = 0; i < 2; i++) {
578 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
579 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
582 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
583 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
584 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
586 for(i = 0; i < 2; i++) {
587 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
588 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
590 for(i = 0; i < 2; i++)
591 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
593 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
598 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
602 FLAC__ASSERT(0 != encoder);
603 FLAC__ASSERT(0 != encoder->protected_);
604 FLAC__ASSERT(0 != encoder->private_);
605 FLAC__ASSERT(0 != encoder->private_->frame);
607 encoder->private_->is_being_deleted = true;
609 (void)FLAC__stream_encoder_finish(encoder);
611 if(0 != encoder->private_->verify.decoder)
612 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
614 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
615 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
616 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
618 for(i = 0; i < 2; i++) {
619 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
620 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
622 for(i = 0; i < 2; i++)
623 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
625 FLAC__bitwriter_delete(encoder->private_->frame);
626 free(encoder->private_);
627 free(encoder->protected_);
631 /***********************************************************************
633 * Public class methods
635 ***********************************************************************/
637 static FLAC__StreamEncoderInitStatus init_stream_internal_(
638 FLAC__StreamEncoder *encoder,
639 FLAC__StreamEncoderReadCallback read_callback,
640 FLAC__StreamEncoderWriteCallback write_callback,
641 FLAC__StreamEncoderSeekCallback seek_callback,
642 FLAC__StreamEncoderTellCallback tell_callback,
643 FLAC__StreamEncoderMetadataCallback metadata_callback,
649 FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
651 FLAC__ASSERT(0 != encoder);
653 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
654 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
658 return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
661 if(0 == write_callback || (seek_callback && 0 == tell_callback))
662 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
664 if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
665 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
667 if(encoder->protected_->channels != 2) {
668 encoder->protected_->do_mid_side_stereo = false;
669 encoder->protected_->loose_mid_side_stereo = false;
671 else if(!encoder->protected_->do_mid_side_stereo)
672 encoder->protected_->loose_mid_side_stereo = false;
674 if(encoder->protected_->bits_per_sample >= 32)
675 encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
677 if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
678 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
680 if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
681 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
683 if(encoder->protected_->blocksize == 0) {
684 if(encoder->protected_->max_lpc_order == 0)
685 encoder->protected_->blocksize = 1152;
687 encoder->protected_->blocksize = 4096;
690 if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
691 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
693 if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
694 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
696 if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
697 return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
699 if(encoder->protected_->qlp_coeff_precision == 0) {
700 if(encoder->protected_->bits_per_sample < 16) {
701 /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
702 /* @@@ until then we'll make a guess */
703 encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
705 else if(encoder->protected_->bits_per_sample == 16) {
706 if(encoder->protected_->blocksize <= 192)
707 encoder->protected_->qlp_coeff_precision = 7;
708 else if(encoder->protected_->blocksize <= 384)
709 encoder->protected_->qlp_coeff_precision = 8;
710 else if(encoder->protected_->blocksize <= 576)
711 encoder->protected_->qlp_coeff_precision = 9;
712 else if(encoder->protected_->blocksize <= 1152)
713 encoder->protected_->qlp_coeff_precision = 10;
714 else if(encoder->protected_->blocksize <= 2304)
715 encoder->protected_->qlp_coeff_precision = 11;
716 else if(encoder->protected_->blocksize <= 4608)
717 encoder->protected_->qlp_coeff_precision = 12;
719 encoder->protected_->qlp_coeff_precision = 13;
722 if(encoder->protected_->blocksize <= 384)
723 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
724 else if(encoder->protected_->blocksize <= 1152)
725 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
727 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
729 FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
731 else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
732 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
734 if(encoder->protected_->streamable_subset) {
735 if(!FLAC__format_blocksize_is_subset(encoder->protected_->blocksize, encoder->protected_->sample_rate))
736 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
737 if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
738 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
740 encoder->protected_->bits_per_sample != 8 &&
741 encoder->protected_->bits_per_sample != 12 &&
742 encoder->protected_->bits_per_sample != 16 &&
743 encoder->protected_->bits_per_sample != 20 &&
744 encoder->protected_->bits_per_sample != 24
746 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
747 if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
748 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
750 encoder->protected_->sample_rate <= 48000 &&
752 encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
753 encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
756 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
760 if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
761 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
762 if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
763 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
766 /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
767 if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
769 for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
770 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
771 FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
773 encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
774 encoder->protected_->metadata[0] = vc;
780 /* keep track of any SEEKTABLE block */
781 if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
783 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
784 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
785 encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
786 break; /* take only the first one */
791 /* validate metadata */
792 if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
793 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
794 metadata_has_seektable = false;
795 metadata_has_vorbis_comment = false;
796 metadata_picture_has_type1 = false;
797 metadata_picture_has_type2 = false;
798 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
799 const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
800 if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
801 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
802 else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
803 if(metadata_has_seektable) /* only one is allowed */
804 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
805 metadata_has_seektable = true;
806 if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
807 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
809 else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
810 if(metadata_has_vorbis_comment) /* only one is allowed */
811 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
812 metadata_has_vorbis_comment = true;
814 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
815 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
816 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
818 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
819 if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
820 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
821 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
822 if(metadata_picture_has_type1) /* there should only be 1 per stream */
823 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
824 metadata_picture_has_type1 = true;
825 /* standard icon must be 32x32 pixel PNG */
827 m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
829 (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
830 m->data.picture.width != 32 ||
831 m->data.picture.height != 32
834 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
836 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
837 if(metadata_picture_has_type2) /* there should only be 1 per stream */
838 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
839 metadata_picture_has_type2 = true;
844 encoder->private_->input_capacity = 0;
845 for(i = 0; i < encoder->protected_->channels; i++) {
846 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
847 #ifndef FLAC__INTEGER_ONLY_LIBRARY
848 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
851 for(i = 0; i < 2; i++) {
852 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
853 #ifndef FLAC__INTEGER_ONLY_LIBRARY
854 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
857 #ifndef FLAC__INTEGER_ONLY_LIBRARY
858 for(i = 0; i < encoder->protected_->num_apodizations; i++)
859 encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
860 encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
862 for(i = 0; i < encoder->protected_->channels; i++) {
863 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
864 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
865 encoder->private_->best_subframe[i] = 0;
867 for(i = 0; i < 2; i++) {
868 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
869 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
870 encoder->private_->best_subframe_mid_side[i] = 0;
872 encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
873 encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
874 #ifndef FLAC__INTEGER_ONLY_LIBRARY
875 encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
877 /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
878 /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply÷ by hand */
879 FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
880 FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
881 FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
882 FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
883 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);
885 if(encoder->private_->loose_mid_side_stereo_frames == 0)
886 encoder->private_->loose_mid_side_stereo_frames = 1;
887 encoder->private_->loose_mid_side_stereo_frame_count = 0;
888 encoder->private_->current_sample_number = 0;
889 encoder->private_->current_frame_number = 0;
891 encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
892 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? */
893 encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
896 * get the CPU info and set the function pointers
898 FLAC__cpu_info(&encoder->private_->cpuinfo);
899 /* first default to the non-asm routines */
900 #ifndef FLAC__INTEGER_ONLY_LIBRARY
901 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
903 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
904 #ifndef FLAC__INTEGER_ONLY_LIBRARY
905 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
906 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
907 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
909 /* now override with asm where appropriate */
910 #ifndef FLAC__INTEGER_ONLY_LIBRARY
911 # ifndef FLAC__NO_ASM
912 if(encoder->private_->cpuinfo.use_asm) {
913 # ifdef FLAC__CPU_IA32
914 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
915 # ifdef FLAC__HAS_NASM
916 if(encoder->private_->cpuinfo.data.ia32.sse) {
917 if(encoder->protected_->max_lpc_order < 4)
918 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
919 else if(encoder->protected_->max_lpc_order < 8)
920 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
921 else if(encoder->protected_->max_lpc_order < 12)
922 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
924 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
926 else if(encoder->private_->cpuinfo.data.ia32._3dnow)
927 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
929 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
930 if(encoder->private_->cpuinfo.data.ia32.mmx) {
931 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
932 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
935 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
936 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
938 if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
939 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
940 # endif /* FLAC__HAS_NASM */
941 # endif /* FLAC__CPU_IA32 */
943 # endif /* !FLAC__NO_ASM */
944 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
945 /* finally override based on wide-ness if necessary */
946 if(encoder->private_->use_wide_by_block) {
947 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
950 /* set state to OK; from here on, errors are fatal and we'll override the state then */
951 encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
954 encoder->private_->is_ogg = is_ogg;
955 if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
956 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
957 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
961 encoder->private_->read_callback = read_callback;
962 encoder->private_->write_callback = write_callback;
963 encoder->private_->seek_callback = seek_callback;
964 encoder->private_->tell_callback = tell_callback;
965 encoder->private_->metadata_callback = metadata_callback;
966 encoder->private_->client_data = client_data;
968 if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
969 /* the above function sets the state for us in case of an error */
970 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
973 if(!FLAC__bitwriter_init(encoder->private_->frame)) {
974 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
975 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
979 * Set up the verify stuff if necessary
981 if(encoder->protected_->verify) {
983 * First, set up the fifo which will hold the
984 * original signal to compare against
986 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
987 for(i = 0; i < encoder->protected_->channels; i++) {
988 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))) {
989 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
990 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
993 encoder->private_->verify.input_fifo.tail = 0;
996 * Now set up a stream decoder for verification
998 if(0 == encoder->private_->verify.decoder) {
999 encoder->private_->verify.decoder = FLAC__stream_decoder_new();
1000 if(0 == encoder->private_->verify.decoder) {
1001 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1002 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1006 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) {
1007 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1008 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1011 encoder->private_->verify.error_stats.absolute_sample = 0;
1012 encoder->private_->verify.error_stats.frame_number = 0;
1013 encoder->private_->verify.error_stats.channel = 0;
1014 encoder->private_->verify.error_stats.sample = 0;
1015 encoder->private_->verify.error_stats.expected = 0;
1016 encoder->private_->verify.error_stats.got = 0;
1019 * These must be done before we write any metadata, because that
1020 * calls the write_callback, which uses these values.
1022 encoder->private_->first_seekpoint_to_check = 0;
1023 encoder->private_->samples_written = 0;
1024 encoder->protected_->streaminfo_offset = 0;
1025 encoder->protected_->seektable_offset = 0;
1026 encoder->protected_->audio_offset = 0;
1029 * write the stream header
1031 if(encoder->protected_->verify)
1032 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1033 if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1034 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1035 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1037 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1038 /* the above function sets the state for us in case of an error */
1039 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1043 * write the STREAMINFO metadata block
1045 if(encoder->protected_->verify)
1046 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1047 encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1048 encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1049 encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1050 encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1051 encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1052 encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1053 encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1054 encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1055 encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1056 encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1057 encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1058 memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1059 if(encoder->protected_->do_md5)
1060 FLAC__MD5Init(&encoder->private_->md5context);
1061 if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1062 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1063 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1065 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1066 /* the above function sets the state for us in case of an error */
1067 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1071 * Now that the STREAMINFO block is written, we can init this to an
1072 * absurdly-high value...
1074 encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1075 /* ... and clear this to 0 */
1076 encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1079 * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1080 * if not, we will write an empty one (FLAC__add_metadata_block()
1081 * automatically supplies the vendor string).
1083 * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1084 * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
1085 * true it will have already insured that the metadata list is properly
1088 if(!metadata_has_vorbis_comment) {
1089 FLAC__StreamMetadata vorbis_comment;
1090 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1091 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1092 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1093 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1094 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1095 vorbis_comment.data.vorbis_comment.num_comments = 0;
1096 vorbis_comment.data.vorbis_comment.comments = 0;
1097 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1098 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1099 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1101 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1102 /* the above function sets the state for us in case of an error */
1103 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1108 * write the user's metadata blocks
1110 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1111 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1112 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1113 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1114 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1116 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1117 /* the above function sets the state for us in case of an error */
1118 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1122 /* now that all the metadata is written, we save the stream offset */
1123 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 */
1124 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1125 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1128 if(encoder->protected_->verify)
1129 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1131 return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1134 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1135 FLAC__StreamEncoder *encoder,
1136 FLAC__StreamEncoderWriteCallback write_callback,
1137 FLAC__StreamEncoderSeekCallback seek_callback,
1138 FLAC__StreamEncoderTellCallback tell_callback,
1139 FLAC__StreamEncoderMetadataCallback metadata_callback,
1143 return init_stream_internal_(
1145 /*read_callback=*/0,
1155 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1156 FLAC__StreamEncoder *encoder,
1157 FLAC__StreamEncoderReadCallback read_callback,
1158 FLAC__StreamEncoderWriteCallback write_callback,
1159 FLAC__StreamEncoderSeekCallback seek_callback,
1160 FLAC__StreamEncoderTellCallback tell_callback,
1161 FLAC__StreamEncoderMetadataCallback metadata_callback,
1165 return init_stream_internal_(
1177 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1178 FLAC__StreamEncoder *encoder,
1180 FLAC__StreamEncoderProgressCallback progress_callback,
1185 FLAC__StreamEncoderInitStatus init_status;
1187 FLAC__ASSERT(0 != encoder);
1188 FLAC__ASSERT(0 != file);
1190 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1191 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1193 /* double protection */
1195 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1196 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1200 * To make sure that our file does not go unclosed after an error, we
1201 * must assign the FILE pointer before any further error can occur in
1205 file = get_binary_stdout_(); /* just to be safe */
1207 encoder->private_->file = file;
1209 encoder->private_->progress_callback = progress_callback;
1210 encoder->private_->bytes_written = 0;
1211 encoder->private_->samples_written = 0;
1212 encoder->private_->frames_written = 0;
1214 init_status = init_stream_internal_(
1216 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1217 file_write_callback_,
1218 encoder->private_->file == stdout? 0 : file_seek_callback_,
1219 encoder->private_->file == stdout? 0 : file_tell_callback_,
1220 /*metadata_callback=*/0,
1224 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1225 /* the above function sets the state for us in case of an error */
1230 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1232 FLAC__ASSERT(blocksize != 0);
1233 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1239 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1240 FLAC__StreamEncoder *encoder,
1242 FLAC__StreamEncoderProgressCallback progress_callback,
1246 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1249 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1250 FLAC__StreamEncoder *encoder,
1252 FLAC__StreamEncoderProgressCallback progress_callback,
1256 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1259 static FLAC__StreamEncoderInitStatus init_file_internal_(
1260 FLAC__StreamEncoder *encoder,
1261 const char *filename,
1262 FLAC__StreamEncoderProgressCallback progress_callback,
1269 FLAC__ASSERT(0 != encoder);
1272 * To make sure that our file does not go unclosed after an error, we
1273 * have to do the same entrance checks here that are later performed
1274 * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1276 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1277 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1279 file = filename? fopen(filename, "w+b") : stdout;
1282 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1283 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1286 return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1289 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1290 FLAC__StreamEncoder *encoder,
1291 const char *filename,
1292 FLAC__StreamEncoderProgressCallback progress_callback,
1296 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1299 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1300 FLAC__StreamEncoder *encoder,
1301 const char *filename,
1302 FLAC__StreamEncoderProgressCallback progress_callback,
1306 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1309 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1311 FLAC__bool error = false;
1313 FLAC__ASSERT(0 != encoder);
1314 FLAC__ASSERT(0 != encoder->private_);
1315 FLAC__ASSERT(0 != encoder->protected_);
1317 if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1320 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1321 if(encoder->private_->current_sample_number != 0) {
1322 const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1323 encoder->protected_->blocksize = encoder->private_->current_sample_number;
1324 if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1329 if(encoder->protected_->do_md5)
1330 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1332 if(!encoder->private_->is_being_deleted) {
1333 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1334 if(encoder->private_->seek_callback) {
1336 if(encoder->private_->is_ogg)
1337 update_ogg_metadata_(encoder);
1340 update_metadata_(encoder);
1342 /* check if an error occurred while updating metadata */
1343 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1346 if(encoder->private_->metadata_callback)
1347 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1350 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1352 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1357 if(0 != encoder->private_->file) {
1358 if(encoder->private_->file != stdout)
1359 fclose(encoder->private_->file);
1360 encoder->private_->file = 0;
1364 if(encoder->private_->is_ogg)
1365 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1369 set_defaults_(encoder);
1372 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1377 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1379 FLAC__ASSERT(0 != encoder);
1380 FLAC__ASSERT(0 != encoder->private_);
1381 FLAC__ASSERT(0 != encoder->protected_);
1382 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1385 /* can't check encoder->private_->is_ogg since that's not set until init time */
1386 FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1394 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1396 FLAC__ASSERT(0 != encoder);
1397 FLAC__ASSERT(0 != encoder->private_);
1398 FLAC__ASSERT(0 != encoder->protected_);
1399 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1401 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1402 encoder->protected_->verify = value;
1407 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1409 FLAC__ASSERT(0 != encoder);
1410 FLAC__ASSERT(0 != encoder->private_);
1411 FLAC__ASSERT(0 != encoder->protected_);
1412 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1414 encoder->protected_->streamable_subset = value;
1418 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
1420 FLAC__ASSERT(0 != encoder);
1421 FLAC__ASSERT(0 != encoder->private_);
1422 FLAC__ASSERT(0 != encoder->protected_);
1423 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1425 encoder->protected_->do_md5 = value;
1429 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1431 FLAC__ASSERT(0 != encoder);
1432 FLAC__ASSERT(0 != encoder->private_);
1433 FLAC__ASSERT(0 != encoder->protected_);
1434 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1436 encoder->protected_->channels = value;
1440 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1442 FLAC__ASSERT(0 != encoder);
1443 FLAC__ASSERT(0 != encoder->private_);
1444 FLAC__ASSERT(0 != encoder->protected_);
1445 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1447 encoder->protected_->bits_per_sample = value;
1451 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1453 FLAC__ASSERT(0 != encoder);
1454 FLAC__ASSERT(0 != encoder->private_);
1455 FLAC__ASSERT(0 != encoder->protected_);
1456 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1458 encoder->protected_->sample_rate = value;
1462 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1464 FLAC__bool ok = true;
1465 FLAC__ASSERT(0 != encoder);
1466 FLAC__ASSERT(0 != encoder->private_);
1467 FLAC__ASSERT(0 != encoder->protected_);
1468 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1470 if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1471 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1472 ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
1473 ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
1474 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1477 ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
1478 /* but it's too hard to specify the string in a locale-specific way */
1480 encoder->protected_->num_apodizations = 1;
1481 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1482 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1485 ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
1486 ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
1487 ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1488 ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
1489 ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
1490 ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1491 ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1492 ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
1496 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1498 FLAC__ASSERT(0 != encoder);
1499 FLAC__ASSERT(0 != encoder->private_);
1500 FLAC__ASSERT(0 != encoder->protected_);
1501 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1503 encoder->protected_->blocksize = value;
1507 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1509 FLAC__ASSERT(0 != encoder);
1510 FLAC__ASSERT(0 != encoder->private_);
1511 FLAC__ASSERT(0 != encoder->protected_);
1512 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1514 encoder->protected_->do_mid_side_stereo = value;
1518 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1520 FLAC__ASSERT(0 != encoder);
1521 FLAC__ASSERT(0 != encoder->private_);
1522 FLAC__ASSERT(0 != encoder->protected_);
1523 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1525 encoder->protected_->loose_mid_side_stereo = value;
1529 /*@@@@add to tests*/
1530 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1532 FLAC__ASSERT(0 != encoder);
1533 FLAC__ASSERT(0 != encoder->private_);
1534 FLAC__ASSERT(0 != encoder->protected_);
1535 FLAC__ASSERT(0 != specification);
1536 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1538 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1539 (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1541 encoder->protected_->num_apodizations = 0;
1543 const char *s = strchr(specification, ';');
1544 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1545 if (n==8 && 0 == strncmp("bartlett" , specification, n))
1546 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1547 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1548 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1549 else if(n==8 && 0 == strncmp("blackman" , specification, n))
1550 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1551 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1552 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1553 else if(n==6 && 0 == strncmp("connes" , specification, n))
1554 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1555 else if(n==7 && 0 == strncmp("flattop" , specification, n))
1556 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1557 else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
1558 FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1559 if (stddev > 0.0 && stddev <= 0.5) {
1560 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1561 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1564 else if(n==7 && 0 == strncmp("hamming" , specification, n))
1565 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1566 else if(n==4 && 0 == strncmp("hann" , specification, n))
1567 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1568 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1569 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1570 else if(n==7 && 0 == strncmp("nuttall" , specification, n))
1571 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1572 else if(n==9 && 0 == strncmp("rectangle" , specification, n))
1573 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1574 else if(n==8 && 0 == strncmp("triangle" , specification, n))
1575 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1576 else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
1577 FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1578 if (p >= 0.0 && p <= 1.0) {
1579 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1580 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1583 else if(n==5 && 0 == strncmp("welch" , specification, n))
1584 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1585 if (encoder->protected_->num_apodizations == 32)
1588 specification = s+1;
1592 if(encoder->protected_->num_apodizations == 0) {
1593 encoder->protected_->num_apodizations = 1;
1594 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1595 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1601 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1603 FLAC__ASSERT(0 != encoder);
1604 FLAC__ASSERT(0 != encoder->private_);
1605 FLAC__ASSERT(0 != encoder->protected_);
1606 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1608 encoder->protected_->max_lpc_order = value;
1612 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1614 FLAC__ASSERT(0 != encoder);
1615 FLAC__ASSERT(0 != encoder->private_);
1616 FLAC__ASSERT(0 != encoder->protected_);
1617 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1619 encoder->protected_->qlp_coeff_precision = value;
1623 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1625 FLAC__ASSERT(0 != encoder);
1626 FLAC__ASSERT(0 != encoder->private_);
1627 FLAC__ASSERT(0 != encoder->protected_);
1628 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1630 encoder->protected_->do_qlp_coeff_prec_search = value;
1634 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1636 FLAC__ASSERT(0 != encoder);
1637 FLAC__ASSERT(0 != encoder->private_);
1638 FLAC__ASSERT(0 != encoder->protected_);
1639 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1642 /*@@@ deprecated: */
1643 encoder->protected_->do_escape_coding = value;
1650 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1652 FLAC__ASSERT(0 != encoder);
1653 FLAC__ASSERT(0 != encoder->private_);
1654 FLAC__ASSERT(0 != encoder->protected_);
1655 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1657 encoder->protected_->do_exhaustive_model_search = value;
1661 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1663 FLAC__ASSERT(0 != encoder);
1664 FLAC__ASSERT(0 != encoder->private_);
1665 FLAC__ASSERT(0 != encoder->protected_);
1666 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1668 encoder->protected_->min_residual_partition_order = value;
1672 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1674 FLAC__ASSERT(0 != encoder);
1675 FLAC__ASSERT(0 != encoder->private_);
1676 FLAC__ASSERT(0 != encoder->protected_);
1677 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1679 encoder->protected_->max_residual_partition_order = value;
1683 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1685 FLAC__ASSERT(0 != encoder);
1686 FLAC__ASSERT(0 != encoder->private_);
1687 FLAC__ASSERT(0 != encoder->protected_);
1688 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1691 /*@@@ deprecated: */
1692 encoder->protected_->rice_parameter_search_dist = value;
1699 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1701 FLAC__ASSERT(0 != encoder);
1702 FLAC__ASSERT(0 != encoder->private_);
1703 FLAC__ASSERT(0 != encoder->protected_);
1704 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1706 encoder->protected_->total_samples_estimate = value;
1710 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1712 FLAC__ASSERT(0 != encoder);
1713 FLAC__ASSERT(0 != encoder->private_);
1714 FLAC__ASSERT(0 != encoder->protected_);
1715 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1721 /* realloc() does not do exactly what we want so... */
1722 if(encoder->protected_->metadata) {
1723 free(encoder->protected_->metadata);
1724 encoder->protected_->metadata = 0;
1725 encoder->protected_->num_metadata_blocks = 0;
1728 FLAC__StreamMetadata **m;
1729 if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
1731 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1732 encoder->protected_->metadata = m;
1733 encoder->protected_->num_metadata_blocks = num_blocks;
1736 if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1743 * These three functions are not static, but not publically exposed in
1744 * include/FLAC/ either. They are used by the test suite.
1746 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1748 FLAC__ASSERT(0 != encoder);
1749 FLAC__ASSERT(0 != encoder->private_);
1750 FLAC__ASSERT(0 != encoder->protected_);
1751 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1753 encoder->private_->disable_constant_subframes = value;
1757 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1759 FLAC__ASSERT(0 != encoder);
1760 FLAC__ASSERT(0 != encoder->private_);
1761 FLAC__ASSERT(0 != encoder->protected_);
1762 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1764 encoder->private_->disable_fixed_subframes = value;
1768 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1770 FLAC__ASSERT(0 != encoder);
1771 FLAC__ASSERT(0 != encoder->private_);
1772 FLAC__ASSERT(0 != encoder->protected_);
1773 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1775 encoder->private_->disable_verbatim_subframes = value;
1779 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1781 FLAC__ASSERT(0 != encoder);
1782 FLAC__ASSERT(0 != encoder->private_);
1783 FLAC__ASSERT(0 != encoder->protected_);
1784 return encoder->protected_->state;
1787 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1789 FLAC__ASSERT(0 != encoder);
1790 FLAC__ASSERT(0 != encoder->private_);
1791 FLAC__ASSERT(0 != encoder->protected_);
1792 if(encoder->protected_->verify)
1793 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1795 return FLAC__STREAM_DECODER_UNINITIALIZED;
1798 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1800 FLAC__ASSERT(0 != encoder);
1801 FLAC__ASSERT(0 != encoder->private_);
1802 FLAC__ASSERT(0 != encoder->protected_);
1803 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1804 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1806 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1809 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)
1811 FLAC__ASSERT(0 != encoder);
1812 FLAC__ASSERT(0 != encoder->private_);
1813 FLAC__ASSERT(0 != encoder->protected_);
1814 if(0 != absolute_sample)
1815 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1816 if(0 != frame_number)
1817 *frame_number = encoder->private_->verify.error_stats.frame_number;
1819 *channel = encoder->private_->verify.error_stats.channel;
1821 *sample = encoder->private_->verify.error_stats.sample;
1823 *expected = encoder->private_->verify.error_stats.expected;
1825 *got = encoder->private_->verify.error_stats.got;
1828 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1830 FLAC__ASSERT(0 != encoder);
1831 FLAC__ASSERT(0 != encoder->private_);
1832 FLAC__ASSERT(0 != encoder->protected_);
1833 return encoder->protected_->verify;
1836 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1838 FLAC__ASSERT(0 != encoder);
1839 FLAC__ASSERT(0 != encoder->private_);
1840 FLAC__ASSERT(0 != encoder->protected_);
1841 return encoder->protected_->streamable_subset;
1844 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
1846 FLAC__ASSERT(0 != encoder);
1847 FLAC__ASSERT(0 != encoder->private_);
1848 FLAC__ASSERT(0 != encoder->protected_);
1849 return encoder->protected_->do_md5;
1852 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1854 FLAC__ASSERT(0 != encoder);
1855 FLAC__ASSERT(0 != encoder->private_);
1856 FLAC__ASSERT(0 != encoder->protected_);
1857 return encoder->protected_->channels;
1860 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1862 FLAC__ASSERT(0 != encoder);
1863 FLAC__ASSERT(0 != encoder->private_);
1864 FLAC__ASSERT(0 != encoder->protected_);
1865 return encoder->protected_->bits_per_sample;
1868 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1870 FLAC__ASSERT(0 != encoder);
1871 FLAC__ASSERT(0 != encoder->private_);
1872 FLAC__ASSERT(0 != encoder->protected_);
1873 return encoder->protected_->sample_rate;
1876 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1878 FLAC__ASSERT(0 != encoder);
1879 FLAC__ASSERT(0 != encoder->private_);
1880 FLAC__ASSERT(0 != encoder->protected_);
1881 return encoder->protected_->blocksize;
1884 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1886 FLAC__ASSERT(0 != encoder);
1887 FLAC__ASSERT(0 != encoder->private_);
1888 FLAC__ASSERT(0 != encoder->protected_);
1889 return encoder->protected_->do_mid_side_stereo;
1892 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1894 FLAC__ASSERT(0 != encoder);
1895 FLAC__ASSERT(0 != encoder->private_);
1896 FLAC__ASSERT(0 != encoder->protected_);
1897 return encoder->protected_->loose_mid_side_stereo;
1900 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1902 FLAC__ASSERT(0 != encoder);
1903 FLAC__ASSERT(0 != encoder->private_);
1904 FLAC__ASSERT(0 != encoder->protected_);
1905 return encoder->protected_->max_lpc_order;
1908 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1910 FLAC__ASSERT(0 != encoder);
1911 FLAC__ASSERT(0 != encoder->private_);
1912 FLAC__ASSERT(0 != encoder->protected_);
1913 return encoder->protected_->qlp_coeff_precision;
1916 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1918 FLAC__ASSERT(0 != encoder);
1919 FLAC__ASSERT(0 != encoder->private_);
1920 FLAC__ASSERT(0 != encoder->protected_);
1921 return encoder->protected_->do_qlp_coeff_prec_search;
1924 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1926 FLAC__ASSERT(0 != encoder);
1927 FLAC__ASSERT(0 != encoder->private_);
1928 FLAC__ASSERT(0 != encoder->protected_);
1929 return encoder->protected_->do_escape_coding;
1932 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1934 FLAC__ASSERT(0 != encoder);
1935 FLAC__ASSERT(0 != encoder->private_);
1936 FLAC__ASSERT(0 != encoder->protected_);
1937 return encoder->protected_->do_exhaustive_model_search;
1940 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1942 FLAC__ASSERT(0 != encoder);
1943 FLAC__ASSERT(0 != encoder->private_);
1944 FLAC__ASSERT(0 != encoder->protected_);
1945 return encoder->protected_->min_residual_partition_order;
1948 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1950 FLAC__ASSERT(0 != encoder);
1951 FLAC__ASSERT(0 != encoder->private_);
1952 FLAC__ASSERT(0 != encoder->protected_);
1953 return encoder->protected_->max_residual_partition_order;
1956 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1958 FLAC__ASSERT(0 != encoder);
1959 FLAC__ASSERT(0 != encoder->private_);
1960 FLAC__ASSERT(0 != encoder->protected_);
1961 return encoder->protected_->rice_parameter_search_dist;
1964 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1966 FLAC__ASSERT(0 != encoder);
1967 FLAC__ASSERT(0 != encoder->private_);
1968 FLAC__ASSERT(0 != encoder->protected_);
1969 return encoder->protected_->total_samples_estimate;
1972 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1974 unsigned i, j = 0, channel;
1975 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1977 FLAC__ASSERT(0 != encoder);
1978 FLAC__ASSERT(0 != encoder->private_);
1979 FLAC__ASSERT(0 != encoder->protected_);
1980 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1983 const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
1985 if(encoder->protected_->verify)
1986 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
1988 for(channel = 0; channel < channels; channel++)
1989 memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
1991 if(encoder->protected_->do_mid_side_stereo) {
1992 FLAC__ASSERT(channels == 2);
1993 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
1994 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1995 encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
1996 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' ! */
2002 encoder->private_->current_sample_number += n;
2004 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2005 if(encoder->private_->current_sample_number > blocksize) {
2006 FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
2007 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2008 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2010 /* move unprocessed overread samples to beginnings of arrays */
2011 for(channel = 0; channel < channels; channel++)
2012 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2013 if(encoder->protected_->do_mid_side_stereo) {
2014 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2015 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2017 encoder->private_->current_sample_number = 1;
2019 } while(j < samples);
2024 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2026 unsigned i, j, k, channel;
2027 FLAC__int32 x, mid, side;
2028 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2030 FLAC__ASSERT(0 != encoder);
2031 FLAC__ASSERT(0 != encoder->private_);
2032 FLAC__ASSERT(0 != encoder->protected_);
2033 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2037 * we have several flavors of the same basic loop, optimized for
2038 * different conditions:
2040 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2042 * stereo coding: unroll channel loop
2045 if(encoder->protected_->verify)
2046 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2048 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2049 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2050 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2052 encoder->private_->integer_signal[1][i] = x;
2055 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2056 encoder->private_->integer_signal_mid_side[1][i] = side;
2057 encoder->private_->integer_signal_mid_side[0][i] = mid;
2059 encoder->private_->current_sample_number = i;
2060 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2062 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2064 /* move unprocessed overread samples to beginnings of arrays */
2065 FLAC__ASSERT(i == blocksize+OVERREAD_);
2066 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2067 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
2068 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
2069 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2070 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2071 encoder->private_->current_sample_number = 1;
2073 } while(j < samples);
2077 * independent channel coding: buffer each channel in inner loop
2080 if(encoder->protected_->verify)
2081 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2083 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2084 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2085 for(channel = 0; channel < channels; channel++)
2086 encoder->private_->integer_signal[channel][i] = buffer[k++];
2088 encoder->private_->current_sample_number = i;
2089 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2091 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2093 /* move unprocessed overread samples to beginnings of arrays */
2094 FLAC__ASSERT(i == blocksize+OVERREAD_);
2095 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2096 for(channel = 0; channel < channels; channel++)
2097 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2098 encoder->private_->current_sample_number = 1;
2100 } while(j < samples);
2106 /***********************************************************************
2108 * Private class methods
2110 ***********************************************************************/
2112 void set_defaults_(FLAC__StreamEncoder *encoder)
2114 FLAC__ASSERT(0 != encoder);
2116 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2117 encoder->protected_->verify = true;
2119 encoder->protected_->verify = false;
2121 encoder->protected_->streamable_subset = true;
2122 encoder->protected_->do_md5 = true;
2123 encoder->protected_->do_mid_side_stereo = false;
2124 encoder->protected_->loose_mid_side_stereo = false;
2125 encoder->protected_->channels = 2;
2126 encoder->protected_->bits_per_sample = 16;
2127 encoder->protected_->sample_rate = 44100;
2128 encoder->protected_->blocksize = 0;
2129 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2130 encoder->protected_->num_apodizations = 1;
2131 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2132 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2134 encoder->protected_->max_lpc_order = 0;
2135 encoder->protected_->qlp_coeff_precision = 0;
2136 encoder->protected_->do_qlp_coeff_prec_search = false;
2137 encoder->protected_->do_exhaustive_model_search = false;
2138 encoder->protected_->do_escape_coding = false;
2139 encoder->protected_->min_residual_partition_order = 0;
2140 encoder->protected_->max_residual_partition_order = 0;
2141 encoder->protected_->rice_parameter_search_dist = 0;
2142 encoder->protected_->total_samples_estimate = 0;
2143 encoder->protected_->metadata = 0;
2144 encoder->protected_->num_metadata_blocks = 0;
2146 encoder->private_->seek_table = 0;
2147 encoder->private_->disable_constant_subframes = false;
2148 encoder->private_->disable_fixed_subframes = false;
2149 encoder->private_->disable_verbatim_subframes = false;
2151 encoder->private_->is_ogg = false;
2153 encoder->private_->read_callback = 0;
2154 encoder->private_->write_callback = 0;
2155 encoder->private_->seek_callback = 0;
2156 encoder->private_->tell_callback = 0;
2157 encoder->private_->metadata_callback = 0;
2158 encoder->private_->progress_callback = 0;
2159 encoder->private_->client_data = 0;
2162 FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2165 FLAC__stream_encoder_set_compression_level(encoder, 5);
2168 void free_(FLAC__StreamEncoder *encoder)
2170 unsigned i, channel;
2172 FLAC__ASSERT(0 != encoder);
2173 if(encoder->protected_->metadata) {
2174 free(encoder->protected_->metadata);
2175 encoder->protected_->metadata = 0;
2176 encoder->protected_->num_metadata_blocks = 0;
2178 for(i = 0; i < encoder->protected_->channels; i++) {
2179 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2180 free(encoder->private_->integer_signal_unaligned[i]);
2181 encoder->private_->integer_signal_unaligned[i] = 0;
2183 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2184 if(0 != encoder->private_->real_signal_unaligned[i]) {
2185 free(encoder->private_->real_signal_unaligned[i]);
2186 encoder->private_->real_signal_unaligned[i] = 0;
2190 for(i = 0; i < 2; i++) {
2191 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2192 free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2193 encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2195 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2196 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2197 free(encoder->private_->real_signal_mid_side_unaligned[i]);
2198 encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2202 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2203 for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2204 if(0 != encoder->private_->window_unaligned[i]) {
2205 free(encoder->private_->window_unaligned[i]);
2206 encoder->private_->window_unaligned[i] = 0;
2209 if(0 != encoder->private_->windowed_signal_unaligned) {
2210 free(encoder->private_->windowed_signal_unaligned);
2211 encoder->private_->windowed_signal_unaligned = 0;
2214 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2215 for(i = 0; i < 2; i++) {
2216 if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2217 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2218 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2222 for(channel = 0; channel < 2; channel++) {
2223 for(i = 0; i < 2; i++) {
2224 if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2225 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2226 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2230 if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2231 free(encoder->private_->abs_residual_partition_sums_unaligned);
2232 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2234 if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2235 free(encoder->private_->raw_bits_per_partition_unaligned);
2236 encoder->private_->raw_bits_per_partition_unaligned = 0;
2238 if(encoder->protected_->verify) {
2239 for(i = 0; i < encoder->protected_->channels; i++) {
2240 if(0 != encoder->private_->verify.input_fifo.data[i]) {
2241 free(encoder->private_->verify.input_fifo.data[i]);
2242 encoder->private_->verify.input_fifo.data[i] = 0;
2246 FLAC__bitwriter_free(encoder->private_->frame);
2249 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2252 unsigned i, channel;
2254 FLAC__ASSERT(new_blocksize > 0);
2255 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2256 FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2258 /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2259 if(new_blocksize <= encoder->private_->input_capacity)
2264 /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
2265 * requires that the input arrays (in our case the integer signals)
2266 * have a buffer of up to 3 zeroes in front (at negative indices) for
2267 * alignment purposes; we use 4 in front to keep the data well-aligned.
2270 for(i = 0; ok && i < encoder->protected_->channels; i++) {
2271 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2272 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2273 encoder->private_->integer_signal[i] += 4;
2274 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2275 #if 0 /* @@@ currently unused */
2276 if(encoder->protected_->max_lpc_order > 0)
2277 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2281 for(i = 0; ok && i < 2; i++) {
2282 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]);
2283 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2284 encoder->private_->integer_signal_mid_side[i] += 4;
2285 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2286 #if 0 /* @@@ currently unused */
2287 if(encoder->protected_->max_lpc_order > 0)
2288 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]);
2292 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2293 if(ok && encoder->protected_->max_lpc_order > 0) {
2294 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2295 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2296 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2299 for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2300 for(i = 0; ok && i < 2; i++) {
2301 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2304 for(channel = 0; ok && channel < 2; channel++) {
2305 for(i = 0; ok && i < 2; i++) {
2306 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]);
2309 /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2310 /*@@@ 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) */
2311 ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2312 if(encoder->protected_->do_escape_coding)
2313 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2315 /* now adjust the windows if the blocksize has changed */
2316 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2317 if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2318 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2319 switch(encoder->protected_->apodizations[i].type) {
2320 case FLAC__APODIZATION_BARTLETT:
2321 FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2323 case FLAC__APODIZATION_BARTLETT_HANN:
2324 FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2326 case FLAC__APODIZATION_BLACKMAN:
2327 FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2329 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2330 FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2332 case FLAC__APODIZATION_CONNES:
2333 FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2335 case FLAC__APODIZATION_FLATTOP:
2336 FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2338 case FLAC__APODIZATION_GAUSS:
2339 FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2341 case FLAC__APODIZATION_HAMMING:
2342 FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2344 case FLAC__APODIZATION_HANN:
2345 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2347 case FLAC__APODIZATION_KAISER_BESSEL:
2348 FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2350 case FLAC__APODIZATION_NUTTALL:
2351 FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2353 case FLAC__APODIZATION_RECTANGLE:
2354 FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2356 case FLAC__APODIZATION_TRIANGLE:
2357 FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2359 case FLAC__APODIZATION_TUKEY:
2360 FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2362 case FLAC__APODIZATION_WELCH:
2363 FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2367 /* double protection */
2368 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2376 encoder->private_->input_capacity = new_blocksize;
2378 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2383 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2385 const FLAC__byte *buffer;
2388 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2390 if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2391 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2395 if(encoder->protected_->verify) {
2396 encoder->private_->verify.output.data = buffer;
2397 encoder->private_->verify.output.bytes = bytes;
2398 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2399 encoder->private_->verify.needs_magic_hack = true;
2402 if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2403 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2404 FLAC__bitwriter_clear(encoder->private_->frame);
2405 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2406 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2412 if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2413 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2414 FLAC__bitwriter_clear(encoder->private_->frame);
2415 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2419 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2420 FLAC__bitwriter_clear(encoder->private_->frame);
2423 encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2424 encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2430 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2432 FLAC__StreamEncoderWriteStatus status;
2433 FLAC__uint64 output_position = 0;
2435 /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2436 if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2437 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2438 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2442 * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2445 FLAC__MetadataType type = (buffer[0] & 0x7f);
2446 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2447 encoder->protected_->streaminfo_offset = output_position;
2448 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2449 encoder->protected_->seektable_offset = output_position;
2453 * Mark the current seek point if hit (if audio_offset == 0 that
2454 * means we're still writing metadata and haven't hit the first
2457 if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2458 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2459 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2460 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2461 FLAC__uint64 test_sample;
2463 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2464 test_sample = encoder->private_->seek_table->points[i].sample_number;
2465 if(test_sample > frame_last_sample) {
2468 else if(test_sample >= frame_first_sample) {
2469 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2470 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2471 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2472 encoder->private_->first_seekpoint_to_check++;
2473 /* DO NOT: "break;" and here's why:
2474 * The seektable template may contain more than one target
2475 * sample for any given frame; we will keep looping, generating
2476 * duplicate seekpoints for them, and we'll clean it up later,
2477 * just before writing the seektable back to the metadata.
2481 encoder->private_->first_seekpoint_to_check++;
2487 if(encoder->private_->is_ogg) {
2488 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2489 &encoder->protected_->ogg_encoder_aspect,
2493 encoder->private_->current_frame_number,
2495 (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2497 encoder->private_->client_data
2502 status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2504 if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2505 encoder->private_->bytes_written += bytes;
2506 encoder->private_->samples_written += samples;
2507 /* we keep a high watermark on the number of frames written because
2508 * when the encoder goes back to write metadata, 'current_frame'
2509 * will drop back to 0.
2511 encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2514 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2519 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2520 void update_metadata_(const FLAC__StreamEncoder *encoder)
2522 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2523 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2524 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2525 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2526 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2527 const unsigned bps = metadata->data.stream_info.bits_per_sample;
2528 FLAC__StreamEncoderSeekStatus seek_status;
2530 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2532 /* All this is based on intimate knowledge of the stream header
2533 * layout, but a change to the header format that would break this
2534 * would also break all streams encoded in the previous format.
2538 * Write MD5 signature
2541 const unsigned md5_offset =
2542 FLAC__STREAM_METADATA_HEADER_LENGTH +
2544 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2545 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2546 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2547 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2548 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2549 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2550 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2551 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2554 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2555 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2556 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2559 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2560 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2566 * Write total samples
2569 const unsigned total_samples_byte_offset =
2570 FLAC__STREAM_METADATA_HEADER_LENGTH +
2572 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2573 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2574 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2575 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2576 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2577 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2578 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2582 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2583 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2584 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2585 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2586 b[4] = (FLAC__byte)(samples & 0xFF);
2587 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) {
2588 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2589 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2592 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2593 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2599 * Write min/max framesize
2602 const unsigned min_framesize_offset =
2603 FLAC__STREAM_METADATA_HEADER_LENGTH +
2605 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2606 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2609 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2610 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2611 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2612 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2613 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2614 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2615 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) {
2616 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2617 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2620 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2621 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2629 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2632 FLAC__format_seektable_sort(encoder->private_->seek_table);
2634 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2636 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) {
2637 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2638 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2642 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2645 xx = encoder->private_->seek_table->points[i].sample_number;
2646 b[7] = (FLAC__byte)xx; xx >>= 8;
2647 b[6] = (FLAC__byte)xx; xx >>= 8;
2648 b[5] = (FLAC__byte)xx; xx >>= 8;
2649 b[4] = (FLAC__byte)xx; xx >>= 8;
2650 b[3] = (FLAC__byte)xx; xx >>= 8;
2651 b[2] = (FLAC__byte)xx; xx >>= 8;
2652 b[1] = (FLAC__byte)xx; xx >>= 8;
2653 b[0] = (FLAC__byte)xx; xx >>= 8;
2654 xx = encoder->private_->seek_table->points[i].stream_offset;
2655 b[15] = (FLAC__byte)xx; xx >>= 8;
2656 b[14] = (FLAC__byte)xx; xx >>= 8;
2657 b[13] = (FLAC__byte)xx; xx >>= 8;
2658 b[12] = (FLAC__byte)xx; xx >>= 8;
2659 b[11] = (FLAC__byte)xx; xx >>= 8;
2660 b[10] = (FLAC__byte)xx; xx >>= 8;
2661 b[9] = (FLAC__byte)xx; xx >>= 8;
2662 b[8] = (FLAC__byte)xx; xx >>= 8;
2663 x = encoder->private_->seek_table->points[i].frame_samples;
2664 b[17] = (FLAC__byte)x; x >>= 8;
2665 b[16] = (FLAC__byte)x; x >>= 8;
2666 if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2667 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2675 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2676 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2678 /* the # of bytes in the 1st packet that precede the STREAMINFO */
2679 static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2680 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2681 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2682 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2683 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2684 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2685 FLAC__STREAM_SYNC_LENGTH
2687 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2688 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2689 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2690 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2691 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2694 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2695 FLAC__ASSERT(0 != encoder->private_->seek_callback);
2697 /* Pre-check that client supports seeking, since we don't want the
2698 * ogg_helper code to ever have to deal with this condition.
2700 if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2703 /* All this is based on intimate knowledge of the stream header
2704 * layout, but a change to the header format that would break this
2705 * would also break all streams encoded in the previous format.
2709 ** Write STREAMINFO stats
2711 simple_ogg_page__init(&page);
2712 if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2713 simple_ogg_page__clear(&page);
2714 return; /* state already set */
2718 * Write MD5 signature
2721 const unsigned md5_offset =
2722 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2723 FLAC__STREAM_METADATA_HEADER_LENGTH +
2725 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2726 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2727 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2728 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2729 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2730 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2731 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2732 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2735 if(md5_offset + 16 > (unsigned)page.body_len) {
2736 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2737 simple_ogg_page__clear(&page);
2740 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2744 * Write total samples
2747 const unsigned total_samples_byte_offset =
2748 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2749 FLAC__STREAM_METADATA_HEADER_LENGTH +
2751 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2752 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2753 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2754 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2755 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2756 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2757 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2761 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2762 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2763 simple_ogg_page__clear(&page);
2766 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2767 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2768 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2769 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2770 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2771 b[4] = (FLAC__byte)(samples & 0xFF);
2772 memcpy(page.body + total_samples_byte_offset, b, 5);
2776 * Write min/max framesize
2779 const unsigned min_framesize_offset =
2780 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2781 FLAC__STREAM_METADATA_HEADER_LENGTH +
2783 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2784 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2787 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2788 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2789 simple_ogg_page__clear(&page);
2792 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2793 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2794 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2795 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2796 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2797 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2798 memcpy(page.body + min_framesize_offset, b, 6);
2800 if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2801 simple_ogg_page__clear(&page);
2802 return; /* state already set */
2804 simple_ogg_page__clear(&page);
2809 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2813 FLAC__format_seektable_sort(encoder->private_->seek_table);
2815 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2817 simple_ogg_page__init(&page);
2818 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2819 simple_ogg_page__clear(&page);
2820 return; /* state already set */
2823 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
2824 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2825 simple_ogg_page__clear(&page);
2829 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
2832 xx = encoder->private_->seek_table->points[i].sample_number;
2833 b[7] = (FLAC__byte)xx; xx >>= 8;
2834 b[6] = (FLAC__byte)xx; xx >>= 8;
2835 b[5] = (FLAC__byte)xx; xx >>= 8;
2836 b[4] = (FLAC__byte)xx; xx >>= 8;
2837 b[3] = (FLAC__byte)xx; xx >>= 8;
2838 b[2] = (FLAC__byte)xx; xx >>= 8;
2839 b[1] = (FLAC__byte)xx; xx >>= 8;
2840 b[0] = (FLAC__byte)xx; xx >>= 8;
2841 xx = encoder->private_->seek_table->points[i].stream_offset;
2842 b[15] = (FLAC__byte)xx; xx >>= 8;
2843 b[14] = (FLAC__byte)xx; xx >>= 8;
2844 b[13] = (FLAC__byte)xx; xx >>= 8;
2845 b[12] = (FLAC__byte)xx; xx >>= 8;
2846 b[11] = (FLAC__byte)xx; xx >>= 8;
2847 b[10] = (FLAC__byte)xx; xx >>= 8;
2848 b[9] = (FLAC__byte)xx; xx >>= 8;
2849 b[8] = (FLAC__byte)xx; xx >>= 8;
2850 x = encoder->private_->seek_table->points[i].frame_samples;
2851 b[17] = (FLAC__byte)x; x >>= 8;
2852 b[16] = (FLAC__byte)x; x >>= 8;
2856 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2857 simple_ogg_page__clear(&page);
2858 return; /* state already set */
2860 simple_ogg_page__clear(&page);
2865 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
2868 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2871 * Accumulate raw signal to the MD5 signature
2873 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)) {
2874 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2879 * Process the frame header and subframes into the frame bitbuffer
2881 if(!process_subframes_(encoder, is_fractional_block)) {
2882 /* the above function sets the state for us in case of an error */
2887 * Zero-pad the frame to a byte_boundary
2889 if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
2890 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2895 * CRC-16 the whole thing
2897 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2899 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
2900 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
2902 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2909 if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
2910 /* the above function sets the state for us in case of an error */
2915 * Get ready for the next frame
2917 encoder->private_->current_sample_number = 0;
2918 encoder->private_->current_frame_number++;
2919 encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
2924 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
2926 FLAC__FrameHeader frame_header;
2927 unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
2928 FLAC__bool do_independent, do_mid_side;
2931 * Calculate the min,max Rice partition orders
2933 if(is_fractional_block) {
2934 max_partition_order = 0;
2937 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
2938 max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
2940 min_partition_order = min(min_partition_order, max_partition_order);
2945 frame_header.blocksize = encoder->protected_->blocksize;
2946 frame_header.sample_rate = encoder->protected_->sample_rate;
2947 frame_header.channels = encoder->protected_->channels;
2948 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
2949 frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
2950 frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2951 frame_header.number.frame_number = encoder->private_->current_frame_number;
2954 * Figure out what channel assignments to try
2956 if(encoder->protected_->do_mid_side_stereo) {
2957 if(encoder->protected_->loose_mid_side_stereo) {
2958 if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
2959 do_independent = true;
2963 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
2964 do_mid_side = !do_independent;
2968 do_independent = true;
2973 do_independent = true;
2974 do_mid_side = false;
2977 FLAC__ASSERT(do_independent || do_mid_side);
2980 * Check for wasted bits; set effective bps for each subframe
2982 if(do_independent) {
2983 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2984 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
2985 encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
2986 encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
2990 FLAC__ASSERT(encoder->protected_->channels == 2);
2991 for(channel = 0; channel < 2; channel++) {
2992 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
2993 encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
2994 encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
2999 * First do a normal encoding pass of each independent channel
3001 if(do_independent) {
3002 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3006 min_partition_order,
3007 max_partition_order,
3009 encoder->private_->subframe_bps[channel],
3010 encoder->private_->integer_signal[channel],
3011 encoder->private_->subframe_workspace_ptr[channel],
3012 encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3013 encoder->private_->residual_workspace[channel],
3014 encoder->private_->best_subframe+channel,
3015 encoder->private_->best_subframe_bits+channel
3023 * Now do mid and side channels if requested
3026 FLAC__ASSERT(encoder->protected_->channels == 2);
3028 for(channel = 0; channel < 2; channel++) {
3032 min_partition_order,
3033 max_partition_order,
3035 encoder->private_->subframe_bps_mid_side[channel],
3036 encoder->private_->integer_signal_mid_side[channel],
3037 encoder->private_->subframe_workspace_ptr_mid_side[channel],
3038 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3039 encoder->private_->residual_workspace_mid_side[channel],
3040 encoder->private_->best_subframe_mid_side+channel,
3041 encoder->private_->best_subframe_bits_mid_side+channel
3049 * Compose the frame bitbuffer
3052 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3053 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3054 FLAC__ChannelAssignment channel_assignment;
3056 FLAC__ASSERT(encoder->protected_->channels == 2);
3058 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3059 channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3062 unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3066 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3067 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
3068 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
3069 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
3070 FLAC__ASSERT(do_independent && do_mid_side);
3072 /* We have to figure out which channel assignent results in the smallest frame */
3073 bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
3074 bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
3075 bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
3076 bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3078 channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3079 min_bits = bits[channel_assignment];
3080 for(ca = 1; ca <= 3; ca++) {
3081 if(bits[ca] < min_bits) {
3082 min_bits = bits[ca];
3083 channel_assignment = (FLAC__ChannelAssignment)ca;
3088 frame_header.channel_assignment = channel_assignment;
3090 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3091 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3095 switch(channel_assignment) {
3096 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3097 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3098 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3100 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3101 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3102 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3104 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3105 left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3106 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3108 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3109 left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3110 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3116 switch(channel_assignment) {
3117 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3118 left_bps = encoder->private_->subframe_bps [0];
3119 right_bps = encoder->private_->subframe_bps [1];
3121 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3122 left_bps = encoder->private_->subframe_bps [0];
3123 right_bps = encoder->private_->subframe_bps_mid_side[1];
3125 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3126 left_bps = encoder->private_->subframe_bps_mid_side[1];
3127 right_bps = encoder->private_->subframe_bps [1];
3129 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3130 left_bps = encoder->private_->subframe_bps_mid_side[0];
3131 right_bps = encoder->private_->subframe_bps_mid_side[1];
3137 /* note that encoder_add_subframe_ sets the state for us in case of an error */
3138 if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3140 if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3144 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3145 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3149 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3150 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)) {
3151 /* the above function sets the state for us in case of an error */
3157 if(encoder->protected_->loose_mid_side_stereo) {
3158 encoder->private_->loose_mid_side_stereo_frame_count++;
3159 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3160 encoder->private_->loose_mid_side_stereo_frame_count = 0;
3163 encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3168 FLAC__bool process_subframe_(
3169 FLAC__StreamEncoder *encoder,
3170 unsigned min_partition_order,
3171 unsigned max_partition_order,
3172 const FLAC__FrameHeader *frame_header,
3173 unsigned subframe_bps,
3174 const FLAC__int32 integer_signal[],
3175 FLAC__Subframe *subframe[2],
3176 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3177 FLAC__int32 *residual[2],
3178 unsigned *best_subframe,
3182 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3183 FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3185 FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3187 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3188 FLAC__double lpc_residual_bits_per_sample;
3189 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 */
3190 FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3191 unsigned min_lpc_order, max_lpc_order, lpc_order;
3192 unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3194 unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3195 unsigned rice_parameter;
3196 unsigned _candidate_bits, _best_bits;
3197 unsigned _best_subframe;
3198 /* only use RICE2 partitions if stream bps > 16 */
3199 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;
3201 FLAC__ASSERT(frame_header->blocksize > 0);
3203 /* verbatim subframe is the baseline against which we measure other compressed subframes */
3205 if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3206 _best_bits = UINT_MAX;
3208 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3210 if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3211 unsigned signal_is_constant = false;
3212 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);
3213 /* check for constant subframe */
3215 !encoder->private_->disable_constant_subframes &&
3216 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3217 fixed_residual_bits_per_sample[1] == 0.0
3219 fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3222 /* the above means it's possible all samples are the same value; now double-check it: */
3224 signal_is_constant = true;
3225 for(i = 1; i < frame_header->blocksize; i++) {
3226 if(integer_signal[0] != integer_signal[i]) {
3227 signal_is_constant = false;
3232 if(signal_is_constant) {
3233 _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3234 if(_candidate_bits < _best_bits) {
3235 _best_subframe = !_best_subframe;
3236 _best_bits = _candidate_bits;
3240 if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3242 if(encoder->protected_->do_exhaustive_model_search) {
3243 min_fixed_order = 0;
3244 max_fixed_order = FLAC__MAX_FIXED_ORDER;
3247 min_fixed_order = max_fixed_order = guess_fixed_order;
3249 if(max_fixed_order >= frame_header->blocksize)
3250 max_fixed_order = frame_header->blocksize - 1;
3251 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3252 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3253 if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3254 continue; /* don't even try */
3255 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 */
3257 if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3258 continue; /* don't even try */
3259 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 */
3261 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3262 if(rice_parameter >= rice_parameter_limit) {
3263 #ifdef DEBUG_VERBOSE
3264 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
3266 rice_parameter = rice_parameter_limit - 1;
3269 evaluate_fixed_subframe_(
3272 residual[!_best_subframe],
3273 encoder->private_->abs_residual_partition_sums,
3274 encoder->private_->raw_bits_per_partition,
3275 frame_header->blocksize,
3279 rice_parameter_limit,
3280 min_partition_order,
3281 max_partition_order,
3282 encoder->protected_->do_escape_coding,
3283 encoder->protected_->rice_parameter_search_dist,
3284 subframe[!_best_subframe],
3285 partitioned_rice_contents[!_best_subframe]
3287 if(_candidate_bits < _best_bits) {
3288 _best_subframe = !_best_subframe;
3289 _best_bits = _candidate_bits;
3294 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3296 if(encoder->protected_->max_lpc_order > 0) {
3297 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3298 max_lpc_order = frame_header->blocksize-1;
3300 max_lpc_order = encoder->protected_->max_lpc_order;
3301 if(max_lpc_order > 0) {
3303 for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3304 FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3305 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3306 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3307 if(autoc[0] != 0.0) {
3308 FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3309 if(encoder->protected_->do_exhaustive_model_search) {
3313 const unsigned guess_lpc_order =
3314 FLAC__lpc_compute_best_order(
3317 frame_header->blocksize,
3319 encoder->protected_->do_qlp_coeff_prec_search?
3320 FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
3321 encoder->protected_->qlp_coeff_precision
3324 min_lpc_order = max_lpc_order = guess_lpc_order;
3326 if(max_lpc_order >= frame_header->blocksize)
3327 max_lpc_order = frame_header->blocksize - 1;
3328 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
3329 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
3330 if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
3331 continue; /* don't even try */
3332 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
3333 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3334 if(rice_parameter >= rice_parameter_limit) {
3335 #ifdef DEBUG_VERBOSE
3336 fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
3338 rice_parameter = rice_parameter_limit - 1;
3340 if(encoder->protected_->do_qlp_coeff_prec_search) {
3341 min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
3342 /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
3343 if(subframe_bps <= 17) {
3344 max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
3345 max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
3348 max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
3351 min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
3353 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
3355 evaluate_lpc_subframe_(
3358 residual[!_best_subframe],
3359 encoder->private_->abs_residual_partition_sums,
3360 encoder->private_->raw_bits_per_partition,
3361 encoder->private_->lp_coeff[lpc_order-1],
3362 frame_header->blocksize,
3365 qlp_coeff_precision,
3367 rice_parameter_limit,
3368 min_partition_order,
3369 max_partition_order,
3370 encoder->protected_->do_escape_coding,
3371 encoder->protected_->rice_parameter_search_dist,
3372 subframe[!_best_subframe],
3373 partitioned_rice_contents[!_best_subframe]
3375 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
3376 if(_candidate_bits < _best_bits) {
3377 _best_subframe = !_best_subframe;
3378 _best_bits = _candidate_bits;
3387 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3391 /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3392 if(_best_bits == UINT_MAX) {
3393 FLAC__ASSERT(_best_subframe == 0);
3394 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3397 *best_subframe = _best_subframe;
3398 *best_bits = _best_bits;
3403 FLAC__bool add_subframe_(
3404 FLAC__StreamEncoder *encoder,
3406 unsigned subframe_bps,
3407 const FLAC__Subframe *subframe,
3408 FLAC__BitWriter *frame
3411 switch(subframe->type) {
3412 case FLAC__SUBFRAME_TYPE_CONSTANT:
3413 if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3414 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3418 case FLAC__SUBFRAME_TYPE_FIXED:
3419 if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3420 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3424 case FLAC__SUBFRAME_TYPE_LPC:
3425 if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3426 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3430 case FLAC__SUBFRAME_TYPE_VERBATIM:
3431 if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3432 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3443 #define SPOTCHECK_ESTIMATE 0
3444 #if SPOTCHECK_ESTIMATE
3445 static void spotcheck_subframe_estimate_(
3446 FLAC__StreamEncoder *encoder,
3448 unsigned subframe_bps,
3449 const FLAC__Subframe *subframe,
3454 FLAC__BitWriter *frame = FLAC__bitwriter_new();
3456 fprintf(stderr, "EST: can't allocate frame\n");
3459 if(!FLAC__bitwriter_init(frame)) {
3460 fprintf(stderr, "EST: can't init frame\n");
3463 ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
3466 const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
3467 if(estimate != actual)
3468 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);
3470 FLAC__bitwriter_delete(frame);
3474 unsigned evaluate_constant_subframe_(
3475 FLAC__StreamEncoder *encoder,
3476 const FLAC__int32 signal,
3478 unsigned subframe_bps,
3479 FLAC__Subframe *subframe
3483 subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3484 subframe->data.constant.value = signal;
3486 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
3488 #if SPOTCHECK_ESTIMATE
3489 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3491 (void)encoder, (void)blocksize;
3497 unsigned evaluate_fixed_subframe_(
3498 FLAC__StreamEncoder *encoder,
3499 const FLAC__int32 signal[],
3500 FLAC__int32 residual[],
3501 FLAC__uint64 abs_residual_partition_sums[],
3502 unsigned raw_bits_per_partition[],
3504 unsigned subframe_bps,
3506 unsigned rice_parameter,
3507 unsigned rice_parameter_limit,
3508 unsigned min_partition_order,
3509 unsigned max_partition_order,
3510 FLAC__bool do_escape_coding,
3511 unsigned rice_parameter_search_dist,
3512 FLAC__Subframe *subframe,
3513 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3516 unsigned i, residual_bits, estimate;
3517 const unsigned residual_samples = blocksize - order;
3519 FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3521 subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3523 subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3524 subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3525 subframe->data.fixed.residual = residual;
3528 find_best_partition_order_(
3531 abs_residual_partition_sums,
3532 raw_bits_per_partition,
3536 rice_parameter_limit,
3537 min_partition_order,
3538 max_partition_order,
3541 rice_parameter_search_dist,
3542 &subframe->data.fixed.entropy_coding_method
3545 subframe->data.fixed.order = order;
3546 for(i = 0; i < order; i++)
3547 subframe->data.fixed.warmup[i] = signal[i];
3549 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
3551 #if SPOTCHECK_ESTIMATE
3552 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3558 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3559 unsigned evaluate_lpc_subframe_(
3560 FLAC__StreamEncoder *encoder,
3561 const FLAC__int32 signal[],
3562 FLAC__int32 residual[],
3563 FLAC__uint64 abs_residual_partition_sums[],
3564 unsigned raw_bits_per_partition[],
3565 const FLAC__real lp_coeff[],
3567 unsigned subframe_bps,
3569 unsigned qlp_coeff_precision,
3570 unsigned rice_parameter,
3571 unsigned rice_parameter_limit,
3572 unsigned min_partition_order,
3573 unsigned max_partition_order,
3574 FLAC__bool do_escape_coding,
3575 unsigned rice_parameter_search_dist,
3576 FLAC__Subframe *subframe,
3577 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3580 FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
3581 unsigned i, residual_bits, estimate;
3582 int quantization, ret;
3583 const unsigned residual_samples = blocksize - order;
3585 /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3586 if(subframe_bps <= 16) {
3587 FLAC__ASSERT(order > 0);
3588 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3589 qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3592 ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3594 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3596 if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3597 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3598 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3600 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3602 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3604 subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3606 subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3607 subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3608 subframe->data.lpc.residual = residual;
3611 find_best_partition_order_(
3614 abs_residual_partition_sums,
3615 raw_bits_per_partition,
3619 rice_parameter_limit,
3620 min_partition_order,
3621 max_partition_order,
3624 rice_parameter_search_dist,
3625 &subframe->data.lpc.entropy_coding_method
3628 subframe->data.lpc.order = order;
3629 subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3630 subframe->data.lpc.quantization_level = quantization;
3631 memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3632 for(i = 0; i < order; i++)
3633 subframe->data.lpc.warmup[i] = signal[i];
3635 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;
3637 #if SPOTCHECK_ESTIMATE
3638 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3645 unsigned evaluate_verbatim_subframe_(
3646 FLAC__StreamEncoder *encoder,
3647 const FLAC__int32 signal[],
3649 unsigned subframe_bps,
3650 FLAC__Subframe *subframe
3655 subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3657 subframe->data.verbatim.data = signal;
3659 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
3661 #if SPOTCHECK_ESTIMATE
3662 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3670 unsigned find_best_partition_order_(
3671 FLAC__StreamEncoderPrivate *private_,
3672 const FLAC__int32 residual[],
3673 FLAC__uint64 abs_residual_partition_sums[],
3674 unsigned raw_bits_per_partition[],
3675 unsigned residual_samples,
3676 unsigned predictor_order,
3677 unsigned rice_parameter,
3678 unsigned rice_parameter_limit,
3679 unsigned min_partition_order,
3680 unsigned max_partition_order,
3682 FLAC__bool do_escape_coding,
3683 unsigned rice_parameter_search_dist,
3684 FLAC__EntropyCodingMethod *best_ecm
3687 unsigned residual_bits, best_residual_bits = 0;
3688 unsigned best_parameters_index = 0;
3689 unsigned best_partition_order = 0;
3690 const unsigned blocksize = residual_samples + predictor_order;
3692 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3693 min_partition_order = min(min_partition_order, max_partition_order);
3695 precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
3697 if(do_escape_coding)
3698 precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3701 int partition_order;
3704 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3706 set_partitioned_rice_(
3707 #ifdef EXACT_RICE_BITS_CALCULATION
3710 abs_residual_partition_sums+sum,
3711 raw_bits_per_partition+sum,
3715 rice_parameter_limit,
3716 rice_parameter_search_dist,
3717 (unsigned)partition_order,
3719 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3724 FLAC__ASSERT(best_residual_bits != 0);
3727 sum += 1u << partition_order;
3728 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3729 best_residual_bits = residual_bits;
3730 best_parameters_index = !best_parameters_index;
3731 best_partition_order = partition_order;
3736 best_ecm->data.partitioned_rice.order = best_partition_order;
3740 * We are allowed to de-const the pointer based on our special
3741 * knowledge; it is const to the outside world.
3743 FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
3746 /* save best parameters and raw_bits */
3747 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
3748 memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
3749 if(do_escape_coding)
3750 memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
3752 * Now need to check if the type should be changed to
3753 * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
3754 * size of the rice parameters.
3756 for(partition = 0; partition < (1u<<best_partition_order); partition++) {
3757 if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3758 best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
3764 return best_residual_bits;
3767 #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
3768 extern void precompute_partition_info_sums_32bit_asm_ia32_(
3769 const FLAC__int32 residual[],
3770 FLAC__uint64 abs_residual_partition_sums[],
3772 unsigned predictor_order,
3773 unsigned min_partition_order,
3774 unsigned max_partition_order
3778 void precompute_partition_info_sums_(
3779 const FLAC__int32 residual[],
3780 FLAC__uint64 abs_residual_partition_sums[],
3781 unsigned residual_samples,
3782 unsigned predictor_order,
3783 unsigned min_partition_order,
3784 unsigned max_partition_order,
3788 const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
3789 unsigned partitions = 1u << max_partition_order;
3791 FLAC__ASSERT(default_partition_samples > predictor_order);
3793 #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
3794 /* slightly pessimistic but still catches all common cases */
3795 /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
3796 if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
3797 precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
3802 /* first do max_partition_order */
3804 unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
3805 /* slightly pessimistic but still catches all common cases */
3806 /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
3807 if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
3808 FLAC__uint32 abs_residual_partition_sum;
3810 for(partition = residual_sample = 0; partition < partitions; partition++) {
3811 end += default_partition_samples;
3812 abs_residual_partition_sum = 0;
3813 for( ; residual_sample < end; residual_sample++)
3814 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3815 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3818 else { /* have to pessimistically use 64 bits for accumulator */
3819 FLAC__uint64 abs_residual_partition_sum;
3821 for(partition = residual_sample = 0; partition < partitions; partition++) {
3822 end += default_partition_samples;
3823 abs_residual_partition_sum = 0;
3824 for( ; residual_sample < end; residual_sample++)
3825 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3826 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3831 /* now merge partitions for lower orders */
3833 unsigned from_partition = 0, to_partition = partitions;
3834 int partition_order;
3835 for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
3838 for(i = 0; i < partitions; i++) {
3839 abs_residual_partition_sums[to_partition++] =
3840 abs_residual_partition_sums[from_partition ] +
3841 abs_residual_partition_sums[from_partition+1];
3842 from_partition += 2;
3848 void precompute_partition_info_escapes_(
3849 const FLAC__int32 residual[],
3850 unsigned raw_bits_per_partition[],
3851 unsigned residual_samples,
3852 unsigned predictor_order,
3853 unsigned min_partition_order,
3854 unsigned max_partition_order
3857 int partition_order;
3858 unsigned from_partition, to_partition = 0;
3859 const unsigned blocksize = residual_samples + predictor_order;
3861 /* first do max_partition_order */
3862 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3865 unsigned partition, partition_sample, partition_samples, residual_sample;
3866 const unsigned partitions = 1u << partition_order;
3867 const unsigned default_partition_samples = blocksize >> partition_order;
3869 FLAC__ASSERT(default_partition_samples > predictor_order);
3871 for(partition = residual_sample = 0; partition < partitions; partition++) {
3872 partition_samples = default_partition_samples;
3874 partition_samples -= predictor_order;
3876 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
3877 r = residual[residual_sample++];
3878 /* OPT: maybe faster: rmax |= r ^ (r>>31) */
3884 /* now we know all residual values are in the range [-rmax-1,rmax] */
3885 raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
3887 to_partition = partitions;
3888 break; /*@@@ yuck, should remove the 'for' loop instead */
3891 /* now merge partitions for lower orders */
3892 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
3895 const unsigned partitions = 1u << partition_order;
3896 for(i = 0; i < partitions; i++) {
3897 m = raw_bits_per_partition[from_partition];
3899 raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
3906 #ifdef EXACT_RICE_BITS_CALCULATION
3907 static FLaC__INLINE unsigned count_rice_bits_in_partition_(
3908 const unsigned rice_parameter,
3909 const unsigned partition_samples,
3910 const FLAC__int32 *residual
3913 unsigned i, partition_bits =
3914 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 */
3915 (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
3917 for(i = 0; i < partition_samples; i++)
3918 partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
3919 return partition_bits;
3922 static FLaC__INLINE unsigned count_rice_bits_in_partition_(
3923 const unsigned rice_parameter,
3924 const unsigned partition_samples,
3925 const FLAC__uint64 abs_residual_partition_sum
3929 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 */
3930 (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
3933 (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
3934 : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
3936 - (partition_samples >> 1)
3937 /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
3938 * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
3939 * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
3940 * So the subtraction term tries to guess how many extra bits were contributed.
3941 * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
3947 FLAC__bool set_partitioned_rice_(
3948 #ifdef EXACT_RICE_BITS_CALCULATION
3949 const FLAC__int32 residual[],
3951 const FLAC__uint64 abs_residual_partition_sums[],
3952 const unsigned raw_bits_per_partition[],
3953 const unsigned residual_samples,
3954 const unsigned predictor_order,
3955 const unsigned suggested_rice_parameter,
3956 const unsigned rice_parameter_limit,
3957 const unsigned rice_parameter_search_dist,
3958 const unsigned partition_order,
3959 const FLAC__bool search_for_escapes,
3960 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3964 unsigned rice_parameter, partition_bits;
3965 unsigned best_partition_bits, best_rice_parameter = 0;
3966 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
3967 unsigned *parameters, *raw_bits;
3968 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3969 unsigned min_rice_parameter, max_rice_parameter;
3971 (void)rice_parameter_search_dist;
3974 FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
3975 FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
3977 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
3978 parameters = partitioned_rice_contents->parameters;
3979 raw_bits = partitioned_rice_contents->raw_bits;
3981 if(partition_order == 0) {
3982 best_partition_bits = (unsigned)(-1);
3983 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3984 if(rice_parameter_search_dist) {
3985 if(suggested_rice_parameter < rice_parameter_search_dist)
3986 min_rice_parameter = 0;
3988 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
3989 max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
3990 if(max_rice_parameter >= rice_parameter_limit) {
3991 #ifdef DEBUG_VERBOSE
3992 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
3994 max_rice_parameter = rice_parameter_limit - 1;
3998 min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
4000 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4002 rice_parameter = suggested_rice_parameter;
4004 #ifdef EXACT_RICE_BITS_CALCULATION
4005 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
4007 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
4009 if(partition_bits < best_partition_bits) {
4010 best_rice_parameter = rice_parameter;
4011 best_partition_bits = partition_bits;
4013 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4016 if(search_for_escapes) {
4017 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;
4018 if(partition_bits <= best_partition_bits) {
4019 raw_bits[0] = raw_bits_per_partition[0];
4020 best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4021 best_partition_bits = partition_bits;
4026 parameters[0] = best_rice_parameter;
4027 bits_ += best_partition_bits;
4030 unsigned partition, residual_sample;
4031 unsigned partition_samples;
4032 FLAC__uint64 mean, k;
4033 const unsigned partitions = 1u << partition_order;
4034 for(partition = residual_sample = 0; partition < partitions; partition++) {
4035 partition_samples = (residual_samples+predictor_order) >> partition_order;
4036 if(partition == 0) {
4037 if(partition_samples <= predictor_order)
4040 partition_samples -= predictor_order;
4042 mean = abs_residual_partition_sums[partition];
4043 /* we are basically calculating the size in bits of the
4044 * average residual magnitude in the partition:
4045 * rice_parameter = floor(log2(mean/partition_samples))
4046 * 'mean' is not a good name for the variable, it is
4047 * actually the sum of magnitudes of all residual values
4048 * in the partition, so the actual mean is
4049 * mean/partition_samples
4051 for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
4053 if(rice_parameter >= rice_parameter_limit) {
4054 #ifdef DEBUG_VERBOSE
4055 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
4057 rice_parameter = rice_parameter_limit - 1;
4060 best_partition_bits = (unsigned)(-1);
4061 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4062 if(rice_parameter_search_dist) {
4063 if(rice_parameter < rice_parameter_search_dist)
4064 min_rice_parameter = 0;
4066 min_rice_parameter = rice_parameter - rice_parameter_search_dist;
4067 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
4068 if(max_rice_parameter >= rice_parameter_limit) {
4069 #ifdef DEBUG_VERBOSE
4070 fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
4072 max_rice_parameter = rice_parameter_limit - 1;
4076 min_rice_parameter = max_rice_parameter = rice_parameter;
4078 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4080 #ifdef EXACT_RICE_BITS_CALCULATION
4081 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
4083 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
4085 if(partition_bits < best_partition_bits) {
4086 best_rice_parameter = rice_parameter;
4087 best_partition_bits = partition_bits;
4089 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4092 if(search_for_escapes) {
4093 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;
4094 if(partition_bits <= best_partition_bits) {
4095 raw_bits[partition] = raw_bits_per_partition[partition];
4096 best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4097 best_partition_bits = partition_bits;
4100 raw_bits[partition] = 0;
4102 parameters[partition] = best_rice_parameter;
4103 bits_ += best_partition_bits;
4104 residual_sample += partition_samples;
4112 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
4117 for(i = 0; i < samples && !(x&1); i++)
4124 for(shift = 0; !(x&1); shift++)
4129 for(i = 0; i < samples; i++)
4130 signal[i] >>= shift;
4136 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4140 for(channel = 0; channel < channels; channel++)
4141 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
4143 fifo->tail += wide_samples;
4145 FLAC__ASSERT(fifo->tail <= fifo->size);
4148 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4151 unsigned sample, wide_sample;
4152 unsigned tail = fifo->tail;
4154 sample = input_offset * channels;
4155 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
4156 for(channel = 0; channel < channels; channel++)
4157 fifo->data[channel][tail] = input[sample++];
4162 FLAC__ASSERT(fifo->tail <= fifo->size);
4165 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4167 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4168 const size_t encoded_bytes = encoder->private_->verify.output.bytes;
4171 if(encoder->private_->verify.needs_magic_hack) {
4172 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
4173 *bytes = FLAC__STREAM_SYNC_LENGTH;
4174 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
4175 encoder->private_->verify.needs_magic_hack = false;
4178 if(encoded_bytes == 0) {
4180 * If we get here, a FIFO underflow has occurred,
4181 * which means there is a bug somewhere.
4184 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
4186 else if(encoded_bytes < *bytes)
4187 *bytes = encoded_bytes;
4188 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
4189 encoder->private_->verify.output.data += *bytes;
4190 encoder->private_->verify.output.bytes -= *bytes;
4193 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
4196 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
4198 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
4200 const unsigned channels = frame->header.channels;
4201 const unsigned blocksize = frame->header.blocksize;
4202 const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
4206 for(channel = 0; channel < channels; channel++) {
4207 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
4208 unsigned i, sample = 0;
4209 FLAC__int32 expect = 0, got = 0;
4211 for(i = 0; i < blocksize; i++) {
4212 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
4214 expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
4215 got = (FLAC__int32)buffer[channel][i];
4219 FLAC__ASSERT(i < blocksize);
4220 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
4221 encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
4222 encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
4223 encoder->private_->verify.error_stats.channel = channel;
4224 encoder->private_->verify.error_stats.sample = sample;
4225 encoder->private_->verify.error_stats.expected = expect;
4226 encoder->private_->verify.error_stats.got = got;
4227 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
4228 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
4231 /* dequeue the frame from the fifo */
4232 encoder->private_->verify.input_fifo.tail -= blocksize;
4233 FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
4234 for(channel = 0; channel < channels; channel++)
4235 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]));
4236 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4239 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4241 (void)decoder, (void)metadata, (void)client_data;
4244 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4246 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4247 (void)decoder, (void)status;
4248 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4251 FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4255 *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
4257 if (feof(encoder->private_->file))
4258 return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
4259 else if (ferror(encoder->private_->file))
4260 return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
4262 return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
4265 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4269 if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
4270 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4272 return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4275 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4281 offset = ftello(encoder->private_->file);
4284 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4287 *absolute_byte_offset = (FLAC__uint64)offset;
4288 return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4292 #ifdef FLAC__VALGRIND_TESTING
4293 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4295 size_t ret = fwrite(ptr, size, nmemb, stream);
4301 #define local__fwrite fwrite
4304 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
4306 (void)client_data, (void)current_frame;
4308 if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4309 FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
4311 /* We would like to be able to use 'samples > 0' in the
4312 * clause here but currently because of the nature of our
4313 * Ogg writing implementation, 'samples' is always 0 (see
4314 * ogg_encoder_aspect.c). The downside is extra progress
4317 encoder->private_->is_ogg? true :
4322 /* NOTE: We have to add +bytes, +samples, and +1 to the stats
4323 * because at this point in the callback chain, the stats
4324 * have not been updated. Only after we return and control
4325 * gets back to write_frame_() are the stats updated
4327 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);
4329 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4332 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4336 * This will forcibly set stdout to binary mode (for OSes that require it)
4338 FILE *get_binary_stdout_(void)
4340 /* if something breaks here it is probably due to the presence or
4341 * absence of an underscore before the identifiers 'setmode',
4342 * 'fileno', and/or 'O_BINARY'; check your system header files.
4344 #if defined _MSC_VER || defined __MINGW32__
4345 _setmode(_fileno(stdout), _O_BINARY);
4346 #elif defined __CYGWIN__
4347 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4348 setmode(_fileno(stdout), _O_BINARY);
4349 #elif defined __EMX__
4350 setmode(fileno(stdout), O_BINARY);