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 #include "FLAC/assert.h"
50 #include "FLAC/stream_decoder.h"
51 #include "share/alloc.h"
52 #include "share/compat.h"
53 #include "protected/stream_encoder.h"
54 #include "private/bitwriter.h"
55 #include "private/bitmath.h"
56 #include "private/crc.h"
57 #include "private/cpu.h"
58 #include "private/fixed.h"
59 #include "private/format.h"
60 #include "private/lpc.h"
61 #include "private/md5.h"
62 #include "private/memory.h"
63 #include "private/macros.h"
65 #include "private/ogg_helper.h"
66 #include "private/ogg_mapping.h"
68 #include "private/stream_encoder_framing.h"
69 #include "private/window.h"
72 /* Exact Rice codeword length calculation is off by default. The simple
73 * (and fast) estimation (of how many bits a residual value will be
74 * encoded with) in this encoder is very good, almost always yielding
75 * compression within 0.1% of exact calculation.
77 #undef EXACT_RICE_BITS_CALCULATION
78 /* Rice parameter searching is off by default. The simple (and fast)
79 * parameter estimation in this encoder is very good, almost always
80 * yielding compression within 0.1% of the optimal parameters.
82 #undef ENABLE_RICE_PARAMETER_SEARCH
86 FLAC__int32 *data[FLAC__MAX_CHANNELS];
87 unsigned size; /* of each data[] in samples */
92 const FLAC__byte *data;
99 ENCODER_IN_METADATA = 1,
103 static struct CompressionLevels {
104 FLAC__bool do_mid_side_stereo;
105 FLAC__bool loose_mid_side_stereo;
106 unsigned max_lpc_order;
107 unsigned qlp_coeff_precision;
108 FLAC__bool do_qlp_coeff_prec_search;
109 FLAC__bool do_escape_coding;
110 FLAC__bool do_exhaustive_model_search;
111 unsigned min_residual_partition_order;
112 unsigned max_residual_partition_order;
113 unsigned rice_parameter_search_dist;
114 } compression_levels_[] = {
115 { false, false, 0, 0, false, false, false, 0, 3, 0 },
116 { true , true , 0, 0, false, false, false, 0, 3, 0 },
117 { true , false, 0, 0, false, false, false, 0, 3, 0 },
118 { false, false, 6, 0, false, false, false, 0, 4, 0 },
119 { true , true , 8, 0, false, false, false, 0, 4, 0 },
120 { true , false, 8, 0, false, false, false, 0, 5, 0 },
121 { true , false, 8, 0, false, false, false, 0, 6, 0 },
122 { true , false, 8, 0, false, false, true , 0, 6, 0 },
123 { true , false, 12, 0, false, false, true , 0, 6, 0 }
127 /***********************************************************************
129 * Private class method prototypes
131 ***********************************************************************/
133 static void set_defaults_(FLAC__StreamEncoder *encoder);
134 static void free_(FLAC__StreamEncoder *encoder);
135 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
136 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
137 static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
138 static void update_metadata_(const FLAC__StreamEncoder *encoder);
140 static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
142 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
143 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
145 static FLAC__bool process_subframe_(
146 FLAC__StreamEncoder *encoder,
147 unsigned min_partition_order,
148 unsigned max_partition_order,
149 const FLAC__FrameHeader *frame_header,
150 unsigned subframe_bps,
151 const FLAC__int32 integer_signal[],
152 FLAC__Subframe *subframe[2],
153 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
154 FLAC__int32 *residual[2],
155 unsigned *best_subframe,
159 static FLAC__bool add_subframe_(
160 FLAC__StreamEncoder *encoder,
162 unsigned subframe_bps,
163 const FLAC__Subframe *subframe,
164 FLAC__BitWriter *frame
167 static unsigned evaluate_constant_subframe_(
168 FLAC__StreamEncoder *encoder,
169 const FLAC__int32 signal,
171 unsigned subframe_bps,
172 FLAC__Subframe *subframe
175 static unsigned evaluate_fixed_subframe_(
176 FLAC__StreamEncoder *encoder,
177 const FLAC__int32 signal[],
178 FLAC__int32 residual[],
179 FLAC__uint64 abs_residual_partition_sums[],
180 unsigned raw_bits_per_partition[],
182 unsigned subframe_bps,
184 unsigned rice_parameter,
185 unsigned rice_parameter_limit,
186 unsigned min_partition_order,
187 unsigned max_partition_order,
188 FLAC__bool do_escape_coding,
189 unsigned rice_parameter_search_dist,
190 FLAC__Subframe *subframe,
191 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
194 #ifndef FLAC__INTEGER_ONLY_LIBRARY
195 static unsigned evaluate_lpc_subframe_(
196 FLAC__StreamEncoder *encoder,
197 const FLAC__int32 signal[],
198 FLAC__int32 residual[],
199 FLAC__uint64 abs_residual_partition_sums[],
200 unsigned raw_bits_per_partition[],
201 const FLAC__real lp_coeff[],
203 unsigned subframe_bps,
205 unsigned qlp_coeff_precision,
206 unsigned rice_parameter,
207 unsigned rice_parameter_limit,
208 unsigned min_partition_order,
209 unsigned max_partition_order,
210 FLAC__bool do_escape_coding,
211 unsigned rice_parameter_search_dist,
212 FLAC__Subframe *subframe,
213 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
217 static unsigned evaluate_verbatim_subframe_(
218 FLAC__StreamEncoder *encoder,
219 const FLAC__int32 signal[],
221 unsigned subframe_bps,
222 FLAC__Subframe *subframe
225 static unsigned find_best_partition_order_(
226 struct FLAC__StreamEncoderPrivate *private_,
227 const FLAC__int32 residual[],
228 FLAC__uint64 abs_residual_partition_sums[],
229 unsigned raw_bits_per_partition[],
230 unsigned residual_samples,
231 unsigned predictor_order,
232 unsigned rice_parameter,
233 unsigned rice_parameter_limit,
234 unsigned min_partition_order,
235 unsigned max_partition_order,
237 FLAC__bool do_escape_coding,
238 unsigned rice_parameter_search_dist,
239 FLAC__EntropyCodingMethod *best_ecm
242 static void precompute_partition_info_sums_(
243 const FLAC__int32 residual[],
244 FLAC__uint64 abs_residual_partition_sums[],
245 unsigned residual_samples,
246 unsigned predictor_order,
247 unsigned min_partition_order,
248 unsigned max_partition_order,
252 static void precompute_partition_info_escapes_(
253 const FLAC__int32 residual[],
254 unsigned raw_bits_per_partition[],
255 unsigned residual_samples,
256 unsigned predictor_order,
257 unsigned min_partition_order,
258 unsigned max_partition_order
261 static FLAC__bool set_partitioned_rice_(
262 #ifdef EXACT_RICE_BITS_CALCULATION
263 const FLAC__int32 residual[],
265 const FLAC__uint64 abs_residual_partition_sums[],
266 const unsigned raw_bits_per_partition[],
267 const unsigned residual_samples,
268 const unsigned predictor_order,
269 const unsigned suggested_rice_parameter,
270 const unsigned rice_parameter_limit,
271 const unsigned rice_parameter_search_dist,
272 const unsigned partition_order,
273 const FLAC__bool search_for_escapes,
274 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
278 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
280 /* verify-related routines: */
281 static void append_to_verify_fifo_(
282 verify_input_fifo *fifo,
283 const FLAC__int32 * const input[],
284 unsigned input_offset,
286 unsigned wide_samples
289 static void append_to_verify_fifo_interleaved_(
290 verify_input_fifo *fifo,
291 const FLAC__int32 input[],
292 unsigned input_offset,
294 unsigned wide_samples
297 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
298 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
299 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
300 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
302 static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
303 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
304 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
305 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);
306 static FILE *get_binary_stdout_(void);
309 /***********************************************************************
313 ***********************************************************************/
315 typedef struct FLAC__StreamEncoderPrivate {
316 unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
317 FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
318 FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
319 #ifndef FLAC__INTEGER_ONLY_LIBRARY
320 FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
321 FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
322 FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
323 FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
325 unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
326 unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
327 FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
328 FLAC__int32 *residual_workspace_mid_side[2][2];
329 FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
330 FLAC__Subframe subframe_workspace_mid_side[2][2];
331 FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
332 FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
333 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
334 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
335 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
336 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
337 unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
338 unsigned best_subframe_mid_side[2];
339 unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
340 unsigned best_subframe_bits_mid_side[2];
341 FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
342 unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
343 FLAC__BitWriter *frame; /* the current frame being worked on */
344 unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
345 unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
346 FLAC__ChannelAssignment last_channel_assignment;
347 FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
348 FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
349 unsigned current_sample_number;
350 unsigned current_frame_number;
351 FLAC__MD5Context md5context;
352 FLAC__CPUInfo cpuinfo;
353 #ifndef FLAC__INTEGER_ONLY_LIBRARY
354 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
356 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
358 #ifndef FLAC__INTEGER_ONLY_LIBRARY
359 void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
360 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[]);
361 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[]);
362 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[]);
364 FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
365 FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
366 FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
367 FLAC__bool disable_constant_subframes;
368 FLAC__bool disable_fixed_subframes;
369 FLAC__bool disable_verbatim_subframes;
373 FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
374 FLAC__StreamEncoderSeekCallback seek_callback;
375 FLAC__StreamEncoderTellCallback tell_callback;
376 FLAC__StreamEncoderWriteCallback write_callback;
377 FLAC__StreamEncoderMetadataCallback metadata_callback;
378 FLAC__StreamEncoderProgressCallback progress_callback;
380 unsigned first_seekpoint_to_check;
381 FILE *file; /* only used when encoding to a file */
382 FLAC__uint64 bytes_written;
383 FLAC__uint64 samples_written;
384 unsigned frames_written;
385 unsigned total_frames_estimate;
386 /* unaligned (original) pointers to allocated data */
387 FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
388 FLAC__int32 *integer_signal_mid_side_unaligned[2];
389 #ifndef FLAC__INTEGER_ONLY_LIBRARY
390 FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
391 FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
392 FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
393 FLAC__real *windowed_signal_unaligned;
395 FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
396 FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
397 FLAC__uint64 *abs_residual_partition_sums_unaligned;
398 unsigned *raw_bits_per_partition_unaligned;
400 * These fields have been moved here from private function local
401 * declarations merely to save stack space during encoding.
403 #ifndef FLAC__INTEGER_ONLY_LIBRARY
404 FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
406 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
408 * The data for the verify section
411 FLAC__StreamDecoder *decoder;
412 EncoderStateHint state_hint;
413 FLAC__bool needs_magic_hack;
414 verify_input_fifo input_fifo;
415 verify_output output;
417 FLAC__uint64 absolute_sample;
418 unsigned frame_number;
421 FLAC__int32 expected;
425 FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
426 } FLAC__StreamEncoderPrivate;
428 /***********************************************************************
430 * Public static class data
432 ***********************************************************************/
434 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
435 "FLAC__STREAM_ENCODER_OK",
436 "FLAC__STREAM_ENCODER_UNINITIALIZED",
437 "FLAC__STREAM_ENCODER_OGG_ERROR",
438 "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
439 "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
440 "FLAC__STREAM_ENCODER_CLIENT_ERROR",
441 "FLAC__STREAM_ENCODER_IO_ERROR",
442 "FLAC__STREAM_ENCODER_FRAMING_ERROR",
443 "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
446 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
447 "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
448 "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
449 "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
450 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
451 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
452 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
453 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
454 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
455 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
456 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
457 "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
458 "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
459 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
460 "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
463 FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
464 "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
465 "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
466 "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
467 "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
470 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
471 "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
472 "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
475 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
476 "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
477 "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
478 "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
481 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
482 "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
483 "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
484 "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
487 /* Number of samples that will be overread to watch for end of stream. By
488 * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
489 * always try to read blocksize+1 samples before encoding a block, so that
490 * even if the stream has a total sample count that is an integral multiple
491 * of the blocksize, we will still notice when we are encoding the last
492 * block. This is needed, for example, to correctly set the end-of-stream
493 * marker in Ogg FLAC.
495 * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
496 * not really any reason to change it.
498 static const unsigned OVERREAD_ = 1;
500 /***********************************************************************
502 * Class constructor/destructor
505 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
507 FLAC__StreamEncoder *encoder;
510 FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
512 encoder = calloc(1, sizeof(FLAC__StreamEncoder));
517 encoder->protected_ = calloc(1, sizeof(FLAC__StreamEncoderProtected));
518 if(encoder->protected_ == 0) {
523 encoder->private_ = calloc(1, sizeof(FLAC__StreamEncoderPrivate));
524 if(encoder->private_ == 0) {
525 free(encoder->protected_);
530 encoder->private_->frame = FLAC__bitwriter_new();
531 if(encoder->private_->frame == 0) {
532 free(encoder->private_);
533 free(encoder->protected_);
538 encoder->private_->file = 0;
540 set_defaults_(encoder);
542 encoder->private_->is_being_deleted = false;
544 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
545 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
546 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
548 for(i = 0; i < 2; i++) {
549 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
550 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
552 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
553 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
554 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
556 for(i = 0; i < 2; i++) {
557 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
558 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
561 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
562 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
563 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
565 for(i = 0; i < 2; i++) {
566 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
567 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
569 for(i = 0; i < 2; i++)
570 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
572 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
577 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
584 FLAC__ASSERT(0 != encoder->protected_);
585 FLAC__ASSERT(0 != encoder->private_);
586 FLAC__ASSERT(0 != encoder->private_->frame);
588 encoder->private_->is_being_deleted = true;
590 (void)FLAC__stream_encoder_finish(encoder);
592 if(0 != encoder->private_->verify.decoder)
593 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
595 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
596 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
597 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
599 for(i = 0; i < 2; i++) {
600 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
601 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
603 for(i = 0; i < 2; i++)
604 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
606 FLAC__bitwriter_delete(encoder->private_->frame);
607 free(encoder->private_);
608 free(encoder->protected_);
612 /***********************************************************************
614 * Public class methods
616 ***********************************************************************/
618 static FLAC__StreamEncoderInitStatus init_stream_internal_(
619 FLAC__StreamEncoder *encoder,
620 FLAC__StreamEncoderReadCallback read_callback,
621 FLAC__StreamEncoderWriteCallback write_callback,
622 FLAC__StreamEncoderSeekCallback seek_callback,
623 FLAC__StreamEncoderTellCallback tell_callback,
624 FLAC__StreamEncoderMetadataCallback metadata_callback,
630 FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
632 FLAC__ASSERT(0 != encoder);
634 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
635 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
639 return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
642 if(0 == write_callback || (seek_callback && 0 == tell_callback))
643 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
645 if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
646 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
648 if(encoder->protected_->channels != 2) {
649 encoder->protected_->do_mid_side_stereo = false;
650 encoder->protected_->loose_mid_side_stereo = false;
652 else if(!encoder->protected_->do_mid_side_stereo)
653 encoder->protected_->loose_mid_side_stereo = false;
655 if(encoder->protected_->bits_per_sample >= 32)
656 encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
658 if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
659 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
661 if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
662 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
664 if(encoder->protected_->blocksize == 0) {
665 if(encoder->protected_->max_lpc_order == 0)
666 encoder->protected_->blocksize = 1152;
668 encoder->protected_->blocksize = 4096;
671 if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
672 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
674 if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
675 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
677 if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
678 return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
680 if(encoder->protected_->qlp_coeff_precision == 0) {
681 if(encoder->protected_->bits_per_sample < 16) {
682 /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
683 /* @@@ until then we'll make a guess */
684 encoder->protected_->qlp_coeff_precision = flac_max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
686 else if(encoder->protected_->bits_per_sample == 16) {
687 if(encoder->protected_->blocksize <= 192)
688 encoder->protected_->qlp_coeff_precision = 7;
689 else if(encoder->protected_->blocksize <= 384)
690 encoder->protected_->qlp_coeff_precision = 8;
691 else if(encoder->protected_->blocksize <= 576)
692 encoder->protected_->qlp_coeff_precision = 9;
693 else if(encoder->protected_->blocksize <= 1152)
694 encoder->protected_->qlp_coeff_precision = 10;
695 else if(encoder->protected_->blocksize <= 2304)
696 encoder->protected_->qlp_coeff_precision = 11;
697 else if(encoder->protected_->blocksize <= 4608)
698 encoder->protected_->qlp_coeff_precision = 12;
700 encoder->protected_->qlp_coeff_precision = 13;
703 if(encoder->protected_->blocksize <= 384)
704 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
705 else if(encoder->protected_->blocksize <= 1152)
706 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
708 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
710 FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
712 else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
713 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
715 if(encoder->protected_->streamable_subset) {
716 if(!FLAC__format_blocksize_is_subset(encoder->protected_->blocksize, encoder->protected_->sample_rate))
717 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
718 if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
719 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
721 encoder->protected_->bits_per_sample != 8 &&
722 encoder->protected_->bits_per_sample != 12 &&
723 encoder->protected_->bits_per_sample != 16 &&
724 encoder->protected_->bits_per_sample != 20 &&
725 encoder->protected_->bits_per_sample != 24
727 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
728 if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
729 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
731 encoder->protected_->sample_rate <= 48000 &&
733 encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
734 encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
737 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
741 if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
742 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
743 if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
744 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
747 /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
748 if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
750 for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
751 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
752 FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
754 encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
755 encoder->protected_->metadata[0] = vc;
761 /* keep track of any SEEKTABLE block */
762 if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
764 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
765 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
766 encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
767 break; /* take only the first one */
772 /* validate metadata */
773 if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
774 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
775 metadata_has_seektable = false;
776 metadata_has_vorbis_comment = false;
777 metadata_picture_has_type1 = false;
778 metadata_picture_has_type2 = false;
779 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
780 const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
781 if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
782 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
783 else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
784 if(metadata_has_seektable) /* only one is allowed */
785 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
786 metadata_has_seektable = true;
787 if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
788 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
790 else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
791 if(metadata_has_vorbis_comment) /* only one is allowed */
792 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
793 metadata_has_vorbis_comment = true;
795 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
796 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
797 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
799 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
800 if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
801 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
802 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
803 if(metadata_picture_has_type1) /* there should only be 1 per stream */
804 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
805 metadata_picture_has_type1 = true;
806 /* standard icon must be 32x32 pixel PNG */
808 m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
810 (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
811 m->data.picture.width != 32 ||
812 m->data.picture.height != 32
815 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
817 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
818 if(metadata_picture_has_type2) /* there should only be 1 per stream */
819 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
820 metadata_picture_has_type2 = true;
825 encoder->private_->input_capacity = 0;
826 for(i = 0; i < encoder->protected_->channels; i++) {
827 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
828 #ifndef FLAC__INTEGER_ONLY_LIBRARY
829 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
832 for(i = 0; i < 2; i++) {
833 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
834 #ifndef FLAC__INTEGER_ONLY_LIBRARY
835 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
838 #ifndef FLAC__INTEGER_ONLY_LIBRARY
839 for(i = 0; i < encoder->protected_->num_apodizations; i++)
840 encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
841 encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
843 for(i = 0; i < encoder->protected_->channels; i++) {
844 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
845 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
846 encoder->private_->best_subframe[i] = 0;
848 for(i = 0; i < 2; i++) {
849 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
850 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
851 encoder->private_->best_subframe_mid_side[i] = 0;
853 encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
854 encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
855 #ifndef FLAC__INTEGER_ONLY_LIBRARY
856 encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
858 /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
859 /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply÷ by hand */
860 FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
861 FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
862 FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
863 FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
864 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);
866 if(encoder->private_->loose_mid_side_stereo_frames == 0)
867 encoder->private_->loose_mid_side_stereo_frames = 1;
868 encoder->private_->loose_mid_side_stereo_frame_count = 0;
869 encoder->private_->current_sample_number = 0;
870 encoder->private_->current_frame_number = 0;
872 encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
873 encoder->private_->use_wide_by_order = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(flac_max(encoder->protected_->max_lpc_order, FLAC__MAX_FIXED_ORDER))+1 > 30); /*@@@ need to use this? */
874 encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
877 * get the CPU info and set the function pointers
879 FLAC__cpu_info(&encoder->private_->cpuinfo);
880 /* first default to the non-asm routines */
881 #ifndef FLAC__INTEGER_ONLY_LIBRARY
882 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
884 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
885 #ifndef FLAC__INTEGER_ONLY_LIBRARY
886 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
887 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
888 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
890 /* now override with asm where appropriate */
891 #ifndef FLAC__INTEGER_ONLY_LIBRARY
892 # ifndef FLAC__NO_ASM
893 if(encoder->private_->cpuinfo.use_asm) {
894 # ifdef FLAC__CPU_IA32
895 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
896 # ifdef FLAC__HAS_NASM
897 if(encoder->private_->cpuinfo.data.ia32.sse) {
898 if(encoder->protected_->max_lpc_order < 4)
899 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
900 else if(encoder->protected_->max_lpc_order < 8)
901 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
902 else if(encoder->protected_->max_lpc_order < 12)
903 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
905 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
907 else if(encoder->private_->cpuinfo.data.ia32._3dnow)
908 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
910 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
911 if(encoder->private_->cpuinfo.data.ia32.mmx) {
912 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
913 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
916 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
917 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
919 if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
920 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
921 # endif /* FLAC__HAS_NASM */
922 # endif /* FLAC__CPU_IA32 */
924 # endif /* !FLAC__NO_ASM */
925 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
926 /* finally override based on wide-ness if necessary */
927 if(encoder->private_->use_wide_by_block) {
928 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
931 /* set state to OK; from here on, errors are fatal and we'll override the state then */
932 encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
935 encoder->private_->is_ogg = is_ogg;
936 if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
937 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
938 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
942 encoder->private_->read_callback = read_callback;
943 encoder->private_->write_callback = write_callback;
944 encoder->private_->seek_callback = seek_callback;
945 encoder->private_->tell_callback = tell_callback;
946 encoder->private_->metadata_callback = metadata_callback;
947 encoder->private_->client_data = client_data;
949 if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
950 /* the above function sets the state for us in case of an error */
951 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
954 if(!FLAC__bitwriter_init(encoder->private_->frame)) {
955 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
956 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
960 * Set up the verify stuff if necessary
962 if(encoder->protected_->verify) {
964 * First, set up the fifo which will hold the
965 * original signal to compare against
967 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
968 for(i = 0; i < encoder->protected_->channels; i++) {
969 if(0 == (encoder->private_->verify.input_fifo.data[i] = safe_malloc_mul_2op_p(sizeof(FLAC__int32), /*times*/encoder->private_->verify.input_fifo.size))) {
970 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
971 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
974 encoder->private_->verify.input_fifo.tail = 0;
977 * Now set up a stream decoder for verification
979 if(0 == encoder->private_->verify.decoder) {
980 encoder->private_->verify.decoder = FLAC__stream_decoder_new();
981 if(0 == encoder->private_->verify.decoder) {
982 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
983 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
987 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) {
988 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
989 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
992 encoder->private_->verify.error_stats.absolute_sample = 0;
993 encoder->private_->verify.error_stats.frame_number = 0;
994 encoder->private_->verify.error_stats.channel = 0;
995 encoder->private_->verify.error_stats.sample = 0;
996 encoder->private_->verify.error_stats.expected = 0;
997 encoder->private_->verify.error_stats.got = 0;
1000 * These must be done before we write any metadata, because that
1001 * calls the write_callback, which uses these values.
1003 encoder->private_->first_seekpoint_to_check = 0;
1004 encoder->private_->samples_written = 0;
1005 encoder->protected_->streaminfo_offset = 0;
1006 encoder->protected_->seektable_offset = 0;
1007 encoder->protected_->audio_offset = 0;
1010 * write the stream header
1012 if(encoder->protected_->verify)
1013 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1014 if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1015 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1016 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1018 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1019 /* the above function sets the state for us in case of an error */
1020 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1024 * write the STREAMINFO metadata block
1026 if(encoder->protected_->verify)
1027 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1028 encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1029 encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1030 encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1031 encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1032 encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1033 encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1034 encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1035 encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1036 encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1037 encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1038 encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1039 memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1040 if(encoder->protected_->do_md5)
1041 FLAC__MD5Init(&encoder->private_->md5context);
1042 if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1043 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1044 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1046 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1047 /* the above function sets the state for us in case of an error */
1048 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1052 * Now that the STREAMINFO block is written, we can init this to an
1053 * absurdly-high value...
1055 encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1056 /* ... and clear this to 0 */
1057 encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1060 * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1061 * if not, we will write an empty one (FLAC__add_metadata_block()
1062 * automatically supplies the vendor string).
1064 * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1065 * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
1066 * true it will have already insured that the metadata list is properly
1069 if(!metadata_has_vorbis_comment) {
1070 FLAC__StreamMetadata vorbis_comment;
1071 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1072 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1073 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1074 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1075 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1076 vorbis_comment.data.vorbis_comment.num_comments = 0;
1077 vorbis_comment.data.vorbis_comment.comments = 0;
1078 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1079 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1080 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1082 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1083 /* the above function sets the state for us in case of an error */
1084 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1089 * write the user's metadata blocks
1091 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1092 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1093 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1094 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1095 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1097 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1098 /* the above function sets the state for us in case of an error */
1099 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1103 /* now that all the metadata is written, we save the stream offset */
1104 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 */
1105 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1106 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1109 if(encoder->protected_->verify)
1110 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1112 return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1115 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1116 FLAC__StreamEncoder *encoder,
1117 FLAC__StreamEncoderWriteCallback write_callback,
1118 FLAC__StreamEncoderSeekCallback seek_callback,
1119 FLAC__StreamEncoderTellCallback tell_callback,
1120 FLAC__StreamEncoderMetadataCallback metadata_callback,
1124 return init_stream_internal_(
1126 /*read_callback=*/0,
1136 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1137 FLAC__StreamEncoder *encoder,
1138 FLAC__StreamEncoderReadCallback read_callback,
1139 FLAC__StreamEncoderWriteCallback write_callback,
1140 FLAC__StreamEncoderSeekCallback seek_callback,
1141 FLAC__StreamEncoderTellCallback tell_callback,
1142 FLAC__StreamEncoderMetadataCallback metadata_callback,
1146 return init_stream_internal_(
1158 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1159 FLAC__StreamEncoder *encoder,
1161 FLAC__StreamEncoderProgressCallback progress_callback,
1166 FLAC__StreamEncoderInitStatus init_status;
1168 FLAC__ASSERT(0 != encoder);
1169 FLAC__ASSERT(0 != file);
1171 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1172 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1174 /* double protection */
1176 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1177 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1181 * To make sure that our file does not go unclosed after an error, we
1182 * must assign the FILE pointer before any further error can occur in
1186 file = get_binary_stdout_(); /* just to be safe */
1188 encoder->private_->file = file;
1190 encoder->private_->progress_callback = progress_callback;
1191 encoder->private_->bytes_written = 0;
1192 encoder->private_->samples_written = 0;
1193 encoder->private_->frames_written = 0;
1195 init_status = init_stream_internal_(
1197 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1198 file_write_callback_,
1199 encoder->private_->file == stdout? 0 : file_seek_callback_,
1200 encoder->private_->file == stdout? 0 : file_tell_callback_,
1201 /*metadata_callback=*/0,
1205 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1206 /* the above function sets the state for us in case of an error */
1211 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1213 FLAC__ASSERT(blocksize != 0);
1214 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1220 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1221 FLAC__StreamEncoder *encoder,
1223 FLAC__StreamEncoderProgressCallback progress_callback,
1227 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1230 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1231 FLAC__StreamEncoder *encoder,
1233 FLAC__StreamEncoderProgressCallback progress_callback,
1237 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1240 static FLAC__StreamEncoderInitStatus init_file_internal_(
1241 FLAC__StreamEncoder *encoder,
1242 const char *filename,
1243 FLAC__StreamEncoderProgressCallback progress_callback,
1250 FLAC__ASSERT(0 != encoder);
1253 * To make sure that our file does not go unclosed after an error, we
1254 * have to do the same entrance checks here that are later performed
1255 * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1257 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1258 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1260 file = filename? fopen(filename, "w+b") : stdout;
1263 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1264 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1267 return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1270 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1271 FLAC__StreamEncoder *encoder,
1272 const char *filename,
1273 FLAC__StreamEncoderProgressCallback progress_callback,
1277 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1280 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1281 FLAC__StreamEncoder *encoder,
1282 const char *filename,
1283 FLAC__StreamEncoderProgressCallback progress_callback,
1287 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1290 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1292 FLAC__bool error = false;
1294 FLAC__ASSERT(0 != encoder);
1295 FLAC__ASSERT(0 != encoder->private_);
1296 FLAC__ASSERT(0 != encoder->protected_);
1298 if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1301 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1302 if(encoder->private_->current_sample_number != 0) {
1303 const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1304 encoder->protected_->blocksize = encoder->private_->current_sample_number;
1305 if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1310 if(encoder->protected_->do_md5)
1311 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1313 if(!encoder->private_->is_being_deleted) {
1314 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1315 if(encoder->private_->seek_callback) {
1317 if(encoder->private_->is_ogg)
1318 update_ogg_metadata_(encoder);
1321 update_metadata_(encoder);
1323 /* check if an error occurred while updating metadata */
1324 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1327 if(encoder->private_->metadata_callback)
1328 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1331 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1333 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1338 if(0 != encoder->private_->file) {
1339 if(encoder->private_->file != stdout)
1340 fclose(encoder->private_->file);
1341 encoder->private_->file = 0;
1345 if(encoder->private_->is_ogg)
1346 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1350 set_defaults_(encoder);
1353 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1358 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1360 FLAC__ASSERT(0 != encoder);
1361 FLAC__ASSERT(0 != encoder->private_);
1362 FLAC__ASSERT(0 != encoder->protected_);
1363 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1366 /* can't check encoder->private_->is_ogg since that's not set until init time */
1367 FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1375 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1377 FLAC__ASSERT(0 != encoder);
1378 FLAC__ASSERT(0 != encoder->private_);
1379 FLAC__ASSERT(0 != encoder->protected_);
1380 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1382 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1383 encoder->protected_->verify = value;
1388 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1390 FLAC__ASSERT(0 != encoder);
1391 FLAC__ASSERT(0 != encoder->private_);
1392 FLAC__ASSERT(0 != encoder->protected_);
1393 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1395 encoder->protected_->streamable_subset = value;
1399 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
1401 FLAC__ASSERT(0 != encoder);
1402 FLAC__ASSERT(0 != encoder->private_);
1403 FLAC__ASSERT(0 != encoder->protected_);
1404 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1406 encoder->protected_->do_md5 = value;
1410 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1412 FLAC__ASSERT(0 != encoder);
1413 FLAC__ASSERT(0 != encoder->private_);
1414 FLAC__ASSERT(0 != encoder->protected_);
1415 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1417 encoder->protected_->channels = value;
1421 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1423 FLAC__ASSERT(0 != encoder);
1424 FLAC__ASSERT(0 != encoder->private_);
1425 FLAC__ASSERT(0 != encoder->protected_);
1426 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1428 encoder->protected_->bits_per_sample = value;
1432 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1434 FLAC__ASSERT(0 != encoder);
1435 FLAC__ASSERT(0 != encoder->private_);
1436 FLAC__ASSERT(0 != encoder->protected_);
1437 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1439 encoder->protected_->sample_rate = value;
1443 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1445 FLAC__bool ok = true;
1446 FLAC__ASSERT(0 != encoder);
1447 FLAC__ASSERT(0 != encoder->private_);
1448 FLAC__ASSERT(0 != encoder->protected_);
1449 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1451 if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1452 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1453 ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
1454 ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
1455 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1458 ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
1459 /* but it's too hard to specify the string in a locale-specific way */
1461 encoder->protected_->num_apodizations = 1;
1462 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1463 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1466 ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
1467 ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
1468 ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1469 ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
1470 ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
1471 ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1472 ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1473 ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
1477 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1479 FLAC__ASSERT(0 != encoder);
1480 FLAC__ASSERT(0 != encoder->private_);
1481 FLAC__ASSERT(0 != encoder->protected_);
1482 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1484 encoder->protected_->blocksize = value;
1488 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1490 FLAC__ASSERT(0 != encoder);
1491 FLAC__ASSERT(0 != encoder->private_);
1492 FLAC__ASSERT(0 != encoder->protected_);
1493 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1495 encoder->protected_->do_mid_side_stereo = value;
1499 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1501 FLAC__ASSERT(0 != encoder);
1502 FLAC__ASSERT(0 != encoder->private_);
1503 FLAC__ASSERT(0 != encoder->protected_);
1504 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1506 encoder->protected_->loose_mid_side_stereo = value;
1510 /*@@@@add to tests*/
1511 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1513 FLAC__ASSERT(0 != encoder);
1514 FLAC__ASSERT(0 != encoder->private_);
1515 FLAC__ASSERT(0 != encoder->protected_);
1516 FLAC__ASSERT(0 != specification);
1517 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1519 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1520 (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1522 encoder->protected_->num_apodizations = 0;
1524 const char *s = strchr(specification, ';');
1525 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1526 if (n==8 && 0 == strncmp("bartlett" , specification, n))
1527 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1528 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1529 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1530 else if(n==8 && 0 == strncmp("blackman" , specification, n))
1531 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1532 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1533 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1534 else if(n==6 && 0 == strncmp("connes" , specification, n))
1535 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1536 else if(n==7 && 0 == strncmp("flattop" , specification, n))
1537 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1538 else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
1539 FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1540 if (stddev > 0.0 && stddev <= 0.5) {
1541 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1542 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1545 else if(n==7 && 0 == strncmp("hamming" , specification, n))
1546 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1547 else if(n==4 && 0 == strncmp("hann" , specification, n))
1548 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1549 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1550 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1551 else if(n==7 && 0 == strncmp("nuttall" , specification, n))
1552 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1553 else if(n==9 && 0 == strncmp("rectangle" , specification, n))
1554 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1555 else if(n==8 && 0 == strncmp("triangle" , specification, n))
1556 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1557 else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
1558 FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1559 if (p >= 0.0 && p <= 1.0) {
1560 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1561 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1564 else if(n==5 && 0 == strncmp("welch" , specification, n))
1565 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1566 if (encoder->protected_->num_apodizations == 32)
1569 specification = s+1;
1573 if(encoder->protected_->num_apodizations == 0) {
1574 encoder->protected_->num_apodizations = 1;
1575 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1576 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1582 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1584 FLAC__ASSERT(0 != encoder);
1585 FLAC__ASSERT(0 != encoder->private_);
1586 FLAC__ASSERT(0 != encoder->protected_);
1587 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1589 encoder->protected_->max_lpc_order = value;
1593 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1595 FLAC__ASSERT(0 != encoder);
1596 FLAC__ASSERT(0 != encoder->private_);
1597 FLAC__ASSERT(0 != encoder->protected_);
1598 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1600 encoder->protected_->qlp_coeff_precision = value;
1604 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1606 FLAC__ASSERT(0 != encoder);
1607 FLAC__ASSERT(0 != encoder->private_);
1608 FLAC__ASSERT(0 != encoder->protected_);
1609 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1611 encoder->protected_->do_qlp_coeff_prec_search = value;
1615 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1617 FLAC__ASSERT(0 != encoder);
1618 FLAC__ASSERT(0 != encoder->private_);
1619 FLAC__ASSERT(0 != encoder->protected_);
1620 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1623 /*@@@ deprecated: */
1624 encoder->protected_->do_escape_coding = value;
1631 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1633 FLAC__ASSERT(0 != encoder);
1634 FLAC__ASSERT(0 != encoder->private_);
1635 FLAC__ASSERT(0 != encoder->protected_);
1636 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1638 encoder->protected_->do_exhaustive_model_search = value;
1642 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1644 FLAC__ASSERT(0 != encoder);
1645 FLAC__ASSERT(0 != encoder->private_);
1646 FLAC__ASSERT(0 != encoder->protected_);
1647 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1649 encoder->protected_->min_residual_partition_order = value;
1653 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1655 FLAC__ASSERT(0 != encoder);
1656 FLAC__ASSERT(0 != encoder->private_);
1657 FLAC__ASSERT(0 != encoder->protected_);
1658 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1660 encoder->protected_->max_residual_partition_order = value;
1664 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1666 FLAC__ASSERT(0 != encoder);
1667 FLAC__ASSERT(0 != encoder->private_);
1668 FLAC__ASSERT(0 != encoder->protected_);
1669 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1672 /*@@@ deprecated: */
1673 encoder->protected_->rice_parameter_search_dist = value;
1680 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1682 FLAC__ASSERT(0 != encoder);
1683 FLAC__ASSERT(0 != encoder->private_);
1684 FLAC__ASSERT(0 != encoder->protected_);
1685 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1687 encoder->protected_->total_samples_estimate = value;
1691 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1693 FLAC__ASSERT(0 != encoder);
1694 FLAC__ASSERT(0 != encoder->private_);
1695 FLAC__ASSERT(0 != encoder->protected_);
1696 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1702 /* realloc() does not do exactly what we want so... */
1703 if(encoder->protected_->metadata) {
1704 free(encoder->protected_->metadata);
1705 encoder->protected_->metadata = 0;
1706 encoder->protected_->num_metadata_blocks = 0;
1709 FLAC__StreamMetadata **m;
1710 if(0 == (m = safe_malloc_mul_2op_p(sizeof(m[0]), /*times*/num_blocks)))
1712 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1713 encoder->protected_->metadata = m;
1714 encoder->protected_->num_metadata_blocks = num_blocks;
1717 if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1724 * These three functions are not static, but not publically exposed in
1725 * include/FLAC/ either. They are used by the test suite.
1727 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1729 FLAC__ASSERT(0 != encoder);
1730 FLAC__ASSERT(0 != encoder->private_);
1731 FLAC__ASSERT(0 != encoder->protected_);
1732 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1734 encoder->private_->disable_constant_subframes = value;
1738 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1740 FLAC__ASSERT(0 != encoder);
1741 FLAC__ASSERT(0 != encoder->private_);
1742 FLAC__ASSERT(0 != encoder->protected_);
1743 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1745 encoder->private_->disable_fixed_subframes = value;
1749 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1751 FLAC__ASSERT(0 != encoder);
1752 FLAC__ASSERT(0 != encoder->private_);
1753 FLAC__ASSERT(0 != encoder->protected_);
1754 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1756 encoder->private_->disable_verbatim_subframes = value;
1760 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1762 FLAC__ASSERT(0 != encoder);
1763 FLAC__ASSERT(0 != encoder->private_);
1764 FLAC__ASSERT(0 != encoder->protected_);
1765 return encoder->protected_->state;
1768 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1770 FLAC__ASSERT(0 != encoder);
1771 FLAC__ASSERT(0 != encoder->private_);
1772 FLAC__ASSERT(0 != encoder->protected_);
1773 if(encoder->protected_->verify)
1774 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1776 return FLAC__STREAM_DECODER_UNINITIALIZED;
1779 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1781 FLAC__ASSERT(0 != encoder);
1782 FLAC__ASSERT(0 != encoder->private_);
1783 FLAC__ASSERT(0 != encoder->protected_);
1784 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1785 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1787 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1790 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)
1792 FLAC__ASSERT(0 != encoder);
1793 FLAC__ASSERT(0 != encoder->private_);
1794 FLAC__ASSERT(0 != encoder->protected_);
1795 if(0 != absolute_sample)
1796 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1797 if(0 != frame_number)
1798 *frame_number = encoder->private_->verify.error_stats.frame_number;
1800 *channel = encoder->private_->verify.error_stats.channel;
1802 *sample = encoder->private_->verify.error_stats.sample;
1804 *expected = encoder->private_->verify.error_stats.expected;
1806 *got = encoder->private_->verify.error_stats.got;
1809 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1811 FLAC__ASSERT(0 != encoder);
1812 FLAC__ASSERT(0 != encoder->private_);
1813 FLAC__ASSERT(0 != encoder->protected_);
1814 return encoder->protected_->verify;
1817 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1819 FLAC__ASSERT(0 != encoder);
1820 FLAC__ASSERT(0 != encoder->private_);
1821 FLAC__ASSERT(0 != encoder->protected_);
1822 return encoder->protected_->streamable_subset;
1825 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
1827 FLAC__ASSERT(0 != encoder);
1828 FLAC__ASSERT(0 != encoder->private_);
1829 FLAC__ASSERT(0 != encoder->protected_);
1830 return encoder->protected_->do_md5;
1833 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1835 FLAC__ASSERT(0 != encoder);
1836 FLAC__ASSERT(0 != encoder->private_);
1837 FLAC__ASSERT(0 != encoder->protected_);
1838 return encoder->protected_->channels;
1841 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1843 FLAC__ASSERT(0 != encoder);
1844 FLAC__ASSERT(0 != encoder->private_);
1845 FLAC__ASSERT(0 != encoder->protected_);
1846 return encoder->protected_->bits_per_sample;
1849 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1851 FLAC__ASSERT(0 != encoder);
1852 FLAC__ASSERT(0 != encoder->private_);
1853 FLAC__ASSERT(0 != encoder->protected_);
1854 return encoder->protected_->sample_rate;
1857 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1859 FLAC__ASSERT(0 != encoder);
1860 FLAC__ASSERT(0 != encoder->private_);
1861 FLAC__ASSERT(0 != encoder->protected_);
1862 return encoder->protected_->blocksize;
1865 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1867 FLAC__ASSERT(0 != encoder);
1868 FLAC__ASSERT(0 != encoder->private_);
1869 FLAC__ASSERT(0 != encoder->protected_);
1870 return encoder->protected_->do_mid_side_stereo;
1873 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1875 FLAC__ASSERT(0 != encoder);
1876 FLAC__ASSERT(0 != encoder->private_);
1877 FLAC__ASSERT(0 != encoder->protected_);
1878 return encoder->protected_->loose_mid_side_stereo;
1881 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1883 FLAC__ASSERT(0 != encoder);
1884 FLAC__ASSERT(0 != encoder->private_);
1885 FLAC__ASSERT(0 != encoder->protected_);
1886 return encoder->protected_->max_lpc_order;
1889 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1891 FLAC__ASSERT(0 != encoder);
1892 FLAC__ASSERT(0 != encoder->private_);
1893 FLAC__ASSERT(0 != encoder->protected_);
1894 return encoder->protected_->qlp_coeff_precision;
1897 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1899 FLAC__ASSERT(0 != encoder);
1900 FLAC__ASSERT(0 != encoder->private_);
1901 FLAC__ASSERT(0 != encoder->protected_);
1902 return encoder->protected_->do_qlp_coeff_prec_search;
1905 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1907 FLAC__ASSERT(0 != encoder);
1908 FLAC__ASSERT(0 != encoder->private_);
1909 FLAC__ASSERT(0 != encoder->protected_);
1910 return encoder->protected_->do_escape_coding;
1913 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1915 FLAC__ASSERT(0 != encoder);
1916 FLAC__ASSERT(0 != encoder->private_);
1917 FLAC__ASSERT(0 != encoder->protected_);
1918 return encoder->protected_->do_exhaustive_model_search;
1921 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1923 FLAC__ASSERT(0 != encoder);
1924 FLAC__ASSERT(0 != encoder->private_);
1925 FLAC__ASSERT(0 != encoder->protected_);
1926 return encoder->protected_->min_residual_partition_order;
1929 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1931 FLAC__ASSERT(0 != encoder);
1932 FLAC__ASSERT(0 != encoder->private_);
1933 FLAC__ASSERT(0 != encoder->protected_);
1934 return encoder->protected_->max_residual_partition_order;
1937 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1939 FLAC__ASSERT(0 != encoder);
1940 FLAC__ASSERT(0 != encoder->private_);
1941 FLAC__ASSERT(0 != encoder->protected_);
1942 return encoder->protected_->rice_parameter_search_dist;
1945 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1947 FLAC__ASSERT(0 != encoder);
1948 FLAC__ASSERT(0 != encoder->private_);
1949 FLAC__ASSERT(0 != encoder->protected_);
1950 return encoder->protected_->total_samples_estimate;
1953 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1955 unsigned i, j = 0, channel;
1956 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1958 FLAC__ASSERT(0 != encoder);
1959 FLAC__ASSERT(0 != encoder->private_);
1960 FLAC__ASSERT(0 != encoder->protected_);
1961 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1964 const unsigned n = flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
1966 if(encoder->protected_->verify)
1967 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
1969 for(channel = 0; channel < channels; channel++)
1970 memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
1972 if(encoder->protected_->do_mid_side_stereo) {
1973 FLAC__ASSERT(channels == 2);
1974 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
1975 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1976 encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
1977 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' ! */
1983 encoder->private_->current_sample_number += n;
1985 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
1986 if(encoder->private_->current_sample_number > blocksize) {
1987 FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
1988 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
1989 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
1991 /* move unprocessed overread samples to beginnings of arrays */
1992 for(channel = 0; channel < channels; channel++)
1993 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
1994 if(encoder->protected_->do_mid_side_stereo) {
1995 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
1996 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
1998 encoder->private_->current_sample_number = 1;
2000 } while(j < samples);
2005 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2007 unsigned i, j, k, channel;
2008 FLAC__int32 x, mid, side;
2009 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2011 FLAC__ASSERT(0 != encoder);
2012 FLAC__ASSERT(0 != encoder->private_);
2013 FLAC__ASSERT(0 != encoder->protected_);
2014 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2018 * we have several flavors of the same basic loop, optimized for
2019 * different conditions:
2021 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2023 * stereo coding: unroll channel loop
2026 if(encoder->protected_->verify)
2027 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2029 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2030 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2031 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2033 encoder->private_->integer_signal[1][i] = x;
2036 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2037 encoder->private_->integer_signal_mid_side[1][i] = side;
2038 encoder->private_->integer_signal_mid_side[0][i] = mid;
2040 encoder->private_->current_sample_number = i;
2041 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2043 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2045 /* move unprocessed overread samples to beginnings of arrays */
2046 FLAC__ASSERT(i == blocksize+OVERREAD_);
2047 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2048 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
2049 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
2050 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2051 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2052 encoder->private_->current_sample_number = 1;
2054 } while(j < samples);
2058 * independent channel coding: buffer each channel in inner loop
2061 if(encoder->protected_->verify)
2062 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2064 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2065 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2066 for(channel = 0; channel < channels; channel++)
2067 encoder->private_->integer_signal[channel][i] = buffer[k++];
2069 encoder->private_->current_sample_number = i;
2070 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2072 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2074 /* move unprocessed overread samples to beginnings of arrays */
2075 FLAC__ASSERT(i == blocksize+OVERREAD_);
2076 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2077 for(channel = 0; channel < channels; channel++)
2078 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2079 encoder->private_->current_sample_number = 1;
2081 } while(j < samples);
2087 /***********************************************************************
2089 * Private class methods
2091 ***********************************************************************/
2093 void set_defaults_(FLAC__StreamEncoder *encoder)
2095 FLAC__ASSERT(0 != encoder);
2097 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2098 encoder->protected_->verify = true;
2100 encoder->protected_->verify = false;
2102 encoder->protected_->streamable_subset = true;
2103 encoder->protected_->do_md5 = true;
2104 encoder->protected_->do_mid_side_stereo = false;
2105 encoder->protected_->loose_mid_side_stereo = false;
2106 encoder->protected_->channels = 2;
2107 encoder->protected_->bits_per_sample = 16;
2108 encoder->protected_->sample_rate = 44100;
2109 encoder->protected_->blocksize = 0;
2110 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2111 encoder->protected_->num_apodizations = 1;
2112 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2113 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2115 encoder->protected_->max_lpc_order = 0;
2116 encoder->protected_->qlp_coeff_precision = 0;
2117 encoder->protected_->do_qlp_coeff_prec_search = false;
2118 encoder->protected_->do_exhaustive_model_search = false;
2119 encoder->protected_->do_escape_coding = false;
2120 encoder->protected_->min_residual_partition_order = 0;
2121 encoder->protected_->max_residual_partition_order = 0;
2122 encoder->protected_->rice_parameter_search_dist = 0;
2123 encoder->protected_->total_samples_estimate = 0;
2124 encoder->protected_->metadata = 0;
2125 encoder->protected_->num_metadata_blocks = 0;
2127 encoder->private_->seek_table = 0;
2128 encoder->private_->disable_constant_subframes = false;
2129 encoder->private_->disable_fixed_subframes = false;
2130 encoder->private_->disable_verbatim_subframes = false;
2132 encoder->private_->is_ogg = false;
2134 encoder->private_->read_callback = 0;
2135 encoder->private_->write_callback = 0;
2136 encoder->private_->seek_callback = 0;
2137 encoder->private_->tell_callback = 0;
2138 encoder->private_->metadata_callback = 0;
2139 encoder->private_->progress_callback = 0;
2140 encoder->private_->client_data = 0;
2143 FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2146 FLAC__stream_encoder_set_compression_level(encoder, 5);
2149 void free_(FLAC__StreamEncoder *encoder)
2151 unsigned i, channel;
2153 FLAC__ASSERT(0 != encoder);
2154 if(encoder->protected_->metadata) {
2155 free(encoder->protected_->metadata);
2156 encoder->protected_->metadata = 0;
2157 encoder->protected_->num_metadata_blocks = 0;
2159 for(i = 0; i < encoder->protected_->channels; i++) {
2160 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2161 free(encoder->private_->integer_signal_unaligned[i]);
2162 encoder->private_->integer_signal_unaligned[i] = 0;
2164 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2165 if(0 != encoder->private_->real_signal_unaligned[i]) {
2166 free(encoder->private_->real_signal_unaligned[i]);
2167 encoder->private_->real_signal_unaligned[i] = 0;
2171 for(i = 0; i < 2; i++) {
2172 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2173 free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2174 encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2176 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2177 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2178 free(encoder->private_->real_signal_mid_side_unaligned[i]);
2179 encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2183 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2184 for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2185 if(0 != encoder->private_->window_unaligned[i]) {
2186 free(encoder->private_->window_unaligned[i]);
2187 encoder->private_->window_unaligned[i] = 0;
2190 if(0 != encoder->private_->windowed_signal_unaligned) {
2191 free(encoder->private_->windowed_signal_unaligned);
2192 encoder->private_->windowed_signal_unaligned = 0;
2195 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2196 for(i = 0; i < 2; i++) {
2197 if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2198 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2199 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2203 for(channel = 0; channel < 2; channel++) {
2204 for(i = 0; i < 2; i++) {
2205 if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2206 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2207 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2211 if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2212 free(encoder->private_->abs_residual_partition_sums_unaligned);
2213 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2215 if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2216 free(encoder->private_->raw_bits_per_partition_unaligned);
2217 encoder->private_->raw_bits_per_partition_unaligned = 0;
2219 if(encoder->protected_->verify) {
2220 for(i = 0; i < encoder->protected_->channels; i++) {
2221 if(0 != encoder->private_->verify.input_fifo.data[i]) {
2222 free(encoder->private_->verify.input_fifo.data[i]);
2223 encoder->private_->verify.input_fifo.data[i] = 0;
2227 FLAC__bitwriter_free(encoder->private_->frame);
2230 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2233 unsigned i, channel;
2235 FLAC__ASSERT(new_blocksize > 0);
2236 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2237 FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2239 /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2240 if(new_blocksize <= encoder->private_->input_capacity)
2245 /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
2246 * requires that the input arrays (in our case the integer signals)
2247 * have a buffer of up to 3 zeroes in front (at negative indices) for
2248 * alignment purposes; we use 4 in front to keep the data well-aligned.
2251 for(i = 0; ok && i < encoder->protected_->channels; i++) {
2252 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2253 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2254 encoder->private_->integer_signal[i] += 4;
2255 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2256 #if 0 /* @@@ currently unused */
2257 if(encoder->protected_->max_lpc_order > 0)
2258 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2262 for(i = 0; ok && i < 2; i++) {
2263 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]);
2264 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2265 encoder->private_->integer_signal_mid_side[i] += 4;
2266 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2267 #if 0 /* @@@ currently unused */
2268 if(encoder->protected_->max_lpc_order > 0)
2269 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]);
2273 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2274 if(ok && encoder->protected_->max_lpc_order > 0) {
2275 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2276 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2277 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2280 for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2281 for(i = 0; ok && i < 2; i++) {
2282 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2285 for(channel = 0; ok && channel < 2; channel++) {
2286 for(i = 0; ok && i < 2; i++) {
2287 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]);
2290 /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2291 /*@@@ 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) */
2292 ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2293 if(encoder->protected_->do_escape_coding)
2294 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2296 /* now adjust the windows if the blocksize has changed */
2297 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2298 if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2299 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2300 switch(encoder->protected_->apodizations[i].type) {
2301 case FLAC__APODIZATION_BARTLETT:
2302 FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2304 case FLAC__APODIZATION_BARTLETT_HANN:
2305 FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2307 case FLAC__APODIZATION_BLACKMAN:
2308 FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2310 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2311 FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2313 case FLAC__APODIZATION_CONNES:
2314 FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2316 case FLAC__APODIZATION_FLATTOP:
2317 FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2319 case FLAC__APODIZATION_GAUSS:
2320 FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2322 case FLAC__APODIZATION_HAMMING:
2323 FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2325 case FLAC__APODIZATION_HANN:
2326 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2328 case FLAC__APODIZATION_KAISER_BESSEL:
2329 FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2331 case FLAC__APODIZATION_NUTTALL:
2332 FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2334 case FLAC__APODIZATION_RECTANGLE:
2335 FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2337 case FLAC__APODIZATION_TRIANGLE:
2338 FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2340 case FLAC__APODIZATION_TUKEY:
2341 FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2343 case FLAC__APODIZATION_WELCH:
2344 FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2348 /* double protection */
2349 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2357 encoder->private_->input_capacity = new_blocksize;
2359 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2364 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2366 const FLAC__byte *buffer;
2369 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2371 if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2372 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2376 if(encoder->protected_->verify) {
2377 encoder->private_->verify.output.data = buffer;
2378 encoder->private_->verify.output.bytes = bytes;
2379 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2380 encoder->private_->verify.needs_magic_hack = true;
2383 if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2384 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2385 FLAC__bitwriter_clear(encoder->private_->frame);
2386 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2387 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2393 if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2394 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2395 FLAC__bitwriter_clear(encoder->private_->frame);
2396 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2400 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2401 FLAC__bitwriter_clear(encoder->private_->frame);
2404 encoder->private_->streaminfo.data.stream_info.min_framesize = flac_min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2405 encoder->private_->streaminfo.data.stream_info.max_framesize = flac_max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2411 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2413 FLAC__StreamEncoderWriteStatus status;
2414 FLAC__uint64 output_position = 0;
2416 /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2417 if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2418 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2419 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2423 * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2426 FLAC__MetadataType type = (buffer[0] & 0x7f);
2427 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2428 encoder->protected_->streaminfo_offset = output_position;
2429 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2430 encoder->protected_->seektable_offset = output_position;
2434 * Mark the current seek point if hit (if audio_offset == 0 that
2435 * means we're still writing metadata and haven't hit the first
2438 if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2439 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2440 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2441 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2442 FLAC__uint64 test_sample;
2444 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2445 test_sample = encoder->private_->seek_table->points[i].sample_number;
2446 if(test_sample > frame_last_sample) {
2449 else if(test_sample >= frame_first_sample) {
2450 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2451 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2452 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2453 encoder->private_->first_seekpoint_to_check++;
2454 /* DO NOT: "break;" and here's why:
2455 * The seektable template may contain more than one target
2456 * sample for any given frame; we will keep looping, generating
2457 * duplicate seekpoints for them, and we'll clean it up later,
2458 * just before writing the seektable back to the metadata.
2462 encoder->private_->first_seekpoint_to_check++;
2468 if(encoder->private_->is_ogg) {
2469 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2470 &encoder->protected_->ogg_encoder_aspect,
2474 encoder->private_->current_frame_number,
2476 (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2478 encoder->private_->client_data
2483 status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2485 if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2486 encoder->private_->bytes_written += bytes;
2487 encoder->private_->samples_written += samples;
2488 /* we keep a high watermark on the number of frames written because
2489 * when the encoder goes back to write metadata, 'current_frame'
2490 * will drop back to 0.
2492 encoder->private_->frames_written = flac_max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2495 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2500 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2501 void update_metadata_(const FLAC__StreamEncoder *encoder)
2503 FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2504 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2505 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2506 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2507 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2508 const unsigned bps = metadata->data.stream_info.bits_per_sample;
2509 FLAC__StreamEncoderSeekStatus seek_status;
2511 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2513 /* All this is based on intimate knowledge of the stream header
2514 * layout, but a change to the header format that would break this
2515 * would also break all streams encoded in the previous format.
2519 * Write MD5 signature
2522 const unsigned md5_offset =
2523 FLAC__STREAM_METADATA_HEADER_LENGTH +
2525 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2526 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2527 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2528 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2529 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2530 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2531 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2532 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2535 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2536 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2537 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2540 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2541 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2547 * Write total samples
2550 const unsigned total_samples_byte_offset =
2551 FLAC__STREAM_METADATA_HEADER_LENGTH +
2553 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2554 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2555 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2556 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2557 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2558 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2559 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2563 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2564 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2565 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2566 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2567 b[4] = (FLAC__byte)(samples & 0xFF);
2568 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) {
2569 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2570 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2573 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2574 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2580 * Write min/max framesize
2583 const unsigned min_framesize_offset =
2584 FLAC__STREAM_METADATA_HEADER_LENGTH +
2586 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2587 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2590 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2591 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2592 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2593 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2594 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2595 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2596 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) {
2597 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2598 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2601 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2602 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2610 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2613 FLAC__format_seektable_sort(encoder->private_->seek_table);
2615 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2617 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) {
2618 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2619 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2623 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2626 xx = encoder->private_->seek_table->points[i].sample_number;
2627 b[7] = (FLAC__byte)xx; xx >>= 8;
2628 b[6] = (FLAC__byte)xx; xx >>= 8;
2629 b[5] = (FLAC__byte)xx; xx >>= 8;
2630 b[4] = (FLAC__byte)xx; xx >>= 8;
2631 b[3] = (FLAC__byte)xx; xx >>= 8;
2632 b[2] = (FLAC__byte)xx; xx >>= 8;
2633 b[1] = (FLAC__byte)xx; xx >>= 8;
2634 b[0] = (FLAC__byte)xx; xx >>= 8;
2635 xx = encoder->private_->seek_table->points[i].stream_offset;
2636 b[15] = (FLAC__byte)xx; xx >>= 8;
2637 b[14] = (FLAC__byte)xx; xx >>= 8;
2638 b[13] = (FLAC__byte)xx; xx >>= 8;
2639 b[12] = (FLAC__byte)xx; xx >>= 8;
2640 b[11] = (FLAC__byte)xx; xx >>= 8;
2641 b[10] = (FLAC__byte)xx; xx >>= 8;
2642 b[9] = (FLAC__byte)xx; xx >>= 8;
2643 b[8] = (FLAC__byte)xx; xx >>= 8;
2644 x = encoder->private_->seek_table->points[i].frame_samples;
2645 b[17] = (FLAC__byte)x; x >>= 8;
2646 b[16] = (FLAC__byte)x; x >>= 8;
2647 if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2648 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2656 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2657 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2659 /* the # of bytes in the 1st packet that precede the STREAMINFO */
2660 static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2661 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2662 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2663 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2664 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2665 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2666 FLAC__STREAM_SYNC_LENGTH
2668 FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2669 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2670 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2671 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2672 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2675 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2676 FLAC__ASSERT(0 != encoder->private_->seek_callback);
2678 /* Pre-check that client supports seeking, since we don't want the
2679 * ogg_helper code to ever have to deal with this condition.
2681 if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2684 /* All this is based on intimate knowledge of the stream header
2685 * layout, but a change to the header format that would break this
2686 * would also break all streams encoded in the previous format.
2690 ** Write STREAMINFO stats
2692 simple_ogg_page__init(&page);
2693 if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2694 simple_ogg_page__clear(&page);
2695 return; /* state already set */
2699 * Write MD5 signature
2702 const unsigned md5_offset =
2703 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2704 FLAC__STREAM_METADATA_HEADER_LENGTH +
2706 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2707 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2708 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2709 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2710 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2711 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2712 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2713 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2716 if(md5_offset + 16 > (unsigned)page.body_len) {
2717 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2718 simple_ogg_page__clear(&page);
2721 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2725 * Write total samples
2728 const unsigned total_samples_byte_offset =
2729 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2730 FLAC__STREAM_METADATA_HEADER_LENGTH +
2732 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2733 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2734 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2735 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2736 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2737 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2738 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2742 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2743 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2744 simple_ogg_page__clear(&page);
2747 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2748 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2749 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2750 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2751 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2752 b[4] = (FLAC__byte)(samples & 0xFF);
2753 memcpy(page.body + total_samples_byte_offset, b, 5);
2757 * Write min/max framesize
2760 const unsigned min_framesize_offset =
2761 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2762 FLAC__STREAM_METADATA_HEADER_LENGTH +
2764 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2765 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2768 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2769 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2770 simple_ogg_page__clear(&page);
2773 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2774 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2775 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2776 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2777 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2778 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2779 memcpy(page.body + min_framesize_offset, b, 6);
2781 if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2782 simple_ogg_page__clear(&page);
2783 return; /* state already set */
2785 simple_ogg_page__clear(&page);
2790 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2794 FLAC__format_seektable_sort(encoder->private_->seek_table);
2796 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2798 simple_ogg_page__init(&page);
2799 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2800 simple_ogg_page__clear(&page);
2801 return; /* state already set */
2804 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
2805 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2806 simple_ogg_page__clear(&page);
2810 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
2813 xx = encoder->private_->seek_table->points[i].sample_number;
2814 b[7] = (FLAC__byte)xx; xx >>= 8;
2815 b[6] = (FLAC__byte)xx; xx >>= 8;
2816 b[5] = (FLAC__byte)xx; xx >>= 8;
2817 b[4] = (FLAC__byte)xx; xx >>= 8;
2818 b[3] = (FLAC__byte)xx; xx >>= 8;
2819 b[2] = (FLAC__byte)xx; xx >>= 8;
2820 b[1] = (FLAC__byte)xx; xx >>= 8;
2821 b[0] = (FLAC__byte)xx; xx >>= 8;
2822 xx = encoder->private_->seek_table->points[i].stream_offset;
2823 b[15] = (FLAC__byte)xx; xx >>= 8;
2824 b[14] = (FLAC__byte)xx; xx >>= 8;
2825 b[13] = (FLAC__byte)xx; xx >>= 8;
2826 b[12] = (FLAC__byte)xx; xx >>= 8;
2827 b[11] = (FLAC__byte)xx; xx >>= 8;
2828 b[10] = (FLAC__byte)xx; xx >>= 8;
2829 b[9] = (FLAC__byte)xx; xx >>= 8;
2830 b[8] = (FLAC__byte)xx; xx >>= 8;
2831 x = encoder->private_->seek_table->points[i].frame_samples;
2832 b[17] = (FLAC__byte)x; x >>= 8;
2833 b[16] = (FLAC__byte)x; x >>= 8;
2837 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2838 simple_ogg_page__clear(&page);
2839 return; /* state already set */
2841 simple_ogg_page__clear(&page);
2846 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
2849 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2852 * Accumulate raw signal to the MD5 signature
2854 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)) {
2855 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2860 * Process the frame header and subframes into the frame bitbuffer
2862 if(!process_subframes_(encoder, is_fractional_block)) {
2863 /* the above function sets the state for us in case of an error */
2868 * Zero-pad the frame to a byte_boundary
2870 if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
2871 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2876 * CRC-16 the whole thing
2878 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2880 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
2881 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
2883 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2890 if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
2891 /* the above function sets the state for us in case of an error */
2896 * Get ready for the next frame
2898 encoder->private_->current_sample_number = 0;
2899 encoder->private_->current_frame_number++;
2900 encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
2905 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
2907 FLAC__FrameHeader frame_header;
2908 unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
2909 FLAC__bool do_independent, do_mid_side;
2912 * Calculate the min,max Rice partition orders
2914 if(is_fractional_block) {
2915 max_partition_order = 0;
2918 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
2919 max_partition_order = flac_min(max_partition_order, encoder->protected_->max_residual_partition_order);
2921 min_partition_order = flac_min(min_partition_order, max_partition_order);
2926 frame_header.blocksize = encoder->protected_->blocksize;
2927 frame_header.sample_rate = encoder->protected_->sample_rate;
2928 frame_header.channels = encoder->protected_->channels;
2929 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
2930 frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
2931 frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2932 frame_header.number.frame_number = encoder->private_->current_frame_number;
2935 * Figure out what channel assignments to try
2937 if(encoder->protected_->do_mid_side_stereo) {
2938 if(encoder->protected_->loose_mid_side_stereo) {
2939 if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
2940 do_independent = true;
2944 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
2945 do_mid_side = !do_independent;
2949 do_independent = true;
2954 do_independent = true;
2955 do_mid_side = false;
2958 FLAC__ASSERT(do_independent || do_mid_side);
2961 * Check for wasted bits; set effective bps for each subframe
2963 if(do_independent) {
2964 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2965 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
2966 encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
2967 encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
2971 FLAC__ASSERT(encoder->protected_->channels == 2);
2972 for(channel = 0; channel < 2; channel++) {
2973 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
2974 encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
2975 encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
2980 * First do a normal encoding pass of each independent channel
2982 if(do_independent) {
2983 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2987 min_partition_order,
2988 max_partition_order,
2990 encoder->private_->subframe_bps[channel],
2991 encoder->private_->integer_signal[channel],
2992 encoder->private_->subframe_workspace_ptr[channel],
2993 encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
2994 encoder->private_->residual_workspace[channel],
2995 encoder->private_->best_subframe+channel,
2996 encoder->private_->best_subframe_bits+channel
3004 * Now do mid and side channels if requested
3007 FLAC__ASSERT(encoder->protected_->channels == 2);
3009 for(channel = 0; channel < 2; channel++) {
3013 min_partition_order,
3014 max_partition_order,
3016 encoder->private_->subframe_bps_mid_side[channel],
3017 encoder->private_->integer_signal_mid_side[channel],
3018 encoder->private_->subframe_workspace_ptr_mid_side[channel],
3019 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3020 encoder->private_->residual_workspace_mid_side[channel],
3021 encoder->private_->best_subframe_mid_side+channel,
3022 encoder->private_->best_subframe_bits_mid_side+channel
3030 * Compose the frame bitbuffer
3033 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3034 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3035 FLAC__ChannelAssignment channel_assignment;
3037 FLAC__ASSERT(encoder->protected_->channels == 2);
3039 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3040 channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3043 unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3047 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3048 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
3049 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
3050 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
3051 FLAC__ASSERT(do_independent && do_mid_side);
3053 /* We have to figure out which channel assignent results in the smallest frame */
3054 bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
3055 bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
3056 bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
3057 bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3059 channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3060 min_bits = bits[channel_assignment];
3061 for(ca = 1; ca <= 3; ca++) {
3062 if(bits[ca] < min_bits) {
3063 min_bits = bits[ca];
3064 channel_assignment = (FLAC__ChannelAssignment)ca;
3069 frame_header.channel_assignment = channel_assignment;
3071 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3072 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3076 switch(channel_assignment) {
3077 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3078 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3079 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3081 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3082 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3083 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3085 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3086 left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3087 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3089 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3090 left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3091 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3097 switch(channel_assignment) {
3098 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3099 left_bps = encoder->private_->subframe_bps [0];
3100 right_bps = encoder->private_->subframe_bps [1];
3102 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3103 left_bps = encoder->private_->subframe_bps [0];
3104 right_bps = encoder->private_->subframe_bps_mid_side[1];
3106 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3107 left_bps = encoder->private_->subframe_bps_mid_side[1];
3108 right_bps = encoder->private_->subframe_bps [1];
3110 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3111 left_bps = encoder->private_->subframe_bps_mid_side[0];
3112 right_bps = encoder->private_->subframe_bps_mid_side[1];
3118 /* note that encoder_add_subframe_ sets the state for us in case of an error */
3119 if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3121 if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3125 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3126 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3130 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3131 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)) {
3132 /* the above function sets the state for us in case of an error */
3138 if(encoder->protected_->loose_mid_side_stereo) {
3139 encoder->private_->loose_mid_side_stereo_frame_count++;
3140 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3141 encoder->private_->loose_mid_side_stereo_frame_count = 0;
3144 encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3149 FLAC__bool process_subframe_(
3150 FLAC__StreamEncoder *encoder,
3151 unsigned min_partition_order,
3152 unsigned max_partition_order,
3153 const FLAC__FrameHeader *frame_header,
3154 unsigned subframe_bps,
3155 const FLAC__int32 integer_signal[],
3156 FLAC__Subframe *subframe[2],
3157 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3158 FLAC__int32 *residual[2],
3159 unsigned *best_subframe,
3163 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3164 FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3166 FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3168 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3169 FLAC__double lpc_residual_bits_per_sample;
3170 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 */
3171 FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3172 unsigned min_lpc_order, max_lpc_order, lpc_order;
3173 unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3175 unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3176 unsigned rice_parameter;
3177 unsigned _candidate_bits, _best_bits;
3178 unsigned _best_subframe;
3179 /* only use RICE2 partitions if stream bps > 16 */
3180 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;
3182 FLAC__ASSERT(frame_header->blocksize > 0);
3184 /* verbatim subframe is the baseline against which we measure other compressed subframes */
3186 if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3187 _best_bits = UINT_MAX;
3189 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3191 if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3192 unsigned signal_is_constant = false;
3193 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);
3194 /* check for constant subframe */
3196 !encoder->private_->disable_constant_subframes &&
3197 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3198 fixed_residual_bits_per_sample[1] == 0.0
3200 fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3203 /* the above means it's possible all samples are the same value; now double-check it: */
3205 signal_is_constant = true;
3206 for(i = 1; i < frame_header->blocksize; i++) {
3207 if(integer_signal[0] != integer_signal[i]) {
3208 signal_is_constant = false;
3213 if(signal_is_constant) {
3214 _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3215 if(_candidate_bits < _best_bits) {
3216 _best_subframe = !_best_subframe;
3217 _best_bits = _candidate_bits;
3221 if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3223 if(encoder->protected_->do_exhaustive_model_search) {
3224 min_fixed_order = 0;
3225 max_fixed_order = FLAC__MAX_FIXED_ORDER;
3228 min_fixed_order = max_fixed_order = guess_fixed_order;
3230 if(max_fixed_order >= frame_header->blocksize)
3231 max_fixed_order = frame_header->blocksize - 1;
3232 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3233 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3234 if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3235 continue; /* don't even try */
3236 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 */
3238 if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3239 continue; /* don't even try */
3240 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 */
3242 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3243 if(rice_parameter >= rice_parameter_limit) {
3244 #ifdef DEBUG_VERBOSE
3245 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
3247 rice_parameter = rice_parameter_limit - 1;
3250 evaluate_fixed_subframe_(
3253 residual[!_best_subframe],
3254 encoder->private_->abs_residual_partition_sums,
3255 encoder->private_->raw_bits_per_partition,
3256 frame_header->blocksize,
3260 rice_parameter_limit,
3261 min_partition_order,
3262 max_partition_order,
3263 encoder->protected_->do_escape_coding,
3264 encoder->protected_->rice_parameter_search_dist,
3265 subframe[!_best_subframe],
3266 partitioned_rice_contents[!_best_subframe]
3268 if(_candidate_bits < _best_bits) {
3269 _best_subframe = !_best_subframe;
3270 _best_bits = _candidate_bits;
3275 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3277 if(encoder->protected_->max_lpc_order > 0) {
3278 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3279 max_lpc_order = frame_header->blocksize-1;
3281 max_lpc_order = encoder->protected_->max_lpc_order;
3282 if(max_lpc_order > 0) {
3284 for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3285 FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3286 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3287 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3288 if(autoc[0] != 0.0) {
3289 FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3290 if(encoder->protected_->do_exhaustive_model_search) {
3294 const unsigned guess_lpc_order =
3295 FLAC__lpc_compute_best_order(
3298 frame_header->blocksize,
3300 encoder->protected_->do_qlp_coeff_prec_search?
3301 FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
3302 encoder->protected_->qlp_coeff_precision
3305 min_lpc_order = max_lpc_order = guess_lpc_order;
3307 if(max_lpc_order >= frame_header->blocksize)
3308 max_lpc_order = frame_header->blocksize - 1;
3309 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
3310 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
3311 if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
3312 continue; /* don't even try */
3313 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
3314 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3315 if(rice_parameter >= rice_parameter_limit) {
3316 #ifdef DEBUG_VERBOSE
3317 fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
3319 rice_parameter = rice_parameter_limit - 1;
3321 if(encoder->protected_->do_qlp_coeff_prec_search) {
3322 min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
3323 /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
3324 if(subframe_bps <= 17) {
3325 max_qlp_coeff_precision = flac_min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
3326 max_qlp_coeff_precision = flac_max(max_qlp_coeff_precision, min_qlp_coeff_precision);
3329 max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
3332 min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
3334 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
3336 evaluate_lpc_subframe_(
3339 residual[!_best_subframe],
3340 encoder->private_->abs_residual_partition_sums,
3341 encoder->private_->raw_bits_per_partition,
3342 encoder->private_->lp_coeff[lpc_order-1],
3343 frame_header->blocksize,
3346 qlp_coeff_precision,
3348 rice_parameter_limit,
3349 min_partition_order,
3350 max_partition_order,
3351 encoder->protected_->do_escape_coding,
3352 encoder->protected_->rice_parameter_search_dist,
3353 subframe[!_best_subframe],
3354 partitioned_rice_contents[!_best_subframe]
3356 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
3357 if(_candidate_bits < _best_bits) {
3358 _best_subframe = !_best_subframe;
3359 _best_bits = _candidate_bits;
3368 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3372 /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3373 if(_best_bits == UINT_MAX) {
3374 FLAC__ASSERT(_best_subframe == 0);
3375 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3378 *best_subframe = _best_subframe;
3379 *best_bits = _best_bits;
3384 FLAC__bool add_subframe_(
3385 FLAC__StreamEncoder *encoder,
3387 unsigned subframe_bps,
3388 const FLAC__Subframe *subframe,
3389 FLAC__BitWriter *frame
3392 switch(subframe->type) {
3393 case FLAC__SUBFRAME_TYPE_CONSTANT:
3394 if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3395 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3399 case FLAC__SUBFRAME_TYPE_FIXED:
3400 if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3401 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3405 case FLAC__SUBFRAME_TYPE_LPC:
3406 if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3407 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3411 case FLAC__SUBFRAME_TYPE_VERBATIM:
3412 if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3413 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3424 #define SPOTCHECK_ESTIMATE 0
3425 #if SPOTCHECK_ESTIMATE
3426 static void spotcheck_subframe_estimate_(
3427 FLAC__StreamEncoder *encoder,
3429 unsigned subframe_bps,
3430 const FLAC__Subframe *subframe,
3435 FLAC__BitWriter *frame = FLAC__bitwriter_new();
3437 fprintf(stderr, "EST: can't allocate frame\n");
3440 if(!FLAC__bitwriter_init(frame)) {
3441 fprintf(stderr, "EST: can't init frame\n");
3444 ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
3447 const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
3448 if(estimate != actual)
3449 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);
3451 FLAC__bitwriter_delete(frame);
3455 unsigned evaluate_constant_subframe_(
3456 FLAC__StreamEncoder *encoder,
3457 const FLAC__int32 signal,
3459 unsigned subframe_bps,
3460 FLAC__Subframe *subframe
3464 subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3465 subframe->data.constant.value = signal;
3467 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
3469 #if SPOTCHECK_ESTIMATE
3470 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3472 (void)encoder, (void)blocksize;
3478 unsigned evaluate_fixed_subframe_(
3479 FLAC__StreamEncoder *encoder,
3480 const FLAC__int32 signal[],
3481 FLAC__int32 residual[],
3482 FLAC__uint64 abs_residual_partition_sums[],
3483 unsigned raw_bits_per_partition[],
3485 unsigned subframe_bps,
3487 unsigned rice_parameter,
3488 unsigned rice_parameter_limit,
3489 unsigned min_partition_order,
3490 unsigned max_partition_order,
3491 FLAC__bool do_escape_coding,
3492 unsigned rice_parameter_search_dist,
3493 FLAC__Subframe *subframe,
3494 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3497 unsigned i, residual_bits, estimate;
3498 const unsigned residual_samples = blocksize - order;
3500 FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3502 subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3504 subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3505 subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3506 subframe->data.fixed.residual = residual;
3509 find_best_partition_order_(
3512 abs_residual_partition_sums,
3513 raw_bits_per_partition,
3517 rice_parameter_limit,
3518 min_partition_order,
3519 max_partition_order,
3522 rice_parameter_search_dist,
3523 &subframe->data.fixed.entropy_coding_method
3526 subframe->data.fixed.order = order;
3527 for(i = 0; i < order; i++)
3528 subframe->data.fixed.warmup[i] = signal[i];
3530 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
3532 #if SPOTCHECK_ESTIMATE
3533 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3539 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3540 unsigned evaluate_lpc_subframe_(
3541 FLAC__StreamEncoder *encoder,
3542 const FLAC__int32 signal[],
3543 FLAC__int32 residual[],
3544 FLAC__uint64 abs_residual_partition_sums[],
3545 unsigned raw_bits_per_partition[],
3546 const FLAC__real lp_coeff[],
3548 unsigned subframe_bps,
3550 unsigned qlp_coeff_precision,
3551 unsigned rice_parameter,
3552 unsigned rice_parameter_limit,
3553 unsigned min_partition_order,
3554 unsigned max_partition_order,
3555 FLAC__bool do_escape_coding,
3556 unsigned rice_parameter_search_dist,
3557 FLAC__Subframe *subframe,
3558 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3561 FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
3562 unsigned i, residual_bits, estimate;
3563 int quantization, ret;
3564 const unsigned residual_samples = blocksize - order;
3566 /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3567 if(subframe_bps <= 16) {
3568 FLAC__ASSERT(order > 0);
3569 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3570 qlp_coeff_precision = flac_min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3573 ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3575 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3577 if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3578 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3579 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3581 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3583 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3585 subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3587 subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3588 subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3589 subframe->data.lpc.residual = residual;
3592 find_best_partition_order_(
3595 abs_residual_partition_sums,
3596 raw_bits_per_partition,
3600 rice_parameter_limit,
3601 min_partition_order,
3602 max_partition_order,
3605 rice_parameter_search_dist,
3606 &subframe->data.lpc.entropy_coding_method
3609 subframe->data.lpc.order = order;
3610 subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3611 subframe->data.lpc.quantization_level = quantization;
3612 memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3613 for(i = 0; i < order; i++)
3614 subframe->data.lpc.warmup[i] = signal[i];
3616 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;
3618 #if SPOTCHECK_ESTIMATE
3619 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3626 unsigned evaluate_verbatim_subframe_(
3627 FLAC__StreamEncoder *encoder,
3628 const FLAC__int32 signal[],
3630 unsigned subframe_bps,
3631 FLAC__Subframe *subframe
3636 subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3638 subframe->data.verbatim.data = signal;
3640 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
3642 #if SPOTCHECK_ESTIMATE
3643 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3651 unsigned find_best_partition_order_(
3652 FLAC__StreamEncoderPrivate *private_,
3653 const FLAC__int32 residual[],
3654 FLAC__uint64 abs_residual_partition_sums[],
3655 unsigned raw_bits_per_partition[],
3656 unsigned residual_samples,
3657 unsigned predictor_order,
3658 unsigned rice_parameter,
3659 unsigned rice_parameter_limit,
3660 unsigned min_partition_order,
3661 unsigned max_partition_order,
3663 FLAC__bool do_escape_coding,
3664 unsigned rice_parameter_search_dist,
3665 FLAC__EntropyCodingMethod *best_ecm
3668 unsigned residual_bits, best_residual_bits = 0;
3669 unsigned best_parameters_index = 0;
3670 unsigned best_partition_order = 0;
3671 const unsigned blocksize = residual_samples + predictor_order;
3673 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3674 min_partition_order = flac_min(min_partition_order, max_partition_order);
3676 precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
3678 if(do_escape_coding)
3679 precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3682 int partition_order;
3685 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3687 set_partitioned_rice_(
3688 #ifdef EXACT_RICE_BITS_CALCULATION
3691 abs_residual_partition_sums+sum,
3692 raw_bits_per_partition+sum,
3696 rice_parameter_limit,
3697 rice_parameter_search_dist,
3698 (unsigned)partition_order,
3700 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3705 FLAC__ASSERT(best_residual_bits != 0);
3708 sum += 1u << partition_order;
3709 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3710 best_residual_bits = residual_bits;
3711 best_parameters_index = !best_parameters_index;
3712 best_partition_order = partition_order;
3717 best_ecm->data.partitioned_rice.order = best_partition_order;
3721 * We are allowed to de-const the pointer based on our special
3722 * knowledge; it is const to the outside world.
3724 FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
3727 /* save best parameters and raw_bits */
3728 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, flac_max(6u, best_partition_order));
3729 memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
3730 if(do_escape_coding)
3731 memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
3733 * Now need to check if the type should be changed to
3734 * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
3735 * size of the rice parameters.
3737 for(partition = 0; partition < (1u<<best_partition_order); partition++) {
3738 if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3739 best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
3745 return best_residual_bits;
3748 #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
3749 extern void precompute_partition_info_sums_32bit_asm_ia32_(
3750 const FLAC__int32 residual[],
3751 FLAC__uint64 abs_residual_partition_sums[],
3753 unsigned predictor_order,
3754 unsigned min_partition_order,
3755 unsigned max_partition_order
3759 void precompute_partition_info_sums_(
3760 const FLAC__int32 residual[],
3761 FLAC__uint64 abs_residual_partition_sums[],
3762 unsigned residual_samples,
3763 unsigned predictor_order,
3764 unsigned min_partition_order,
3765 unsigned max_partition_order,
3769 const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
3770 unsigned partitions = 1u << max_partition_order;
3772 FLAC__ASSERT(default_partition_samples > predictor_order);
3774 #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
3775 /* slightly pessimistic but still catches all common cases */
3776 /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
3777 if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
3778 precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
3783 /* first do max_partition_order */
3785 unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
3786 /* slightly pessimistic but still catches all common cases */
3787 /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
3788 if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
3789 FLAC__uint32 abs_residual_partition_sum;
3791 for(partition = residual_sample = 0; partition < partitions; partition++) {
3792 end += default_partition_samples;
3793 abs_residual_partition_sum = 0;
3794 for( ; residual_sample < end; residual_sample++)
3795 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3796 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3799 else { /* have to pessimistically use 64 bits for accumulator */
3800 FLAC__uint64 abs_residual_partition_sum;
3802 for(partition = residual_sample = 0; partition < partitions; partition++) {
3803 end += default_partition_samples;
3804 abs_residual_partition_sum = 0;
3805 for( ; residual_sample < end; residual_sample++)
3806 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3807 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3812 /* now merge partitions for lower orders */
3814 unsigned from_partition = 0, to_partition = partitions;
3815 int partition_order;
3816 for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
3819 for(i = 0; i < partitions; i++) {
3820 abs_residual_partition_sums[to_partition++] =
3821 abs_residual_partition_sums[from_partition ] +
3822 abs_residual_partition_sums[from_partition+1];
3823 from_partition += 2;
3829 void precompute_partition_info_escapes_(
3830 const FLAC__int32 residual[],
3831 unsigned raw_bits_per_partition[],
3832 unsigned residual_samples,
3833 unsigned predictor_order,
3834 unsigned min_partition_order,
3835 unsigned max_partition_order
3838 int partition_order;
3839 unsigned from_partition, to_partition = 0;
3840 const unsigned blocksize = residual_samples + predictor_order;
3842 /* first do max_partition_order */
3843 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3846 unsigned partition, partition_sample, partition_samples, residual_sample;
3847 const unsigned partitions = 1u << partition_order;
3848 const unsigned default_partition_samples = blocksize >> partition_order;
3850 FLAC__ASSERT(default_partition_samples > predictor_order);
3852 for(partition = residual_sample = 0; partition < partitions; partition++) {
3853 partition_samples = default_partition_samples;
3855 partition_samples -= predictor_order;
3857 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
3858 r = residual[residual_sample++];
3859 /* OPT: maybe faster: rmax |= r ^ (r>>31) */
3865 /* now we know all residual values are in the range [-rmax-1,rmax] */
3866 raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
3868 to_partition = partitions;
3869 break; /*@@@ yuck, should remove the 'for' loop instead */
3872 /* now merge partitions for lower orders */
3873 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
3876 const unsigned partitions = 1u << partition_order;
3877 for(i = 0; i < partitions; i++) {
3878 m = raw_bits_per_partition[from_partition];
3880 raw_bits_per_partition[to_partition] = flac_max(m, raw_bits_per_partition[from_partition]);
3887 #ifdef EXACT_RICE_BITS_CALCULATION
3888 static inline unsigned count_rice_bits_in_partition_(
3889 const unsigned rice_parameter,
3890 const unsigned partition_samples,
3891 const FLAC__int32 *residual
3894 unsigned i, partition_bits =
3895 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 */
3896 (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
3898 for(i = 0; i < partition_samples; i++)
3899 partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
3900 return partition_bits;
3903 static inline unsigned count_rice_bits_in_partition_(
3904 const unsigned rice_parameter,
3905 const unsigned partition_samples,
3906 const FLAC__uint64 abs_residual_partition_sum
3910 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 */
3911 (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
3914 (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
3915 : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
3917 - (partition_samples >> 1)
3918 /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
3919 * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
3920 * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
3921 * So the subtraction term tries to guess how many extra bits were contributed.
3922 * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
3928 FLAC__bool set_partitioned_rice_(
3929 #ifdef EXACT_RICE_BITS_CALCULATION
3930 const FLAC__int32 residual[],
3932 const FLAC__uint64 abs_residual_partition_sums[],
3933 const unsigned raw_bits_per_partition[],
3934 const unsigned residual_samples,
3935 const unsigned predictor_order,
3936 const unsigned suggested_rice_parameter,
3937 const unsigned rice_parameter_limit,
3938 const unsigned rice_parameter_search_dist,
3939 const unsigned partition_order,
3940 const FLAC__bool search_for_escapes,
3941 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3945 unsigned rice_parameter, partition_bits;
3946 unsigned best_partition_bits, best_rice_parameter = 0;
3947 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
3948 unsigned *parameters, *raw_bits;
3949 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3950 unsigned min_rice_parameter, max_rice_parameter;
3952 (void)rice_parameter_search_dist;
3955 FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
3956 FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
3958 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, flac_max(6u, partition_order));
3959 parameters = partitioned_rice_contents->parameters;
3960 raw_bits = partitioned_rice_contents->raw_bits;
3962 if(partition_order == 0) {
3963 best_partition_bits = (unsigned)(-1);
3964 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3965 if(rice_parameter_search_dist) {
3966 if(suggested_rice_parameter < rice_parameter_search_dist)
3967 min_rice_parameter = 0;
3969 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
3970 max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
3971 if(max_rice_parameter >= rice_parameter_limit) {
3972 #ifdef DEBUG_VERBOSE
3973 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
3975 max_rice_parameter = rice_parameter_limit - 1;
3979 min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
3981 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3983 rice_parameter = suggested_rice_parameter;
3985 #ifdef EXACT_RICE_BITS_CALCULATION
3986 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
3988 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
3990 if(partition_bits < best_partition_bits) {
3991 best_rice_parameter = rice_parameter;
3992 best_partition_bits = partition_bits;
3994 #ifdef ENABLE_RICE_PARAMETER_SEARCH
3997 if(search_for_escapes) {
3998 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;
3999 if(partition_bits <= best_partition_bits) {
4000 raw_bits[0] = raw_bits_per_partition[0];
4001 best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4002 best_partition_bits = partition_bits;
4007 parameters[0] = best_rice_parameter;
4008 bits_ += best_partition_bits;
4011 unsigned partition, residual_sample;
4012 unsigned partition_samples;
4013 FLAC__uint64 mean, k;
4014 const unsigned partitions = 1u << partition_order;
4015 for(partition = residual_sample = 0; partition < partitions; partition++) {
4016 partition_samples = (residual_samples+predictor_order) >> partition_order;
4017 if(partition == 0) {
4018 if(partition_samples <= predictor_order)
4021 partition_samples -= predictor_order;
4023 mean = abs_residual_partition_sums[partition];
4024 /* we are basically calculating the size in bits of the
4025 * average residual magnitude in the partition:
4026 * rice_parameter = floor(log2(mean/partition_samples))
4027 * 'mean' is not a good name for the variable, it is
4028 * actually the sum of magnitudes of all residual values
4029 * in the partition, so the actual mean is
4030 * mean/partition_samples
4032 for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
4034 if(rice_parameter >= rice_parameter_limit) {
4035 #ifdef DEBUG_VERBOSE
4036 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
4038 rice_parameter = rice_parameter_limit - 1;
4041 best_partition_bits = (unsigned)(-1);
4042 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4043 if(rice_parameter_search_dist) {
4044 if(rice_parameter < rice_parameter_search_dist)
4045 min_rice_parameter = 0;
4047 min_rice_parameter = rice_parameter - rice_parameter_search_dist;
4048 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
4049 if(max_rice_parameter >= rice_parameter_limit) {
4050 #ifdef DEBUG_VERBOSE
4051 fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
4053 max_rice_parameter = rice_parameter_limit - 1;
4057 min_rice_parameter = max_rice_parameter = rice_parameter;
4059 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4061 #ifdef EXACT_RICE_BITS_CALCULATION
4062 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
4064 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
4066 if(partition_bits < best_partition_bits) {
4067 best_rice_parameter = rice_parameter;
4068 best_partition_bits = partition_bits;
4070 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4073 if(search_for_escapes) {
4074 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;
4075 if(partition_bits <= best_partition_bits) {
4076 raw_bits[partition] = raw_bits_per_partition[partition];
4077 best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4078 best_partition_bits = partition_bits;
4081 raw_bits[partition] = 0;
4083 parameters[partition] = best_rice_parameter;
4084 bits_ += best_partition_bits;
4085 residual_sample += partition_samples;
4093 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
4098 for(i = 0; i < samples && !(x&1); i++)
4105 for(shift = 0; !(x&1); shift++)
4110 for(i = 0; i < samples; i++)
4111 signal[i] >>= shift;
4117 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4121 for(channel = 0; channel < channels; channel++)
4122 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
4124 fifo->tail += wide_samples;
4126 FLAC__ASSERT(fifo->tail <= fifo->size);
4129 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4132 unsigned sample, wide_sample;
4133 unsigned tail = fifo->tail;
4135 sample = input_offset * channels;
4136 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
4137 for(channel = 0; channel < channels; channel++)
4138 fifo->data[channel][tail] = input[sample++];
4143 FLAC__ASSERT(fifo->tail <= fifo->size);
4146 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4148 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4149 const size_t encoded_bytes = encoder->private_->verify.output.bytes;
4152 if(encoder->private_->verify.needs_magic_hack) {
4153 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
4154 *bytes = FLAC__STREAM_SYNC_LENGTH;
4155 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
4156 encoder->private_->verify.needs_magic_hack = false;
4159 if(encoded_bytes == 0) {
4161 * If we get here, a FIFO underflow has occurred,
4162 * which means there is a bug somewhere.
4165 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
4167 else if(encoded_bytes < *bytes)
4168 *bytes = encoded_bytes;
4169 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
4170 encoder->private_->verify.output.data += *bytes;
4171 encoder->private_->verify.output.bytes -= *bytes;
4174 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
4177 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
4179 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
4181 const unsigned channels = frame->header.channels;
4182 const unsigned blocksize = frame->header.blocksize;
4183 const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
4187 for(channel = 0; channel < channels; channel++) {
4188 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
4189 unsigned i, sample = 0;
4190 FLAC__int32 expect = 0, got = 0;
4192 for(i = 0; i < blocksize; i++) {
4193 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
4195 expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
4196 got = (FLAC__int32)buffer[channel][i];
4200 FLAC__ASSERT(i < blocksize);
4201 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
4202 encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
4203 encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
4204 encoder->private_->verify.error_stats.channel = channel;
4205 encoder->private_->verify.error_stats.sample = sample;
4206 encoder->private_->verify.error_stats.expected = expect;
4207 encoder->private_->verify.error_stats.got = got;
4208 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
4209 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
4212 /* dequeue the frame from the fifo */
4213 encoder->private_->verify.input_fifo.tail -= blocksize;
4214 FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
4215 for(channel = 0; channel < channels; channel++)
4216 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]));
4217 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4220 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4222 (void)decoder, (void)metadata, (void)client_data;
4225 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4227 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4228 (void)decoder, (void)status;
4229 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4232 FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4236 *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
4238 if (feof(encoder->private_->file))
4239 return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
4240 else if (ferror(encoder->private_->file))
4241 return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
4243 return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
4246 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4250 if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
4251 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4253 return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4256 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4262 offset = ftello(encoder->private_->file);
4265 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4268 *absolute_byte_offset = (FLAC__uint64)offset;
4269 return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4273 #ifdef FLAC__VALGRIND_TESTING
4274 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4276 size_t ret = fwrite(ptr, size, nmemb, stream);
4282 #define local__fwrite fwrite
4285 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
4287 (void)client_data, (void)current_frame;
4289 if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4290 FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
4292 /* We would like to be able to use 'samples > 0' in the
4293 * clause here but currently because of the nature of our
4294 * Ogg writing implementation, 'samples' is always 0 (see
4295 * ogg_encoder_aspect.c). The downside is extra progress
4298 encoder->private_->is_ogg? true :
4303 /* NOTE: We have to add +bytes, +samples, and +1 to the stats
4304 * because at this point in the callback chain, the stats
4305 * have not been updated. Only after we return and control
4306 * gets back to write_frame_() are the stats updated
4308 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);
4310 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4313 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4317 * This will forcibly set stdout to binary mode (for OSes that require it)
4319 FILE *get_binary_stdout_(void)
4321 /* if something breaks here it is probably due to the presence or
4322 * absence of an underscore before the identifiers 'setmode',
4323 * 'fileno', and/or 'O_BINARY'; check your system header files.
4325 #if defined _MSC_VER || defined __MINGW32__
4326 _setmode(_fileno(stdout), _O_BINARY);
4327 #elif defined __CYGWIN__
4328 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4329 setmode(_fileno(stdout), _O_BINARY);
4330 #elif defined __EMX__
4331 setmode(fileno(stdout), O_BINARY);