1 /* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006 Josh Coalson
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 #if defined _MSC_VER || defined __MINGW32__
37 #include <io.h> /* for _setmode() */
38 #include <fcntl.h> /* for _O_BINARY */
40 #if defined __CYGWIN__ || defined __EMX__
41 #include <io.h> /* for setmode(), O_BINARY */
42 #include <fcntl.h> /* for _O_BINARY */
46 #include <stdlib.h> /* for malloc() */
47 #include <string.h> /* for memcpy() */
48 #include <sys/types.h> /* for off_t */
49 #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
50 #if _MSC_VER <= 1200 || defined __BORLANDC__ /* @@@ [2G limit] */
55 #include "FLAC/assert.h"
56 #include "FLAC/stream_decoder.h"
57 #include "protected/stream_encoder.h"
58 #include "private/bitwriter.h"
59 #include "private/bitmath.h"
60 #include "private/crc.h"
61 #include "private/cpu.h"
62 #include "private/fixed.h"
63 #include "private/format.h"
64 #include "private/lpc.h"
65 #include "private/md5.h"
66 #include "private/memory.h"
68 #include "private/ogg_helper.h"
69 #include "private/ogg_mapping.h"
71 #include "private/stream_encoder_framing.h"
72 #include "private/window.h"
77 #define min(x,y) ((x)<(y)?(x):(y))
82 #define max(x,y) ((x)>(y)?(x):(y))
84 /* Exact Rice codeword length calculation is off by default. The simple
85 * (and fast) estimation (of how many bits a residual value will be
86 * encoded with) in this encoder is very good, almost always yielding
87 * compression within 0.1% of exact calculation.
89 #undef EXACT_RICE_BITS_CALCULATION
90 /* Rice parameter searching is off by default. The simple (and fast)
91 * parameter estimation in this encoder is very good, almost always
92 * yielding compression within 0.1% of the optimal parameters.
94 #undef ENABLE_RICE_PARAMETER_SEARCH
97 FLAC__int32 *data[FLAC__MAX_CHANNELS];
98 unsigned size; /* of each data[] in samples */
103 const FLAC__byte *data;
109 ENCODER_IN_MAGIC = 0,
110 ENCODER_IN_METADATA = 1,
114 static struct CompressionLevels {
115 FLAC__bool do_mid_side_stereo;
116 FLAC__bool loose_mid_side_stereo;
117 unsigned max_lpc_order;
118 unsigned qlp_coeff_precision;
119 FLAC__bool do_qlp_coeff_prec_search;
120 FLAC__bool do_escape_coding;
121 FLAC__bool do_exhaustive_model_search;
122 unsigned min_residual_partition_order;
123 unsigned max_residual_partition_order;
124 unsigned rice_parameter_search_dist;
125 } compression_levels_[] = {
126 { false, false, 0, 0, false, false, false, 2, 2, 0 },
127 { true , true , 0, 0, false, false, false, 2, 2, 0 },
128 { true , false, 0, 0, false, false, false, 0, 3, 0 },
129 { false, false, 6, 0, false, false, false, 3, 3, 0 },
130 { true , true , 8, 0, false, false, false, 3, 3, 0 },
131 { true , false, 8, 0, false, false, false, 3, 3, 0 },
132 { true , false, 8, 0, false, false, false, 0, 4, 0 },
133 { true , false, 8, 0, false, false, true , 0, 6, 0 },
134 { true , false, 12, 0, false, false, true , 0, 6, 0 }
138 /***********************************************************************
140 * Private class method prototypes
142 ***********************************************************************/
144 static void set_defaults_(FLAC__StreamEncoder *encoder);
145 static void free_(FLAC__StreamEncoder *encoder);
146 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
147 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
148 static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
149 static void update_metadata_(const FLAC__StreamEncoder *encoder);
151 static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
153 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
154 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
156 static FLAC__bool process_subframe_(
157 FLAC__StreamEncoder *encoder,
158 unsigned min_partition_order,
159 unsigned max_partition_order,
160 const FLAC__FrameHeader *frame_header,
161 unsigned subframe_bps,
162 const FLAC__int32 integer_signal[],
163 #ifndef FLAC__INTEGER_ONLY_LIBRARY
164 const FLAC__real real_signal[],
166 FLAC__Subframe *subframe[2],
167 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
168 FLAC__int32 *residual[2],
169 unsigned *best_subframe,
173 static FLAC__bool add_subframe_(
174 FLAC__StreamEncoder *encoder,
176 unsigned subframe_bps,
177 const FLAC__Subframe *subframe,
178 FLAC__BitWriter *frame
181 static unsigned evaluate_constant_subframe_(
182 FLAC__StreamEncoder *encoder,
183 const FLAC__int32 signal,
185 unsigned subframe_bps,
186 FLAC__Subframe *subframe
189 static unsigned evaluate_fixed_subframe_(
190 FLAC__StreamEncoder *encoder,
191 const FLAC__int32 signal[],
192 FLAC__int32 residual[],
193 FLAC__uint64 abs_residual_partition_sums[],
194 unsigned raw_bits_per_partition[],
196 unsigned subframe_bps,
198 unsigned rice_parameter,
199 unsigned min_partition_order,
200 unsigned max_partition_order,
201 FLAC__bool do_escape_coding,
202 unsigned rice_parameter_search_dist,
203 FLAC__Subframe *subframe,
204 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
207 #ifndef FLAC__INTEGER_ONLY_LIBRARY
208 static unsigned evaluate_lpc_subframe_(
209 FLAC__StreamEncoder *encoder,
210 const FLAC__int32 signal[],
211 FLAC__int32 residual[],
212 FLAC__uint64 abs_residual_partition_sums[],
213 unsigned raw_bits_per_partition[],
214 const FLAC__real lp_coeff[],
216 unsigned subframe_bps,
218 unsigned qlp_coeff_precision,
219 unsigned rice_parameter,
220 unsigned min_partition_order,
221 unsigned max_partition_order,
222 FLAC__bool do_escape_coding,
223 unsigned rice_parameter_search_dist,
224 FLAC__Subframe *subframe,
225 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
229 static unsigned evaluate_verbatim_subframe_(
230 FLAC__StreamEncoder *encoder,
231 const FLAC__int32 signal[],
233 unsigned subframe_bps,
234 FLAC__Subframe *subframe
237 static unsigned find_best_partition_order_(
238 struct FLAC__StreamEncoderPrivate *private_,
239 const FLAC__int32 residual[],
240 FLAC__uint64 abs_residual_partition_sums[],
241 unsigned raw_bits_per_partition[],
242 unsigned residual_samples,
243 unsigned predictor_order,
244 unsigned rice_parameter,
245 unsigned min_partition_order,
246 unsigned max_partition_order,
247 FLAC__bool do_escape_coding,
248 unsigned rice_parameter_search_dist,
249 FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
252 static void precompute_partition_info_sums_(
253 const FLAC__int32 residual[],
254 FLAC__uint64 abs_residual_partition_sums[],
255 unsigned residual_samples,
256 unsigned predictor_order,
257 unsigned min_partition_order,
258 unsigned max_partition_order
261 static void precompute_partition_info_escapes_(
262 const FLAC__int32 residual[],
263 unsigned raw_bits_per_partition[],
264 unsigned residual_samples,
265 unsigned predictor_order,
266 unsigned min_partition_order,
267 unsigned max_partition_order
270 static FLAC__bool set_partitioned_rice_(
271 #ifdef EXACT_RICE_BITS_CALCULATION
272 const FLAC__int32 residual[],
274 const FLAC__uint64 abs_residual_partition_sums[],
275 const unsigned raw_bits_per_partition[],
276 const unsigned residual_samples,
277 const unsigned predictor_order,
278 const unsigned suggested_rice_parameter,
279 const unsigned rice_parameter_search_dist,
280 const unsigned partition_order,
281 const FLAC__bool search_for_escapes,
282 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
286 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
288 /* verify-related routines: */
289 static void append_to_verify_fifo_(
290 verify_input_fifo *fifo,
291 const FLAC__int32 * const input[],
292 unsigned input_offset,
294 unsigned wide_samples
297 static void append_to_verify_fifo_interleaved_(
298 verify_input_fifo *fifo,
299 const FLAC__int32 input[],
300 unsigned input_offset,
302 unsigned wide_samples
305 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
306 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
307 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
308 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
310 static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
311 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
312 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
313 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);
314 static FILE *get_binary_stdout_();
317 /***********************************************************************
321 ***********************************************************************/
323 typedef struct FLAC__StreamEncoderPrivate {
324 unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
325 FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
326 FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
327 #ifndef FLAC__INTEGER_ONLY_LIBRARY
328 FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* the floating-point version of the input signal */
329 FLAC__real *real_signal_mid_side[2]; /* the floating-point version of the mid-side input signal (stereo only) */
330 FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
331 FLAC__real *windowed_signal; /* the real_signal[] * current window[] */
333 unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
334 unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
335 FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
336 FLAC__int32 *residual_workspace_mid_side[2][2];
337 FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
338 FLAC__Subframe subframe_workspace_mid_side[2][2];
339 FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
340 FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
341 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
342 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
343 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
344 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
345 unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
346 unsigned best_subframe_mid_side[2];
347 unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
348 unsigned best_subframe_bits_mid_side[2];
349 FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
350 unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
351 FLAC__BitWriter *frame; /* the current frame being worked on */
352 unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
353 unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
354 FLAC__ChannelAssignment last_channel_assignment;
355 FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
356 FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
357 unsigned current_sample_number;
358 unsigned current_frame_number;
359 struct FLAC__MD5Context md5context;
360 FLAC__CPUInfo cpuinfo;
361 #ifndef FLAC__INTEGER_ONLY_LIBRARY
362 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
364 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
366 #ifndef FLAC__INTEGER_ONLY_LIBRARY
367 void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
368 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[]);
369 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[]);
370 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[]);
372 FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
373 FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
374 FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
375 FLAC__bool disable_constant_subframes;
376 FLAC__bool disable_fixed_subframes;
377 FLAC__bool disable_verbatim_subframes;
381 FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
382 FLAC__StreamEncoderSeekCallback seek_callback;
383 FLAC__StreamEncoderTellCallback tell_callback;
384 FLAC__StreamEncoderWriteCallback write_callback;
385 FLAC__StreamEncoderMetadataCallback metadata_callback;
386 FLAC__StreamEncoderProgressCallback progress_callback;
388 unsigned first_seekpoint_to_check;
389 FILE *file; /* only used when encoding to a file */
390 FLAC__uint64 bytes_written;
391 FLAC__uint64 samples_written;
392 unsigned frames_written;
393 unsigned total_frames_estimate;
394 /* unaligned (original) pointers to allocated data */
395 FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
396 FLAC__int32 *integer_signal_mid_side_unaligned[2];
397 #ifndef FLAC__INTEGER_ONLY_LIBRARY
398 FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS];
399 FLAC__real *real_signal_mid_side_unaligned[2];
400 FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
401 FLAC__real *windowed_signal_unaligned;
403 FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
404 FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
405 FLAC__uint64 *abs_residual_partition_sums_unaligned;
406 unsigned *raw_bits_per_partition_unaligned;
408 * These fields have been moved here from private function local
409 * declarations merely to save stack space during encoding.
411 #ifndef FLAC__INTEGER_ONLY_LIBRARY
412 FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
414 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
416 * The data for the verify section
419 FLAC__StreamDecoder *decoder;
420 EncoderStateHint state_hint;
421 FLAC__bool needs_magic_hack;
422 verify_input_fifo input_fifo;
423 verify_output output;
425 FLAC__uint64 absolute_sample;
426 unsigned frame_number;
429 FLAC__int32 expected;
433 FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
434 } FLAC__StreamEncoderPrivate;
436 /***********************************************************************
438 * Public static class data
440 ***********************************************************************/
442 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
443 "FLAC__STREAM_ENCODER_OK",
444 "FLAC__STREAM_ENCODER_UNINITIALIZED",
445 "FLAC__STREAM_ENCODER_OGG_ERROR",
446 "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
447 "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
448 "FLAC__STREAM_ENCODER_CLIENT_ERROR",
449 "FLAC__STREAM_ENCODER_IO_ERROR",
450 "FLAC__STREAM_ENCODER_FRAMING_ERROR",
451 "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
454 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
455 "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
456 "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
457 "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
458 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
459 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
460 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
461 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
462 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
463 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
464 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
465 "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
466 "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
467 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
468 "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
471 FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
472 "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
473 "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
474 "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
475 "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
478 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
479 "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
480 "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
483 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
484 "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
485 "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
486 "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
489 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
490 "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
491 "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
492 "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
495 /* Number of samples that will be overread to watch for end of stream. By
496 * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
497 * always try to read blocksize+1 samples before encoding a block, so that
498 * even if the stream has a total sample count that is an integral multiple
499 * of the blocksize, we will still notice when we are encoding the last
500 * block. This is needed, for example, to correctly set the end-of-stream
501 * marker in Ogg FLAC.
503 * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
504 * not really any reason to change it.
506 static const unsigned OVERREAD_ = 1;
508 /***********************************************************************
510 * Class constructor/destructor
513 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new()
515 FLAC__StreamEncoder *encoder;
518 FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
520 encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
525 encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
526 if(encoder->protected_ == 0) {
531 encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
532 if(encoder->private_ == 0) {
533 free(encoder->protected_);
538 encoder->private_->frame = FLAC__bitwriter_new();
539 if(encoder->private_->frame == 0) {
540 free(encoder->private_);
541 free(encoder->protected_);
546 encoder->private_->file = 0;
548 set_defaults_(encoder);
550 encoder->private_->is_being_deleted = false;
552 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
553 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
554 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
556 for(i = 0; i < 2; i++) {
557 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
558 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
560 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
561 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
562 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
564 for(i = 0; i < 2; i++) {
565 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
566 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
569 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
570 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
571 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
573 for(i = 0; i < 2; i++) {
574 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
575 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
577 for(i = 0; i < 2; i++)
578 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
580 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
585 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
589 FLAC__ASSERT(0 != encoder);
590 FLAC__ASSERT(0 != encoder->protected_);
591 FLAC__ASSERT(0 != encoder->private_);
592 FLAC__ASSERT(0 != encoder->private_->frame);
594 encoder->private_->is_being_deleted = true;
596 (void)FLAC__stream_encoder_finish(encoder);
598 if(0 != encoder->private_->verify.decoder)
599 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
601 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
602 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
603 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
605 for(i = 0; i < 2; i++) {
606 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
607 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
609 for(i = 0; i < 2; i++)
610 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
612 FLAC__bitwriter_delete(encoder->private_->frame);
613 free(encoder->private_);
614 free(encoder->protected_);
618 /***********************************************************************
620 * Public class methods
622 ***********************************************************************/
624 static FLAC__StreamEncoderInitStatus init_stream_internal_(
625 FLAC__StreamEncoder *encoder,
626 FLAC__StreamEncoderReadCallback read_callback,
627 FLAC__StreamEncoderWriteCallback write_callback,
628 FLAC__StreamEncoderSeekCallback seek_callback,
629 FLAC__StreamEncoderTellCallback tell_callback,
630 FLAC__StreamEncoderMetadataCallback metadata_callback,
636 FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
638 FLAC__ASSERT(0 != encoder);
640 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
641 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
645 return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
648 if(0 == write_callback || (seek_callback && 0 == tell_callback))
649 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
651 if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
652 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
654 if(encoder->protected_->channels != 2) {
655 encoder->protected_->do_mid_side_stereo = false;
656 encoder->protected_->loose_mid_side_stereo = false;
658 else if(!encoder->protected_->do_mid_side_stereo)
659 encoder->protected_->loose_mid_side_stereo = false;
661 if(encoder->protected_->bits_per_sample >= 32)
662 encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
664 if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
665 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
667 if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
668 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
670 if(encoder->protected_->blocksize == 0) {
671 if(encoder->protected_->max_lpc_order == 0)
672 encoder->protected_->blocksize = 1152;
674 encoder->protected_->blocksize = 4608;
677 if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
678 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
680 if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
681 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
683 if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
684 return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
686 if(encoder->protected_->qlp_coeff_precision == 0) {
687 if(encoder->protected_->bits_per_sample < 16) {
688 /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
689 /* @@@ until then we'll make a guess */
690 encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
692 else if(encoder->protected_->bits_per_sample == 16) {
693 if(encoder->protected_->blocksize <= 192)
694 encoder->protected_->qlp_coeff_precision = 7;
695 else if(encoder->protected_->blocksize <= 384)
696 encoder->protected_->qlp_coeff_precision = 8;
697 else if(encoder->protected_->blocksize <= 576)
698 encoder->protected_->qlp_coeff_precision = 9;
699 else if(encoder->protected_->blocksize <= 1152)
700 encoder->protected_->qlp_coeff_precision = 10;
701 else if(encoder->protected_->blocksize <= 2304)
702 encoder->protected_->qlp_coeff_precision = 11;
703 else if(encoder->protected_->blocksize <= 4608)
704 encoder->protected_->qlp_coeff_precision = 12;
706 encoder->protected_->qlp_coeff_precision = 13;
709 if(encoder->protected_->blocksize <= 384)
710 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
711 else if(encoder->protected_->blocksize <= 1152)
712 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
714 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
716 FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
718 else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
719 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
721 if(encoder->protected_->streamable_subset) {
723 encoder->protected_->blocksize != 192 &&
724 encoder->protected_->blocksize != 576 &&
725 encoder->protected_->blocksize != 1152 &&
726 encoder->protected_->blocksize != 2304 &&
727 encoder->protected_->blocksize != 4608 &&
728 encoder->protected_->blocksize != 256 &&
729 encoder->protected_->blocksize != 512 &&
730 encoder->protected_->blocksize != 1024 &&
731 encoder->protected_->blocksize != 2048 &&
732 encoder->protected_->blocksize != 4096 &&
733 encoder->protected_->blocksize != 8192 &&
734 encoder->protected_->blocksize != 16384
736 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
738 encoder->protected_->sample_rate != 8000 &&
739 encoder->protected_->sample_rate != 16000 &&
740 encoder->protected_->sample_rate != 22050 &&
741 encoder->protected_->sample_rate != 24000 &&
742 encoder->protected_->sample_rate != 32000 &&
743 encoder->protected_->sample_rate != 44100 &&
744 encoder->protected_->sample_rate != 48000 &&
745 encoder->protected_->sample_rate != 96000
747 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
749 encoder->protected_->bits_per_sample != 8 &&
750 encoder->protected_->bits_per_sample != 12 &&
751 encoder->protected_->bits_per_sample != 16 &&
752 encoder->protected_->bits_per_sample != 20 &&
753 encoder->protected_->bits_per_sample != 24
755 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
756 if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
757 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
759 encoder->protected_->sample_rate <= 48000 &&
761 encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
762 encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
765 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
769 if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
770 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
771 if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
772 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
775 /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
776 if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
778 for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
779 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
780 FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
782 encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
783 encoder->protected_->metadata[0] = vc;
789 /* keep track of any SEEKTABLE block */
790 if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
792 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
793 if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
794 encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
795 break; /* take only the first one */
800 /* validate metadata */
801 if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
802 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
803 metadata_has_seektable = false;
804 metadata_has_vorbis_comment = false;
805 metadata_picture_has_type1 = false;
806 metadata_picture_has_type2 = false;
807 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
808 const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
809 if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
810 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
811 else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
812 if(metadata_has_seektable) /* only one is allowed */
813 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
814 metadata_has_seektable = true;
815 if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
816 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
818 else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
819 if(metadata_has_vorbis_comment) /* only one is allowed */
820 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
821 metadata_has_vorbis_comment = true;
823 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
824 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
825 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
827 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
828 if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
829 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
830 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
831 if(metadata_picture_has_type1) /* there should only be 1 per stream */
832 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
833 metadata_picture_has_type1 = true;
834 /* standard icon must be 32x32 pixel PNG */
836 m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
838 (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
839 m->data.picture.width != 32 ||
840 m->data.picture.height != 32
843 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
845 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
846 if(metadata_picture_has_type2) /* there should only be 1 per stream */
847 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
848 metadata_picture_has_type2 = true;
853 encoder->private_->input_capacity = 0;
854 for(i = 0; i < encoder->protected_->channels; i++) {
855 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
856 #ifndef FLAC__INTEGER_ONLY_LIBRARY
857 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
860 for(i = 0; i < 2; i++) {
861 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
862 #ifndef FLAC__INTEGER_ONLY_LIBRARY
863 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
866 #ifndef FLAC__INTEGER_ONLY_LIBRARY
867 for(i = 0; i < encoder->protected_->num_apodizations; i++)
868 encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
869 encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
871 for(i = 0; i < encoder->protected_->channels; i++) {
872 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
873 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
874 encoder->private_->best_subframe[i] = 0;
876 for(i = 0; i < 2; i++) {
877 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
878 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
879 encoder->private_->best_subframe_mid_side[i] = 0;
881 encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
882 encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
883 #ifndef FLAC__INTEGER_ONLY_LIBRARY
884 encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
886 /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
887 /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply÷ by hand */
888 FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
889 FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
890 FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
891 FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
892 encoder->private_->loose_mid_side_stereo_frames = (unsigned)FLAC__fixedpoint_trunc((((FLAC__uint64)(encoder->protected_->sample_rate) * (FLAC__uint64)(26214)) << 16) / (encoder->protected_->blocksize<<16) + FLAC__FP_ONE_HALF);
894 if(encoder->private_->loose_mid_side_stereo_frames == 0)
895 encoder->private_->loose_mid_side_stereo_frames = 1;
896 encoder->private_->loose_mid_side_stereo_frame_count = 0;
897 encoder->private_->current_sample_number = 0;
898 encoder->private_->current_frame_number = 0;
900 encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
901 encoder->private_->use_wide_by_order = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(max(encoder->protected_->max_lpc_order, FLAC__MAX_FIXED_ORDER))+1 > 30); /*@@@ need to use this? */
902 encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
905 * get the CPU info and set the function pointers
907 FLAC__cpu_info(&encoder->private_->cpuinfo);
908 /* first default to the non-asm routines */
909 #ifndef FLAC__INTEGER_ONLY_LIBRARY
910 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
912 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
913 #ifndef FLAC__INTEGER_ONLY_LIBRARY
914 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
915 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
916 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
918 /* now override with asm where appropriate */
919 #ifndef FLAC__INTEGER_ONLY_LIBRARY
920 # ifndef FLAC__NO_ASM
921 if(encoder->private_->cpuinfo.use_asm) {
922 # ifdef FLAC__CPU_IA32
923 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
924 # ifdef FLAC__HAS_NASM
926 if(encoder->private_->cpuinfo.data.ia32.sse) {
927 if(encoder->protected_->max_lpc_order < 4)
928 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
929 else if(encoder->protected_->max_lpc_order < 8)
930 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
931 else if(encoder->protected_->max_lpc_order < 12)
932 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
934 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
937 # endif /* FLAC__SSE_OS */
938 if(encoder->private_->cpuinfo.data.ia32._3dnow)
939 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
941 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
942 if(encoder->private_->cpuinfo.data.ia32.mmx) {
943 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
944 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
947 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
948 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
950 if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
951 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
952 # endif /* FLAC__HAS_NASM */
953 # endif /* FLAC__CPU_IA32 */
955 # endif /* !FLAC__NO_ASM */
956 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
957 /* finally override based on wide-ness if necessary */
958 if(encoder->private_->use_wide_by_block) {
959 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
962 /* set state to OK; from here on, errors are fatal and we'll override the state then */
963 encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
966 encoder->private_->is_ogg = is_ogg;
967 if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
968 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
969 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
973 encoder->private_->read_callback = read_callback;
974 encoder->private_->write_callback = write_callback;
975 encoder->private_->seek_callback = seek_callback;
976 encoder->private_->tell_callback = tell_callback;
977 encoder->private_->metadata_callback = metadata_callback;
978 encoder->private_->client_data = client_data;
980 if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
981 /* the above function sets the state for us in case of an error */
982 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
985 if(!FLAC__bitwriter_init(encoder->private_->frame)) {
986 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
987 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
991 * Set up the verify stuff if necessary
993 if(encoder->protected_->verify) {
995 * First, set up the fifo which will hold the
996 * original signal to compare against
998 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
999 for(i = 0; i < encoder->protected_->channels; i++) {
1000 if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder->private_->verify.input_fifo.size))) {
1001 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1002 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1005 encoder->private_->verify.input_fifo.tail = 0;
1008 * Now set up a stream decoder for verification
1010 encoder->private_->verify.decoder = FLAC__stream_decoder_new();
1011 if(0 == encoder->private_->verify.decoder) {
1012 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1013 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1016 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) {
1017 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1018 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1021 encoder->private_->verify.error_stats.absolute_sample = 0;
1022 encoder->private_->verify.error_stats.frame_number = 0;
1023 encoder->private_->verify.error_stats.channel = 0;
1024 encoder->private_->verify.error_stats.sample = 0;
1025 encoder->private_->verify.error_stats.expected = 0;
1026 encoder->private_->verify.error_stats.got = 0;
1029 * These must be done before we write any metadata, because that
1030 * calls the write_callback, which uses these values.
1032 encoder->private_->first_seekpoint_to_check = 0;
1033 encoder->private_->samples_written = 0;
1034 encoder->protected_->streaminfo_offset = 0;
1035 encoder->protected_->seektable_offset = 0;
1036 encoder->protected_->audio_offset = 0;
1039 * write the stream header
1041 if(encoder->protected_->verify)
1042 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1043 if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1044 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1045 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1047 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1048 /* the above function sets the state for us in case of an error */
1049 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1053 * write the STREAMINFO metadata block
1055 if(encoder->protected_->verify)
1056 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1057 encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1058 encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1059 encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1060 encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1061 encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1062 encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1063 encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1064 encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1065 encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1066 encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1067 encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1068 memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1069 FLAC__MD5Init(&encoder->private_->md5context);
1070 if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1071 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1072 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1074 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1075 /* the above function sets the state for us in case of an error */
1076 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1080 * Now that the STREAMINFO block is written, we can init this to an
1081 * absurdly-high value...
1083 encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1084 /* ... and clear this to 0 */
1085 encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1088 * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1089 * if not, we will write an empty one (FLAC__add_metadata_block()
1090 * automatically supplies the vendor string).
1092 * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1093 * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
1094 * true it will have already insured that the metadata list is properly
1097 if(!metadata_has_vorbis_comment) {
1098 FLAC__StreamMetadata vorbis_comment;
1099 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1100 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1101 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1102 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1103 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1104 vorbis_comment.data.vorbis_comment.num_comments = 0;
1105 vorbis_comment.data.vorbis_comment.comments = 0;
1106 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1107 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1108 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1110 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1111 /* the above function sets the state for us in case of an error */
1112 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1117 * write the user's metadata blocks
1119 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1120 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1121 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1122 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1123 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1125 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1126 /* the above function sets the state for us in case of an error */
1127 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1131 /* now that all the metadata is written, we save the stream offset */
1132 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 */
1133 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1134 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1137 if(encoder->protected_->verify)
1138 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1140 return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1143 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1144 FLAC__StreamEncoder *encoder,
1145 FLAC__StreamEncoderWriteCallback write_callback,
1146 FLAC__StreamEncoderSeekCallback seek_callback,
1147 FLAC__StreamEncoderTellCallback tell_callback,
1148 FLAC__StreamEncoderMetadataCallback metadata_callback,
1152 return init_stream_internal_(
1154 /*read_callback=*/0,
1164 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1165 FLAC__StreamEncoder *encoder,
1166 FLAC__StreamEncoderReadCallback read_callback,
1167 FLAC__StreamEncoderWriteCallback write_callback,
1168 FLAC__StreamEncoderSeekCallback seek_callback,
1169 FLAC__StreamEncoderTellCallback tell_callback,
1170 FLAC__StreamEncoderMetadataCallback metadata_callback,
1174 return init_stream_internal_(
1186 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1187 FLAC__StreamEncoder *encoder,
1189 FLAC__StreamEncoderProgressCallback progress_callback,
1194 FLAC__StreamEncoderInitStatus init_status;
1196 FLAC__ASSERT(0 != encoder);
1197 FLAC__ASSERT(0 != file);
1199 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1200 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1202 /* double protection */
1204 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1205 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1209 * To make sure that our file does not go unclosed after an error, we
1210 * must assign the FILE pointer before any further error can occur in
1214 file = get_binary_stdout_(); /* just to be safe */
1216 encoder->private_->file = file;
1218 encoder->private_->progress_callback = progress_callback;
1219 encoder->private_->bytes_written = 0;
1220 encoder->private_->samples_written = 0;
1221 encoder->private_->frames_written = 0;
1223 init_status = init_stream_internal_(
1225 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1226 file_write_callback_,
1227 encoder->private_->file == stdout? 0 : file_seek_callback_,
1228 encoder->private_->file == stdout? 0 : file_tell_callback_,
1229 /*metadata_callback=*/0,
1233 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1234 /* the above function sets the state for us in case of an error */
1239 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1241 FLAC__ASSERT(blocksize != 0);
1242 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1248 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1249 FLAC__StreamEncoder *encoder,
1251 FLAC__StreamEncoderProgressCallback progress_callback,
1255 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1258 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1259 FLAC__StreamEncoder *encoder,
1261 FLAC__StreamEncoderProgressCallback progress_callback,
1265 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1268 static FLAC__StreamEncoderInitStatus init_file_internal_(
1269 FLAC__StreamEncoder *encoder,
1270 const char *filename,
1271 FLAC__StreamEncoderProgressCallback progress_callback,
1278 FLAC__ASSERT(0 != encoder);
1281 * To make sure that our file does not go unclosed after an error, we
1282 * have to do the same entrance checks here that are later performed
1283 * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1285 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1286 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1288 file = filename? fopen(filename, "w+b") : stdout;
1291 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1292 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1295 return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1298 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1299 FLAC__StreamEncoder *encoder,
1300 const char *filename,
1301 FLAC__StreamEncoderProgressCallback progress_callback,
1305 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1308 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1309 FLAC__StreamEncoder *encoder,
1310 const char *filename,
1311 FLAC__StreamEncoderProgressCallback progress_callback,
1315 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1318 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1320 FLAC__bool error = false;
1322 FLAC__ASSERT(0 != encoder);
1323 FLAC__ASSERT(0 != encoder->private_);
1324 FLAC__ASSERT(0 != encoder->protected_);
1326 if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1329 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1330 if(encoder->private_->current_sample_number != 0) {
1331 const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1332 encoder->protected_->blocksize = encoder->private_->current_sample_number;
1333 if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1338 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1340 if(!encoder->private_->is_being_deleted) {
1341 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1342 if(encoder->private_->seek_callback) {
1344 if(encoder->private_->is_ogg)
1345 update_ogg_metadata_(encoder);
1348 update_metadata_(encoder);
1350 /* check if an error occurred while updating metadata */
1351 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1354 if(encoder->private_->metadata_callback)
1355 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1358 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1360 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1365 if(0 != encoder->private_->file) {
1366 if(encoder->private_->file != stdout)
1367 fclose(encoder->private_->file);
1368 encoder->private_->file = 0;
1372 if(encoder->private_->is_ogg)
1373 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1377 set_defaults_(encoder);
1380 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1385 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1387 FLAC__ASSERT(0 != encoder);
1388 FLAC__ASSERT(0 != encoder->private_);
1389 FLAC__ASSERT(0 != encoder->protected_);
1390 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1393 /* can't check encoder->private_->is_ogg since that's not set until init time */
1394 FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1402 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1404 FLAC__ASSERT(0 != encoder);
1405 FLAC__ASSERT(0 != encoder->private_);
1406 FLAC__ASSERT(0 != encoder->protected_);
1407 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1409 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1410 encoder->protected_->verify = value;
1415 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1417 FLAC__ASSERT(0 != encoder);
1418 FLAC__ASSERT(0 != encoder->private_);
1419 FLAC__ASSERT(0 != encoder->protected_);
1420 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1422 encoder->protected_->streamable_subset = value;
1426 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1428 FLAC__ASSERT(0 != encoder);
1429 FLAC__ASSERT(0 != encoder->private_);
1430 FLAC__ASSERT(0 != encoder->protected_);
1431 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1433 encoder->protected_->channels = value;
1437 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1439 FLAC__ASSERT(0 != encoder);
1440 FLAC__ASSERT(0 != encoder->private_);
1441 FLAC__ASSERT(0 != encoder->protected_);
1442 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1444 encoder->protected_->bits_per_sample = value;
1448 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1450 FLAC__ASSERT(0 != encoder);
1451 FLAC__ASSERT(0 != encoder->private_);
1452 FLAC__ASSERT(0 != encoder->protected_);
1453 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1455 encoder->protected_->sample_rate = value;
1459 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1461 FLAC__bool ok = true;
1462 FLAC__ASSERT(0 != encoder);
1463 FLAC__ASSERT(0 != encoder->private_);
1464 FLAC__ASSERT(0 != encoder->protected_);
1465 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1467 if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1468 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1469 ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
1470 ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
1473 ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
1474 /* but it's too hard to specify the string in a locale-specific way */
1476 encoder->protected_->num_apodizations = 1;
1477 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1478 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1480 ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
1481 ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
1482 ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1483 ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
1484 ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
1485 ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1486 ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1487 ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
1491 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1493 FLAC__ASSERT(0 != encoder);
1494 FLAC__ASSERT(0 != encoder->private_);
1495 FLAC__ASSERT(0 != encoder->protected_);
1496 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1498 encoder->protected_->blocksize = value;
1502 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1504 FLAC__ASSERT(0 != encoder);
1505 FLAC__ASSERT(0 != encoder->private_);
1506 FLAC__ASSERT(0 != encoder->protected_);
1507 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1509 encoder->protected_->do_mid_side_stereo = value;
1513 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1515 FLAC__ASSERT(0 != encoder);
1516 FLAC__ASSERT(0 != encoder->private_);
1517 FLAC__ASSERT(0 != encoder->protected_);
1518 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1520 encoder->protected_->loose_mid_side_stereo = value;
1524 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1526 FLAC__ASSERT(0 != encoder);
1527 FLAC__ASSERT(0 != encoder->private_);
1528 FLAC__ASSERT(0 != encoder->protected_);
1529 FLAC__ASSERT(0 != specification);
1530 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1532 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1533 (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1535 encoder->protected_->num_apodizations = 0;
1537 const char *s = strchr(specification, ';');
1538 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1539 if (n==8 && 0 == strncmp("bartlett" , specification, n))
1540 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1541 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1542 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1543 else if(n==8 && 0 == strncmp("blackman" , specification, n))
1544 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1545 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1546 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1547 else if(n==6 && 0 == strncmp("connes" , specification, n))
1548 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1549 else if(n==7 && 0 == strncmp("flattop" , specification, n))
1550 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1551 else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
1552 FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1553 if (stddev > 0.0 && stddev <= 0.5) {
1554 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1555 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1558 else if(n==7 && 0 == strncmp("hamming" , specification, n))
1559 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1560 else if(n==4 && 0 == strncmp("hann" , specification, n))
1561 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1562 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1563 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1564 else if(n==7 && 0 == strncmp("nuttall" , specification, n))
1565 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1566 else if(n==9 && 0 == strncmp("rectangle" , specification, n))
1567 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1568 else if(n==8 && 0 == strncmp("triangle" , specification, n))
1569 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1570 else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
1571 FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1572 if (p >= 0.0 && p <= 1.0) {
1573 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1574 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1577 else if(n==5 && 0 == strncmp("welch" , specification, n))
1578 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1579 if (encoder->protected_->num_apodizations == 32)
1582 specification = s+1;
1586 if(encoder->protected_->num_apodizations == 0) {
1587 encoder->protected_->num_apodizations = 1;
1588 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1589 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1595 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1597 FLAC__ASSERT(0 != encoder);
1598 FLAC__ASSERT(0 != encoder->private_);
1599 FLAC__ASSERT(0 != encoder->protected_);
1600 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1602 encoder->protected_->max_lpc_order = value;
1606 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1608 FLAC__ASSERT(0 != encoder);
1609 FLAC__ASSERT(0 != encoder->private_);
1610 FLAC__ASSERT(0 != encoder->protected_);
1611 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1613 encoder->protected_->qlp_coeff_precision = value;
1617 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1619 FLAC__ASSERT(0 != encoder);
1620 FLAC__ASSERT(0 != encoder->private_);
1621 FLAC__ASSERT(0 != encoder->protected_);
1622 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1624 encoder->protected_->do_qlp_coeff_prec_search = value;
1628 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1630 FLAC__ASSERT(0 != encoder);
1631 FLAC__ASSERT(0 != encoder->private_);
1632 FLAC__ASSERT(0 != encoder->protected_);
1633 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1636 /*@@@ deprecated: */
1637 encoder->protected_->do_escape_coding = value;
1644 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1646 FLAC__ASSERT(0 != encoder);
1647 FLAC__ASSERT(0 != encoder->private_);
1648 FLAC__ASSERT(0 != encoder->protected_);
1649 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1651 encoder->protected_->do_exhaustive_model_search = value;
1655 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1657 FLAC__ASSERT(0 != encoder);
1658 FLAC__ASSERT(0 != encoder->private_);
1659 FLAC__ASSERT(0 != encoder->protected_);
1660 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1662 encoder->protected_->min_residual_partition_order = value;
1666 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1668 FLAC__ASSERT(0 != encoder);
1669 FLAC__ASSERT(0 != encoder->private_);
1670 FLAC__ASSERT(0 != encoder->protected_);
1671 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1673 encoder->protected_->max_residual_partition_order = value;
1677 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1679 FLAC__ASSERT(0 != encoder);
1680 FLAC__ASSERT(0 != encoder->private_);
1681 FLAC__ASSERT(0 != encoder->protected_);
1682 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1685 /*@@@ deprecated: */
1686 encoder->protected_->rice_parameter_search_dist = value;
1693 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1695 FLAC__ASSERT(0 != encoder);
1696 FLAC__ASSERT(0 != encoder->private_);
1697 FLAC__ASSERT(0 != encoder->protected_);
1698 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1700 encoder->protected_->total_samples_estimate = value;
1704 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1706 FLAC__ASSERT(0 != encoder);
1707 FLAC__ASSERT(0 != encoder->private_);
1708 FLAC__ASSERT(0 != encoder->protected_);
1709 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1711 encoder->protected_->metadata = metadata;
1712 encoder->protected_->num_metadata_blocks = num_blocks;
1714 if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1721 * These three functions are not static, but not publically exposed in
1722 * include/FLAC/ either. They are used by the test suite.
1724 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1726 FLAC__ASSERT(0 != encoder);
1727 FLAC__ASSERT(0 != encoder->private_);
1728 FLAC__ASSERT(0 != encoder->protected_);
1729 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1731 encoder->private_->disable_constant_subframes = value;
1735 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1737 FLAC__ASSERT(0 != encoder);
1738 FLAC__ASSERT(0 != encoder->private_);
1739 FLAC__ASSERT(0 != encoder->protected_);
1740 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1742 encoder->private_->disable_fixed_subframes = value;
1746 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1748 FLAC__ASSERT(0 != encoder);
1749 FLAC__ASSERT(0 != encoder->private_);
1750 FLAC__ASSERT(0 != encoder->protected_);
1751 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1753 encoder->private_->disable_verbatim_subframes = value;
1757 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1759 FLAC__ASSERT(0 != encoder);
1760 FLAC__ASSERT(0 != encoder->private_);
1761 FLAC__ASSERT(0 != encoder->protected_);
1762 return encoder->protected_->state;
1765 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1767 FLAC__ASSERT(0 != encoder);
1768 FLAC__ASSERT(0 != encoder->private_);
1769 FLAC__ASSERT(0 != encoder->protected_);
1770 if(encoder->protected_->verify)
1771 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1773 return FLAC__STREAM_DECODER_UNINITIALIZED;
1776 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1778 FLAC__ASSERT(0 != encoder);
1779 FLAC__ASSERT(0 != encoder->private_);
1780 FLAC__ASSERT(0 != encoder->protected_);
1781 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1782 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1784 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1787 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)
1789 FLAC__ASSERT(0 != encoder);
1790 FLAC__ASSERT(0 != encoder->private_);
1791 FLAC__ASSERT(0 != encoder->protected_);
1792 if(0 != absolute_sample)
1793 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1794 if(0 != frame_number)
1795 *frame_number = encoder->private_->verify.error_stats.frame_number;
1797 *channel = encoder->private_->verify.error_stats.channel;
1799 *sample = encoder->private_->verify.error_stats.sample;
1801 *expected = encoder->private_->verify.error_stats.expected;
1803 *got = encoder->private_->verify.error_stats.got;
1806 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1808 FLAC__ASSERT(0 != encoder);
1809 FLAC__ASSERT(0 != encoder->private_);
1810 FLAC__ASSERT(0 != encoder->protected_);
1811 return encoder->protected_->verify;
1814 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1816 FLAC__ASSERT(0 != encoder);
1817 FLAC__ASSERT(0 != encoder->private_);
1818 FLAC__ASSERT(0 != encoder->protected_);
1819 return encoder->protected_->streamable_subset;
1822 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1824 FLAC__ASSERT(0 != encoder);
1825 FLAC__ASSERT(0 != encoder->private_);
1826 FLAC__ASSERT(0 != encoder->protected_);
1827 return encoder->protected_->channels;
1830 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1832 FLAC__ASSERT(0 != encoder);
1833 FLAC__ASSERT(0 != encoder->private_);
1834 FLAC__ASSERT(0 != encoder->protected_);
1835 return encoder->protected_->bits_per_sample;
1838 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1840 FLAC__ASSERT(0 != encoder);
1841 FLAC__ASSERT(0 != encoder->private_);
1842 FLAC__ASSERT(0 != encoder->protected_);
1843 return encoder->protected_->sample_rate;
1846 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1848 FLAC__ASSERT(0 != encoder);
1849 FLAC__ASSERT(0 != encoder->private_);
1850 FLAC__ASSERT(0 != encoder->protected_);
1851 return encoder->protected_->blocksize;
1854 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1856 FLAC__ASSERT(0 != encoder);
1857 FLAC__ASSERT(0 != encoder->private_);
1858 FLAC__ASSERT(0 != encoder->protected_);
1859 return encoder->protected_->do_mid_side_stereo;
1862 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1864 FLAC__ASSERT(0 != encoder);
1865 FLAC__ASSERT(0 != encoder->private_);
1866 FLAC__ASSERT(0 != encoder->protected_);
1867 return encoder->protected_->loose_mid_side_stereo;
1870 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1872 FLAC__ASSERT(0 != encoder);
1873 FLAC__ASSERT(0 != encoder->private_);
1874 FLAC__ASSERT(0 != encoder->protected_);
1875 return encoder->protected_->max_lpc_order;
1878 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1880 FLAC__ASSERT(0 != encoder);
1881 FLAC__ASSERT(0 != encoder->private_);
1882 FLAC__ASSERT(0 != encoder->protected_);
1883 return encoder->protected_->qlp_coeff_precision;
1886 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1888 FLAC__ASSERT(0 != encoder);
1889 FLAC__ASSERT(0 != encoder->private_);
1890 FLAC__ASSERT(0 != encoder->protected_);
1891 return encoder->protected_->do_qlp_coeff_prec_search;
1894 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1896 FLAC__ASSERT(0 != encoder);
1897 FLAC__ASSERT(0 != encoder->private_);
1898 FLAC__ASSERT(0 != encoder->protected_);
1899 return encoder->protected_->do_escape_coding;
1902 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1904 FLAC__ASSERT(0 != encoder);
1905 FLAC__ASSERT(0 != encoder->private_);
1906 FLAC__ASSERT(0 != encoder->protected_);
1907 return encoder->protected_->do_exhaustive_model_search;
1910 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1912 FLAC__ASSERT(0 != encoder);
1913 FLAC__ASSERT(0 != encoder->private_);
1914 FLAC__ASSERT(0 != encoder->protected_);
1915 return encoder->protected_->min_residual_partition_order;
1918 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1920 FLAC__ASSERT(0 != encoder);
1921 FLAC__ASSERT(0 != encoder->private_);
1922 FLAC__ASSERT(0 != encoder->protected_);
1923 return encoder->protected_->max_residual_partition_order;
1926 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1928 FLAC__ASSERT(0 != encoder);
1929 FLAC__ASSERT(0 != encoder->private_);
1930 FLAC__ASSERT(0 != encoder->protected_);
1931 return encoder->protected_->rice_parameter_search_dist;
1934 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1936 FLAC__ASSERT(0 != encoder);
1937 FLAC__ASSERT(0 != encoder->private_);
1938 FLAC__ASSERT(0 != encoder->protected_);
1939 return encoder->protected_->total_samples_estimate;
1942 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1944 unsigned i, j, channel;
1945 FLAC__int32 x, mid, side;
1946 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1948 FLAC__ASSERT(0 != encoder);
1949 FLAC__ASSERT(0 != encoder->private_);
1950 FLAC__ASSERT(0 != encoder->protected_);
1951 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1955 * we have several flavors of the same basic loop, optimized for
1956 * different conditions:
1958 if(encoder->protected_->max_lpc_order > 0) {
1959 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1961 * stereo coding: unroll channel loop
1962 * with LPC: calculate floating point version of signal
1965 if(encoder->protected_->verify)
1966 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
1968 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
1969 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1970 x = mid = side = buffer[0][j];
1971 encoder->private_->integer_signal[0][i] = x;
1972 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1973 encoder->private_->real_signal[0][i] = (FLAC__real)x;
1976 encoder->private_->integer_signal[1][i] = x;
1977 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1978 encoder->private_->real_signal[1][i] = (FLAC__real)x;
1982 mid >>= 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
1983 encoder->private_->integer_signal_mid_side[1][i] = side;
1984 encoder->private_->integer_signal_mid_side[0][i] = mid;
1985 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1986 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
1987 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
1989 encoder->private_->current_sample_number++;
1991 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
1993 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
1995 /* move unprocessed overread samples to beginnings of arrays */
1996 FLAC__ASSERT(i == blocksize+OVERREAD_);
1997 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
1999 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2000 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2001 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2002 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2003 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2004 encoder->private_->real_signal[0][0] = encoder->private_->real_signal[0][i];
2005 encoder->private_->real_signal[1][0] = encoder->private_->real_signal[1][i];
2006 encoder->private_->real_signal_mid_side[0][0] = encoder->private_->real_signal_mid_side[0][i];
2007 encoder->private_->real_signal_mid_side[1][0] = encoder->private_->real_signal_mid_side[1][i];
2009 encoder->private_->current_sample_number = 1;
2011 } while(j < samples);
2015 * independent channel coding: buffer each channel in inner loop
2016 * with LPC: calculate floating point version of signal
2019 if(encoder->protected_->verify)
2020 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2022 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2023 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2024 for(channel = 0; channel < channels; channel++) {
2025 x = buffer[channel][j];
2026 encoder->private_->integer_signal[channel][i] = x;
2027 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2028 encoder->private_->real_signal[channel][i] = (FLAC__real)x;
2031 encoder->private_->current_sample_number++;
2033 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2035 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2037 /* move unprocessed overread samples to beginnings of arrays */
2038 FLAC__ASSERT(i == blocksize+OVERREAD_);
2039 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2041 for(channel = 0; channel < channels; channel++) {
2042 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2043 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2044 encoder->private_->real_signal[channel][0] = encoder->private_->real_signal[channel][i];
2047 encoder->private_->current_sample_number = 1;
2049 } while(j < samples);
2053 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2055 * stereo coding: unroll channel loop
2056 * without LPC: no need to calculate floating point version of signal
2059 if(encoder->protected_->verify)
2060 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2062 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2063 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2064 encoder->private_->integer_signal[0][i] = mid = side = buffer[0][j];
2066 encoder->private_->integer_signal[1][i] = x;
2069 mid >>= 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
2070 encoder->private_->integer_signal_mid_side[1][i] = side;
2071 encoder->private_->integer_signal_mid_side[0][i] = mid;
2072 encoder->private_->current_sample_number++;
2074 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2076 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2078 /* move unprocessed overread samples to beginnings of arrays */
2079 FLAC__ASSERT(i == blocksize+OVERREAD_);
2080 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2082 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2083 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2084 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2085 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2086 encoder->private_->current_sample_number = 1;
2088 } while(j < samples);
2092 * independent channel coding: buffer each channel in inner loop
2093 * without LPC: no need to calculate floating point version of signal
2096 if(encoder->protected_->verify)
2097 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2099 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2100 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2101 for(channel = 0; channel < channels; channel++)
2102 encoder->private_->integer_signal[channel][i] = buffer[channel][j];
2103 encoder->private_->current_sample_number++;
2105 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2107 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2109 /* move unprocessed overread samples to beginnings of arrays */
2110 FLAC__ASSERT(i == blocksize+OVERREAD_);
2111 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2113 for(channel = 0; channel < channels; channel++)
2114 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2115 encoder->private_->current_sample_number = 1;
2117 } while(j < samples);
2124 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2126 unsigned i, j, k, channel;
2127 FLAC__int32 x, mid, side;
2128 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2130 FLAC__ASSERT(0 != encoder);
2131 FLAC__ASSERT(0 != encoder->private_);
2132 FLAC__ASSERT(0 != encoder->protected_);
2133 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2137 * we have several flavors of the same basic loop, optimized for
2138 * different conditions:
2140 if(encoder->protected_->max_lpc_order > 0) {
2141 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2143 * stereo coding: unroll channel loop
2144 * with LPC: calculate floating point version of signal
2147 if(encoder->protected_->verify)
2148 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2150 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2151 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2152 x = mid = side = buffer[k++];
2153 encoder->private_->integer_signal[0][i] = x;
2154 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2155 encoder->private_->real_signal[0][i] = (FLAC__real)x;
2158 encoder->private_->integer_signal[1][i] = x;
2159 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2160 encoder->private_->real_signal[1][i] = (FLAC__real)x;
2164 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2165 encoder->private_->integer_signal_mid_side[1][i] = side;
2166 encoder->private_->integer_signal_mid_side[0][i] = mid;
2167 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2168 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
2169 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
2171 encoder->private_->current_sample_number++;
2173 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2175 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2177 /* move unprocessed overread samples to beginnings of arrays */
2178 FLAC__ASSERT(i == blocksize+OVERREAD_);
2179 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2181 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2182 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2183 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2184 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2185 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2186 encoder->private_->real_signal[0][0] = encoder->private_->real_signal[0][i];
2187 encoder->private_->real_signal[1][0] = encoder->private_->real_signal[1][i];
2188 encoder->private_->real_signal_mid_side[0][0] = encoder->private_->real_signal_mid_side[0][i];
2189 encoder->private_->real_signal_mid_side[1][0] = encoder->private_->real_signal_mid_side[1][i];
2191 encoder->private_->current_sample_number = 1;
2193 } while(j < samples);
2197 * independent channel coding: buffer each channel in inner loop
2198 * with LPC: calculate floating point version of signal
2201 if(encoder->protected_->verify)
2202 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2204 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2205 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2206 for(channel = 0; channel < channels; channel++) {
2208 encoder->private_->integer_signal[channel][i] = x;
2209 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2210 encoder->private_->real_signal[channel][i] = (FLAC__real)x;
2213 encoder->private_->current_sample_number++;
2215 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2217 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2219 /* move unprocessed overread samples to beginnings of arrays */
2220 FLAC__ASSERT(i == blocksize+OVERREAD_);
2221 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2223 for(channel = 0; channel < channels; channel++) {
2224 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2225 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2226 encoder->private_->real_signal[channel][0] = encoder->private_->real_signal[channel][i];
2229 encoder->private_->current_sample_number = 1;
2231 } while(j < samples);
2235 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2237 * stereo coding: unroll channel loop
2238 * without LPC: no need to calculate floating point version of signal
2241 if(encoder->protected_->verify)
2242 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2244 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2245 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2246 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2248 encoder->private_->integer_signal[1][i] = x;
2251 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2252 encoder->private_->integer_signal_mid_side[1][i] = side;
2253 encoder->private_->integer_signal_mid_side[0][i] = mid;
2254 encoder->private_->current_sample_number++;
2256 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2258 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2260 /* move unprocessed overread samples to beginnings of arrays */
2261 FLAC__ASSERT(i == blocksize+OVERREAD_);
2262 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2264 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
2265 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
2266 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
2267 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
2268 encoder->private_->current_sample_number = 1;
2270 } while(j < samples);
2274 * independent channel coding: buffer each channel in inner loop
2275 * without LPC: no need to calculate floating point version of signal
2278 if(encoder->protected_->verify)
2279 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
2281 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2282 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2283 for(channel = 0; channel < channels; channel++)
2284 encoder->private_->integer_signal[channel][i] = buffer[k++];
2285 encoder->private_->current_sample_number++;
2287 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2289 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2291 /* move unprocessed overread samples to beginnings of arrays */
2292 FLAC__ASSERT(i == blocksize+OVERREAD_);
2293 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2295 for(channel = 0; channel < channels; channel++)
2296 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
2297 encoder->private_->current_sample_number = 1;
2299 } while(j < samples);
2306 /***********************************************************************
2308 * Private class methods
2310 ***********************************************************************/
2312 void set_defaults_(FLAC__StreamEncoder *encoder)
2314 FLAC__ASSERT(0 != encoder);
2316 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2317 encoder->protected_->verify = true;
2319 encoder->protected_->verify = false;
2321 encoder->protected_->streamable_subset = true;
2322 encoder->protected_->do_mid_side_stereo = false;
2323 encoder->protected_->loose_mid_side_stereo = false;
2324 encoder->protected_->channels = 2;
2325 encoder->protected_->bits_per_sample = 16;
2326 encoder->protected_->sample_rate = 44100;
2327 encoder->protected_->blocksize = 0;
2328 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2329 encoder->protected_->num_apodizations = 1;
2330 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2331 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2333 encoder->protected_->max_lpc_order = 0;
2334 encoder->protected_->qlp_coeff_precision = 0;
2335 encoder->protected_->do_qlp_coeff_prec_search = false;
2336 encoder->protected_->do_exhaustive_model_search = false;
2337 encoder->protected_->do_escape_coding = false;
2338 encoder->protected_->min_residual_partition_order = 0;
2339 encoder->protected_->max_residual_partition_order = 0;
2340 encoder->protected_->rice_parameter_search_dist = 0;
2341 encoder->protected_->total_samples_estimate = 0;
2342 encoder->protected_->metadata = 0;
2343 encoder->protected_->num_metadata_blocks = 0;
2345 encoder->private_->seek_table = 0;
2346 encoder->private_->disable_constant_subframes = false;
2347 encoder->private_->disable_fixed_subframes = false;
2348 encoder->private_->disable_verbatim_subframes = false;
2350 encoder->private_->is_ogg = false;
2352 encoder->private_->read_callback = 0;
2353 encoder->private_->write_callback = 0;
2354 encoder->private_->seek_callback = 0;
2355 encoder->private_->tell_callback = 0;
2356 encoder->private_->metadata_callback = 0;
2357 encoder->private_->progress_callback = 0;
2358 encoder->private_->client_data = 0;
2361 FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2365 void free_(FLAC__StreamEncoder *encoder)
2367 unsigned i, channel;
2369 FLAC__ASSERT(0 != encoder);
2370 for(i = 0; i < encoder->protected_->channels; i++) {
2371 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2372 free(encoder->private_->integer_signal_unaligned[i]);
2373 encoder->private_->integer_signal_unaligned[i] = 0;
2375 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2376 if(0 != encoder->private_->real_signal_unaligned[i]) {
2377 free(encoder->private_->real_signal_unaligned[i]);
2378 encoder->private_->real_signal_unaligned[i] = 0;
2382 for(i = 0; i < 2; i++) {
2383 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2384 free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2385 encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2387 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2388 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2389 free(encoder->private_->real_signal_mid_side_unaligned[i]);
2390 encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2394 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2395 for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2396 if(0 != encoder->private_->window_unaligned[i]) {
2397 free(encoder->private_->window_unaligned[i]);
2398 encoder->private_->window_unaligned[i] = 0;
2401 if(0 != encoder->private_->windowed_signal_unaligned) {
2402 free(encoder->private_->windowed_signal_unaligned);
2403 encoder->private_->windowed_signal_unaligned = 0;
2406 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2407 for(i = 0; i < 2; i++) {
2408 if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2409 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2410 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2414 for(channel = 0; channel < 2; channel++) {
2415 for(i = 0; i < 2; i++) {
2416 if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2417 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2418 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2422 if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2423 free(encoder->private_->abs_residual_partition_sums_unaligned);
2424 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2426 if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2427 free(encoder->private_->raw_bits_per_partition_unaligned);
2428 encoder->private_->raw_bits_per_partition_unaligned = 0;
2430 if(encoder->protected_->verify) {
2431 for(i = 0; i < encoder->protected_->channels; i++) {
2432 if(0 != encoder->private_->verify.input_fifo.data[i]) {
2433 free(encoder->private_->verify.input_fifo.data[i]);
2434 encoder->private_->verify.input_fifo.data[i] = 0;
2438 FLAC__bitwriter_free(encoder->private_->frame);
2441 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2444 unsigned i, channel;
2446 FLAC__ASSERT(new_blocksize > 0);
2447 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2448 FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2450 /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2451 if(new_blocksize <= encoder->private_->input_capacity)
2456 /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
2457 * requires that the input arrays (in our case the integer signals)
2458 * have a buffer of up to 3 zeroes in front (at negative indices) for
2459 * alignment purposes; we use 4 in front to keep the data well-aligned.
2462 for(i = 0; ok && i < encoder->protected_->channels; i++) {
2463 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2464 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2465 encoder->private_->integer_signal[i] += 4;
2466 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2467 if(encoder->protected_->max_lpc_order > 0)
2468 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2471 for(i = 0; ok && i < 2; i++) {
2472 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]);
2473 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2474 encoder->private_->integer_signal_mid_side[i] += 4;
2475 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2476 if(encoder->protected_->max_lpc_order > 0)
2477 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]);
2480 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2481 if(ok && encoder->protected_->max_lpc_order > 0) {
2482 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2483 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2484 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2487 for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2488 for(i = 0; ok && i < 2; i++) {
2489 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2492 for(channel = 0; ok && channel < 2; channel++) {
2493 for(i = 0; ok && i < 2; i++) {
2494 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]);
2497 /* @@@@@@@@@ blocksize*2 is too pessimistic, but to fix, we need smarter logic because a smaller new_blocksize can actually increase the # of partitions */
2498 ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2499 if(encoder->protected_->do_escape_coding)
2500 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2502 /* now adjust the windows if the blocksize has changed */
2503 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2504 if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2505 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2506 switch(encoder->protected_->apodizations[i].type) {
2507 case FLAC__APODIZATION_BARTLETT:
2508 FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2510 case FLAC__APODIZATION_BARTLETT_HANN:
2511 FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2513 case FLAC__APODIZATION_BLACKMAN:
2514 FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2516 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2517 FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2519 case FLAC__APODIZATION_CONNES:
2520 FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2522 case FLAC__APODIZATION_FLATTOP:
2523 FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2525 case FLAC__APODIZATION_GAUSS:
2526 FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2528 case FLAC__APODIZATION_HAMMING:
2529 FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2531 case FLAC__APODIZATION_HANN:
2532 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2534 case FLAC__APODIZATION_KAISER_BESSEL:
2535 FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2537 case FLAC__APODIZATION_NUTTALL:
2538 FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2540 case FLAC__APODIZATION_RECTANGLE:
2541 FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2543 case FLAC__APODIZATION_TRIANGLE:
2544 FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2546 case FLAC__APODIZATION_TUKEY:
2547 FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2549 case FLAC__APODIZATION_WELCH:
2550 FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2554 /* double protection */
2555 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2563 encoder->private_->input_capacity = new_blocksize;
2565 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2570 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2572 const FLAC__byte *buffer;
2575 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2577 if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2578 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2582 if(encoder->protected_->verify) {
2583 encoder->private_->verify.output.data = buffer;
2584 encoder->private_->verify.output.bytes = bytes;
2585 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2586 encoder->private_->verify.needs_magic_hack = true;
2589 if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2590 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2591 FLAC__bitwriter_clear(encoder->private_->frame);
2592 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2593 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2599 if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2600 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2601 FLAC__bitwriter_clear(encoder->private_->frame);
2602 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2606 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2607 FLAC__bitwriter_clear(encoder->private_->frame);
2610 encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2611 encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2617 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2619 FLAC__StreamEncoderWriteStatus status;
2620 FLAC__uint64 output_position = 0;
2622 /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2623 if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2624 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2625 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2629 * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2632 FLAC__MetadataType type = (buffer[0] & 0x7f);
2633 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2634 encoder->protected_->streaminfo_offset = output_position;
2635 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2636 encoder->protected_->seektable_offset = output_position;
2640 * Mark the current seek point if hit (if audio_offset == 0 that
2641 * means we're still writing metadata and haven't hit the first
2644 if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2645 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2646 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2647 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2648 FLAC__uint64 test_sample;
2650 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2651 test_sample = encoder->private_->seek_table->points[i].sample_number;
2652 if(test_sample > frame_last_sample) {
2655 else if(test_sample >= frame_first_sample) {
2656 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2657 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2658 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2659 encoder->private_->first_seekpoint_to_check++;
2660 /* DO NOT: "break;" and here's why:
2661 * The seektable template may contain more than one target
2662 * sample for any given frame; we will keep looping, generating
2663 * duplicate seekpoints for them, and we'll clean it up later,
2664 * just before writing the seektable back to the metadata.
2668 encoder->private_->first_seekpoint_to_check++;
2674 if(encoder->private_->is_ogg) {
2675 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2676 &encoder->protected_->ogg_encoder_aspect,
2680 encoder->private_->current_frame_number,
2682 (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2684 encoder->private_->client_data
2689 status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2691 if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2692 encoder->private_->bytes_written += bytes;
2693 encoder->private_->samples_written += samples;
2694 /* we keep a high watermark on the number of frames written because
2695 * when the encoder goes back to write metadata, 'current_frame'
2696 * will drop back to 0.
2698 encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2701 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2706 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2707 void update_metadata_(const FLAC__StreamEncoder *encoder)
2709 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2710 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2711 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2712 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2713 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2714 const unsigned bps = metadata->data.stream_info.bits_per_sample;
2715 FLAC__StreamEncoderSeekStatus seek_status;
2717 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2719 /* All this is based on intimate knowledge of the stream header
2720 * layout, but a change to the header format that would break this
2721 * would also break all streams encoded in the previous format.
2725 * Write MD5 signature
2728 const unsigned md5_offset =
2729 FLAC__STREAM_METADATA_HEADER_LENGTH +
2731 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2732 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2733 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2734 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2735 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2736 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2737 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2738 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2741 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2742 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2743 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2746 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2747 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2753 * Write total samples
2756 const unsigned total_samples_byte_offset =
2757 FLAC__STREAM_METADATA_HEADER_LENGTH +
2759 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2760 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2761 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2762 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2763 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2764 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2765 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2769 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2770 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2771 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2772 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2773 b[4] = (FLAC__byte)(samples & 0xFF);
2774 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) {
2775 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2776 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2779 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2780 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2786 * Write min/max framesize
2789 const unsigned min_framesize_offset =
2790 FLAC__STREAM_METADATA_HEADER_LENGTH +
2792 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2793 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2796 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2797 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2798 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2799 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2800 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2801 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2802 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) {
2803 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2804 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2807 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2808 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2816 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2819 FLAC__format_seektable_sort(encoder->private_->seek_table);
2821 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2823 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) {
2824 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2825 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2829 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2832 xx = encoder->private_->seek_table->points[i].sample_number;
2833 b[7] = (FLAC__byte)xx; xx >>= 8;
2834 b[6] = (FLAC__byte)xx; xx >>= 8;
2835 b[5] = (FLAC__byte)xx; xx >>= 8;
2836 b[4] = (FLAC__byte)xx; xx >>= 8;
2837 b[3] = (FLAC__byte)xx; xx >>= 8;
2838 b[2] = (FLAC__byte)xx; xx >>= 8;
2839 b[1] = (FLAC__byte)xx; xx >>= 8;
2840 b[0] = (FLAC__byte)xx; xx >>= 8;
2841 xx = encoder->private_->seek_table->points[i].stream_offset;
2842 b[15] = (FLAC__byte)xx; xx >>= 8;
2843 b[14] = (FLAC__byte)xx; xx >>= 8;
2844 b[13] = (FLAC__byte)xx; xx >>= 8;
2845 b[12] = (FLAC__byte)xx; xx >>= 8;
2846 b[11] = (FLAC__byte)xx; xx >>= 8;
2847 b[10] = (FLAC__byte)xx; xx >>= 8;
2848 b[9] = (FLAC__byte)xx; xx >>= 8;
2849 b[8] = (FLAC__byte)xx; xx >>= 8;
2850 x = encoder->private_->seek_table->points[i].frame_samples;
2851 b[17] = (FLAC__byte)x; x >>= 8;
2852 b[16] = (FLAC__byte)x; x >>= 8;
2853 if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2854 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2862 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2863 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2865 /* the # of bytes in the 1st packet that precede the STREAMINFO */
2866 static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2867 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2868 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2869 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2870 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2871 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2872 FLAC__STREAM_SYNC_LENGTH
2874 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2875 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2876 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2877 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2878 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2881 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2882 FLAC__ASSERT(0 != encoder->private_->seek_callback);
2884 /* Pre-check that client supports seeking, since we don't want the
2885 * ogg_helper code to ever have to deal with this condition.
2887 if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2890 /* All this is based on intimate knowledge of the stream header
2891 * layout, but a change to the header format that would break this
2892 * would also break all streams encoded in the previous format.
2896 ** Write STREAMINFO stats
2898 simple_ogg_page__init(&page);
2899 if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2900 simple_ogg_page__clear(&page);
2901 return; /* state already set */
2905 * Write MD5 signature
2908 const unsigned md5_offset =
2909 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2910 FLAC__STREAM_METADATA_HEADER_LENGTH +
2912 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2913 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2914 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2915 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2916 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2917 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2918 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2919 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2922 if(md5_offset + 16 > (unsigned)page.body_len) {
2923 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2924 simple_ogg_page__clear(&page);
2927 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2931 * Write total samples
2934 const unsigned total_samples_byte_offset =
2935 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2936 FLAC__STREAM_METADATA_HEADER_LENGTH +
2938 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2939 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2940 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2941 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2942 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2943 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2944 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2948 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2949 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2950 simple_ogg_page__clear(&page);
2953 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2954 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2955 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2956 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2957 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2958 b[4] = (FLAC__byte)(samples & 0xFF);
2959 memcpy(page.body + total_samples_byte_offset, b, 5);
2963 * Write min/max framesize
2966 const unsigned min_framesize_offset =
2967 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2968 FLAC__STREAM_METADATA_HEADER_LENGTH +
2970 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2971 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2974 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2975 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2976 simple_ogg_page__clear(&page);
2979 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2980 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2981 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2982 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2983 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2984 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2985 memcpy(page.body + min_framesize_offset, b, 6);
2987 if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2988 simple_ogg_page__clear(&page);
2989 return; /* state already set */
2991 simple_ogg_page__clear(&page);
2996 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
3000 FLAC__format_seektable_sort(encoder->private_->seek_table);
3002 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
3004 simple_ogg_page__init(&page);
3005 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
3006 simple_ogg_page__clear(&page);
3007 return; /* state already set */
3010 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
3011 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
3012 simple_ogg_page__clear(&page);
3016 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
3019 xx = encoder->private_->seek_table->points[i].sample_number;
3020 b[7] = (FLAC__byte)xx; xx >>= 8;
3021 b[6] = (FLAC__byte)xx; xx >>= 8;
3022 b[5] = (FLAC__byte)xx; xx >>= 8;
3023 b[4] = (FLAC__byte)xx; xx >>= 8;
3024 b[3] = (FLAC__byte)xx; xx >>= 8;
3025 b[2] = (FLAC__byte)xx; xx >>= 8;
3026 b[1] = (FLAC__byte)xx; xx >>= 8;
3027 b[0] = (FLAC__byte)xx; xx >>= 8;
3028 xx = encoder->private_->seek_table->points[i].stream_offset;
3029 b[15] = (FLAC__byte)xx; xx >>= 8;
3030 b[14] = (FLAC__byte)xx; xx >>= 8;
3031 b[13] = (FLAC__byte)xx; xx >>= 8;
3032 b[12] = (FLAC__byte)xx; xx >>= 8;
3033 b[11] = (FLAC__byte)xx; xx >>= 8;
3034 b[10] = (FLAC__byte)xx; xx >>= 8;
3035 b[9] = (FLAC__byte)xx; xx >>= 8;
3036 b[8] = (FLAC__byte)xx; xx >>= 8;
3037 x = encoder->private_->seek_table->points[i].frame_samples;
3038 b[17] = (FLAC__byte)x; x >>= 8;
3039 b[16] = (FLAC__byte)x; x >>= 8;
3043 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
3044 simple_ogg_page__clear(&page);
3045 return; /* state already set */
3047 simple_ogg_page__clear(&page);
3052 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
3055 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
3058 * Accumulate raw signal to the MD5 signature
3060 if(!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)) {
3061 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3066 * Process the frame header and subframes into the frame bitbuffer
3068 if(!process_subframes_(encoder, is_fractional_block)) {
3069 /* the above function sets the state for us in case of an error */
3074 * Zero-pad the frame to a byte_boundary
3076 if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
3077 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3082 * CRC-16 the whole thing
3084 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
3086 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
3087 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
3089 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3096 if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
3097 /* the above function sets the state for us in case of an error */
3102 * Get ready for the next frame
3104 encoder->private_->current_sample_number = 0;
3105 encoder->private_->current_frame_number++;
3106 encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
3111 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
3113 FLAC__FrameHeader frame_header;
3114 unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
3115 FLAC__bool do_independent, do_mid_side;
3118 * Calculate the min,max Rice partition orders
3120 if(is_fractional_block) {
3121 max_partition_order = 0;
3124 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
3125 max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
3127 min_partition_order = min(min_partition_order, max_partition_order);
3132 frame_header.blocksize = encoder->protected_->blocksize;
3133 frame_header.sample_rate = encoder->protected_->sample_rate;
3134 frame_header.channels = encoder->protected_->channels;
3135 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
3136 frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
3137 frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
3138 frame_header.number.frame_number = encoder->private_->current_frame_number;
3141 * Figure out what channel assignments to try
3143 if(encoder->protected_->do_mid_side_stereo) {
3144 if(encoder->protected_->loose_mid_side_stereo) {
3145 if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
3146 do_independent = true;
3150 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
3151 do_mid_side = !do_independent;
3155 do_independent = true;
3160 do_independent = true;
3161 do_mid_side = false;
3164 FLAC__ASSERT(do_independent || do_mid_side);
3167 * Check for wasted bits; set effective bps for each subframe
3169 if(do_independent) {
3170 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3171 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
3172 encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
3173 encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
3177 FLAC__ASSERT(encoder->protected_->channels == 2);
3178 for(channel = 0; channel < 2; channel++) {
3179 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
3180 encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
3181 encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
3186 * First do a normal encoding pass of each independent channel
3188 if(do_independent) {
3189 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3193 min_partition_order,
3194 max_partition_order,
3196 encoder->private_->subframe_bps[channel],
3197 encoder->private_->integer_signal[channel],
3198 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3199 encoder->private_->real_signal[channel],
3201 encoder->private_->subframe_workspace_ptr[channel],
3202 encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3203 encoder->private_->residual_workspace[channel],
3204 encoder->private_->best_subframe+channel,
3205 encoder->private_->best_subframe_bits+channel
3213 * Now do mid and side channels if requested
3216 FLAC__ASSERT(encoder->protected_->channels == 2);
3218 for(channel = 0; channel < 2; channel++) {
3222 min_partition_order,
3223 max_partition_order,
3225 encoder->private_->subframe_bps_mid_side[channel],
3226 encoder->private_->integer_signal_mid_side[channel],
3227 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3228 encoder->private_->real_signal_mid_side[channel],
3230 encoder->private_->subframe_workspace_ptr_mid_side[channel],
3231 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3232 encoder->private_->residual_workspace_mid_side[channel],
3233 encoder->private_->best_subframe_mid_side+channel,
3234 encoder->private_->best_subframe_bits_mid_side+channel
3242 * Compose the frame bitbuffer
3245 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3246 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3247 FLAC__ChannelAssignment channel_assignment;
3249 FLAC__ASSERT(encoder->protected_->channels == 2);
3251 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3252 channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3255 unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3259 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3260 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
3261 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
3262 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
3263 FLAC__ASSERT(do_independent && do_mid_side);
3265 /* We have to figure out which channel assignent results in the smallest frame */
3266 bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
3267 bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
3268 bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
3269 bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3271 channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3272 min_bits = bits[channel_assignment];
3273 for(ca = 1; ca <= 3; ca++) {
3274 if(bits[ca] < min_bits) {
3275 min_bits = bits[ca];
3276 channel_assignment = (FLAC__ChannelAssignment)ca;
3281 frame_header.channel_assignment = channel_assignment;
3283 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3284 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3288 switch(channel_assignment) {
3289 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3290 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3291 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3293 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3294 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3295 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3297 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3298 left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3299 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3301 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3302 left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3303 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3309 switch(channel_assignment) {
3310 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3311 left_bps = encoder->private_->subframe_bps [0];
3312 right_bps = encoder->private_->subframe_bps [1];
3314 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3315 left_bps = encoder->private_->subframe_bps [0];
3316 right_bps = encoder->private_->subframe_bps_mid_side[1];
3318 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3319 left_bps = encoder->private_->subframe_bps_mid_side[1];
3320 right_bps = encoder->private_->subframe_bps [1];
3322 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3323 left_bps = encoder->private_->subframe_bps_mid_side[0];
3324 right_bps = encoder->private_->subframe_bps_mid_side[1];
3330 /* note that encoder_add_subframe_ sets the state for us in case of an error */
3331 if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3333 if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3337 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3338 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3342 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3343 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)) {
3344 /* the above function sets the state for us in case of an error */
3350 if(encoder->protected_->loose_mid_side_stereo) {
3351 encoder->private_->loose_mid_side_stereo_frame_count++;
3352 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3353 encoder->private_->loose_mid_side_stereo_frame_count = 0;
3356 encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3361 FLAC__bool process_subframe_(
3362 FLAC__StreamEncoder *encoder,
3363 unsigned min_partition_order,
3364 unsigned max_partition_order,
3365 const FLAC__FrameHeader *frame_header,
3366 unsigned subframe_bps,
3367 const FLAC__int32 integer_signal[],
3368 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3369 const FLAC__real real_signal[],
3371 FLAC__Subframe *subframe[2],
3372 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3373 FLAC__int32 *residual[2],
3374 unsigned *best_subframe,
3378 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3379 FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3381 FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3383 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3384 FLAC__double lpc_residual_bits_per_sample;
3385 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 */
3386 FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3387 unsigned min_lpc_order, max_lpc_order, lpc_order;
3388 unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3390 unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3391 unsigned rice_parameter;
3392 unsigned _candidate_bits, _best_bits;
3393 unsigned _best_subframe;
3395 FLAC__ASSERT(frame_header->blocksize > 0);
3397 /* verbatim subframe is the baseline against which we measure other compressed subframes */
3399 if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3400 _best_bits = UINT_MAX;
3402 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3404 if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3405 unsigned signal_is_constant = false;
3406 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);
3407 /* check for constant subframe */
3409 !encoder->private_->disable_constant_subframes &&
3410 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3411 fixed_residual_bits_per_sample[1] == 0.0
3413 fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3416 /* the above means it's possible all samples are the same value; now double-check it: */
3418 signal_is_constant = true;
3419 for(i = 1; i < frame_header->blocksize; i++) {
3420 if(integer_signal[0] != integer_signal[i]) {
3421 signal_is_constant = false;
3426 if(signal_is_constant) {
3427 _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3428 if(_candidate_bits < _best_bits) {
3429 _best_subframe = !_best_subframe;
3430 _best_bits = _candidate_bits;
3434 if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3436 if(encoder->protected_->do_exhaustive_model_search) {
3437 min_fixed_order = 0;
3438 max_fixed_order = FLAC__MAX_FIXED_ORDER;
3441 min_fixed_order = max_fixed_order = guess_fixed_order;
3443 if(max_fixed_order >= frame_header->blocksize)
3444 max_fixed_order = frame_header->blocksize - 1;
3445 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3446 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3447 if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3448 continue; /* don't even try */
3449 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 */
3451 if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3452 continue; /* don't even try */
3453 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 */
3455 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3456 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3457 #ifdef DEBUG_VERBOSE
3458 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3460 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3463 evaluate_fixed_subframe_(
3466 residual[!_best_subframe],
3467 encoder->private_->abs_residual_partition_sums,
3468 encoder->private_->raw_bits_per_partition,
3469 frame_header->blocksize,
3473 min_partition_order,
3474 max_partition_order,
3475 encoder->protected_->do_escape_coding,
3476 encoder->protected_->rice_parameter_search_dist,
3477 subframe[!_best_subframe],
3478 partitioned_rice_contents[!_best_subframe]
3480 if(_candidate_bits < _best_bits) {
3481 _best_subframe = !_best_subframe;
3482 _best_bits = _candidate_bits;
3487 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3489 if(encoder->protected_->max_lpc_order > 0) {
3490 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3491 max_lpc_order = frame_header->blocksize-1;
3493 max_lpc_order = encoder->protected_->max_lpc_order;
3494 if(max_lpc_order > 0) {
3496 for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3497 FLAC__lpc_window_data(real_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3498 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3499 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3500 if(autoc[0] != 0.0) {
3501 FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3502 if(encoder->protected_->do_exhaustive_model_search) {
3506 const unsigned guess_lpc_order =
3507 FLAC__lpc_compute_best_order(
3510 frame_header->blocksize,
3512 encoder->protected_->do_qlp_coeff_prec_search?
3513 FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
3514 encoder->protected_->qlp_coeff_precision
3517 min_lpc_order = max_lpc_order = guess_lpc_order;
3519 if(max_lpc_order >= frame_header->blocksize)
3520 max_lpc_order = frame_header->blocksize - 1;
3521 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
3522 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
3523 if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
3524 continue; /* don't even try */
3525 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
3526 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3527 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3528 #ifdef DEBUG_VERBOSE
3529 fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3531 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3533 if(encoder->protected_->do_qlp_coeff_prec_search) {
3534 min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
3535 /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
3536 if(subframe_bps <= 17) {
3537 max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
3538 max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
3541 max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
3544 min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
3546 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
3548 evaluate_lpc_subframe_(
3551 residual[!_best_subframe],
3552 encoder->private_->abs_residual_partition_sums,
3553 encoder->private_->raw_bits_per_partition,
3554 encoder->private_->lp_coeff[lpc_order-1],
3555 frame_header->blocksize,
3558 qlp_coeff_precision,
3560 min_partition_order,
3561 max_partition_order,
3562 encoder->protected_->do_escape_coding,
3563 encoder->protected_->rice_parameter_search_dist,
3564 subframe[!_best_subframe],
3565 partitioned_rice_contents[!_best_subframe]
3567 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
3568 if(_candidate_bits < _best_bits) {
3569 _best_subframe = !_best_subframe;
3570 _best_bits = _candidate_bits;
3579 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3583 /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3584 if(_best_bits == UINT_MAX) {
3585 FLAC__ASSERT(_best_subframe == 0);
3586 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3589 *best_subframe = _best_subframe;
3590 *best_bits = _best_bits;
3595 FLAC__bool add_subframe_(
3596 FLAC__StreamEncoder *encoder,
3598 unsigned subframe_bps,
3599 const FLAC__Subframe *subframe,
3600 FLAC__BitWriter *frame
3603 switch(subframe->type) {
3604 case FLAC__SUBFRAME_TYPE_CONSTANT:
3605 if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3606 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3610 case FLAC__SUBFRAME_TYPE_FIXED:
3611 if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3612 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3616 case FLAC__SUBFRAME_TYPE_LPC:
3617 if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3618 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3622 case FLAC__SUBFRAME_TYPE_VERBATIM:
3623 if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3624 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3635 #define SPOTCHECK_ESTIMATE 0 //@@@@@@@@@
3636 #if SPOTCHECK_ESTIMATE
3637 static void spotcheck_subframe_estimate_(
3638 FLAC__StreamEncoder *encoder,
3640 unsigned subframe_bps,
3641 const FLAC__Subframe *subframe,
3646 FLAC__BitWriter *frame = FLAC__bitwriter_new();
3648 fprintf(stderr, "EST: can't allocate frame\n");
3651 if(!FLAC__bitwriter_init(frame)) {
3652 fprintf(stderr, "EST: can't init frame\n");
3655 ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
3658 const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
3659 if(estimate != actual)
3660 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);
3662 FLAC__bitwriter_delete(frame);
3666 unsigned evaluate_constant_subframe_(
3667 FLAC__StreamEncoder *encoder,
3668 const FLAC__int32 signal,
3670 unsigned subframe_bps,
3671 FLAC__Subframe *subframe
3675 subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3676 subframe->data.constant.value = signal;
3678 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
3680 #if SPOTCHECK_ESTIMATE
3681 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3683 (void)encoder, (void)blocksize;
3689 unsigned evaluate_fixed_subframe_(
3690 FLAC__StreamEncoder *encoder,
3691 const FLAC__int32 signal[],
3692 FLAC__int32 residual[],
3693 FLAC__uint64 abs_residual_partition_sums[],
3694 unsigned raw_bits_per_partition[],
3696 unsigned subframe_bps,
3698 unsigned rice_parameter,
3699 unsigned min_partition_order,
3700 unsigned max_partition_order,
3701 FLAC__bool do_escape_coding,
3702 unsigned rice_parameter_search_dist,
3703 FLAC__Subframe *subframe,
3704 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3707 unsigned i, residual_bits, estimate;
3708 const unsigned residual_samples = blocksize - order;
3710 FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3712 subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3714 subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3715 subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3716 subframe->data.fixed.residual = residual;
3719 find_best_partition_order_(
3722 abs_residual_partition_sums,
3723 raw_bits_per_partition,
3727 min_partition_order,
3728 max_partition_order,
3730 rice_parameter_search_dist,
3731 &subframe->data.fixed.entropy_coding_method.data.partitioned_rice
3734 subframe->data.fixed.order = order;
3735 for(i = 0; i < order; i++)
3736 subframe->data.fixed.warmup[i] = signal[i];
3738 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
3740 #if SPOTCHECK_ESTIMATE
3741 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3747 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3748 unsigned evaluate_lpc_subframe_(
3749 FLAC__StreamEncoder *encoder,
3750 const FLAC__int32 signal[],
3751 FLAC__int32 residual[],
3752 FLAC__uint64 abs_residual_partition_sums[],
3753 unsigned raw_bits_per_partition[],
3754 const FLAC__real lp_coeff[],
3756 unsigned subframe_bps,
3758 unsigned qlp_coeff_precision,
3759 unsigned rice_parameter,
3760 unsigned min_partition_order,
3761 unsigned max_partition_order,
3762 FLAC__bool do_escape_coding,
3763 unsigned rice_parameter_search_dist,
3764 FLAC__Subframe *subframe,
3765 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3768 FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
3769 unsigned i, residual_bits, estimate;
3770 int quantization, ret;
3771 const unsigned residual_samples = blocksize - order;
3773 /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3774 if(subframe_bps <= 16) {
3775 FLAC__ASSERT(order > 0);
3776 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3777 qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3780 ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3782 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3784 if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3785 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3786 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3788 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3790 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3792 subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3794 subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3795 subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3796 subframe->data.lpc.residual = residual;
3799 find_best_partition_order_(
3802 abs_residual_partition_sums,
3803 raw_bits_per_partition,
3807 min_partition_order,
3808 max_partition_order,
3810 rice_parameter_search_dist,
3811 &subframe->data.lpc.entropy_coding_method.data.partitioned_rice
3814 subframe->data.lpc.order = order;
3815 subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3816 subframe->data.lpc.quantization_level = quantization;
3817 memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3818 for(i = 0; i < order; i++)
3819 subframe->data.lpc.warmup[i] = signal[i];
3821 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;
3823 #if SPOTCHECK_ESTIMATE
3824 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3831 unsigned evaluate_verbatim_subframe_(
3832 FLAC__StreamEncoder *encoder,
3833 const FLAC__int32 signal[],
3835 unsigned subframe_bps,
3836 FLAC__Subframe *subframe
3841 subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3843 subframe->data.verbatim.data = signal;
3845 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
3847 #if SPOTCHECK_ESTIMATE
3848 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3856 unsigned find_best_partition_order_(
3857 FLAC__StreamEncoderPrivate *private_,
3858 const FLAC__int32 residual[],
3859 FLAC__uint64 abs_residual_partition_sums[],
3860 unsigned raw_bits_per_partition[],
3861 unsigned residual_samples,
3862 unsigned predictor_order,
3863 unsigned rice_parameter,
3864 unsigned min_partition_order,
3865 unsigned max_partition_order,
3866 FLAC__bool do_escape_coding,
3867 unsigned rice_parameter_search_dist,
3868 FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
3871 unsigned residual_bits, best_residual_bits = 0;
3872 unsigned best_parameters_index = 0;
3873 const unsigned blocksize = residual_samples + predictor_order;
3875 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3876 min_partition_order = min(min_partition_order, max_partition_order);
3878 precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order);
3880 if(do_escape_coding)
3881 precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3884 int partition_order;
3887 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3889 set_partitioned_rice_(
3890 #ifdef EXACT_RICE_BITS_CALCULATION
3893 abs_residual_partition_sums+sum,
3894 raw_bits_per_partition+sum,
3898 rice_parameter_search_dist,
3899 (unsigned)partition_order,
3901 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3906 FLAC__ASSERT(best_residual_bits != 0);
3909 sum += 1u << partition_order;
3910 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3911 best_residual_bits = residual_bits;
3912 best_parameters_index = !best_parameters_index;
3913 best_partitioned_rice->order = partition_order;
3919 * We are allowed to de-const the pointer based on our special knowledge;
3920 * it is const to the outside world.
3923 FLAC__EntropyCodingMethod_PartitionedRiceContents* best_partitioned_rice_contents = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_partitioned_rice->contents;
3924 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(best_partitioned_rice_contents, max(6, best_partitioned_rice->order));
3925 memcpy(best_partitioned_rice_contents->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
3926 memcpy(best_partitioned_rice_contents->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
3929 return best_residual_bits;
3932 void precompute_partition_info_sums_(
3933 const FLAC__int32 residual[],
3934 FLAC__uint64 abs_residual_partition_sums[],
3935 unsigned residual_samples,
3936 unsigned predictor_order,
3937 unsigned min_partition_order,
3938 unsigned max_partition_order
3941 int partition_order;
3942 unsigned from_partition, to_partition = 0;
3943 const unsigned blocksize = residual_samples + predictor_order;
3945 /* first do max_partition_order */
3946 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3947 FLAC__uint64 abs_residual_partition_sum; /* OPT: can reasonably be FLAC__uint32 for bps <= 17 and maybe higher */
3948 unsigned partition, partition_sample, partition_samples, residual_sample;
3949 const unsigned partitions = 1u << partition_order;
3950 const unsigned default_partition_samples = blocksize >> partition_order;
3952 FLAC__ASSERT(default_partition_samples > predictor_order);
3954 for(partition = residual_sample = 0; partition < partitions; partition++) {
3955 partition_samples = default_partition_samples;
3957 partition_samples -= predictor_order;
3958 abs_residual_partition_sum = 0;
3959 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++, residual_sample++) {
3960 #if defined _MSC_VER && _MSC_VER <= 1200
3961 /* OPT: abs() may be faster for some compilers */
3962 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3964 const FLAC__int32 r = residual[residual_sample];
3966 abs_residual_partition_sum -= r;
3968 abs_residual_partition_sum += r;
3971 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3973 to_partition = partitions;
3977 /* now merge partitions for lower orders */
3978 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
3981 const unsigned partitions = 1u << partition_order;
3982 for(i = 0; i < partitions; i++) {
3983 s = abs_residual_partition_sums[from_partition];
3985 abs_residual_partition_sums[to_partition] = s + abs_residual_partition_sums[from_partition];
3992 void precompute_partition_info_escapes_(
3993 const FLAC__int32 residual[],
3994 unsigned raw_bits_per_partition[],
3995 unsigned residual_samples,
3996 unsigned predictor_order,
3997 unsigned min_partition_order,
3998 unsigned max_partition_order
4001 int partition_order;
4002 unsigned from_partition, to_partition = 0;
4003 const unsigned blocksize = residual_samples + predictor_order;
4005 /* first do max_partition_order */
4006 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
4007 FLAC__int32 r, residual_partition_min, residual_partition_max;
4008 unsigned silog2_min, silog2_max;
4009 unsigned partition, partition_sample, partition_samples, residual_sample;
4010 const unsigned partitions = 1u << partition_order;
4011 const unsigned default_partition_samples = blocksize >> partition_order;
4013 FLAC__ASSERT(default_partition_samples > predictor_order);
4015 for(partition = residual_sample = 0; partition < partitions; partition++) {
4016 partition_samples = default_partition_samples;
4018 partition_samples -= predictor_order;
4019 residual_partition_min = residual_partition_max = 0;
4020 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
4021 r = residual[residual_sample];
4022 if(r < residual_partition_min)
4023 residual_partition_min = r;
4024 else if(r > residual_partition_max)
4025 residual_partition_max = r;
4028 silog2_min = FLAC__bitmath_silog2(residual_partition_min);
4029 silog2_max = FLAC__bitmath_silog2(residual_partition_max);
4030 raw_bits_per_partition[partition] = max(silog2_min, silog2_max);
4032 to_partition = partitions;
4033 break; /*@@@ yuck, should remove the 'for' loop instead */
4036 /* now merge partitions for lower orders */
4037 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
4040 const unsigned partitions = 1u << partition_order;
4041 for(i = 0; i < partitions; i++) {
4042 m = raw_bits_per_partition[from_partition];
4044 raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
4051 /*@@@@@@ overflow is a possible problem here for hi-res samples */
4052 #ifdef EXACT_RICE_BITS_CALCULATION
4053 static __inline unsigned count_rice_bits_in_partition_(
4054 const unsigned rice_parameter,
4055 const unsigned partition_samples,
4056 const FLAC__int32 *residual
4059 unsigned i, partition_bits =
4060 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN +
4061 (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
4063 for(i = 0; i < partition_samples; i++)
4064 partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
4065 return partition_bits;
4068 static __inline unsigned count_rice_bits_in_partition_(
4069 const unsigned rice_parameter,
4070 const unsigned partition_samples,
4071 const FLAC__uint64 abs_residual_partition_sum
4075 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN +
4076 (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
4079 (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
4080 : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
4082 - (partition_samples >> 1)
4083 /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
4084 * The actual number of bits used is closer to the sum for all i in the partition of abs(residual[i])>>(rice_parameter-1)
4085 * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
4086 * So the subtraction term tries to guess how many extra bits were contributed.
4087 * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
4093 FLAC__bool set_partitioned_rice_(
4094 #ifdef EXACT_RICE_BITS_CALCULATION
4095 const FLAC__int32 residual[],
4097 const FLAC__uint64 abs_residual_partition_sums[],
4098 const unsigned raw_bits_per_partition[],
4099 const unsigned residual_samples,
4100 const unsigned predictor_order,
4101 const unsigned suggested_rice_parameter,
4102 const unsigned rice_parameter_search_dist,
4103 const unsigned partition_order,
4104 const FLAC__bool search_for_escapes,
4105 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
4109 unsigned rice_parameter, partition_bits;
4110 unsigned best_partition_bits, best_rice_parameter = 0;
4112 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
4113 unsigned *parameters, *raw_bits;
4114 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4115 unsigned min_rice_parameter, max_rice_parameter;
4117 (void)rice_parameter_search_dist;
4120 FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
4122 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
4123 parameters = partitioned_rice_contents->parameters;
4124 raw_bits = partitioned_rice_contents->raw_bits;
4126 if(partition_order == 0) {
4127 best_partition_bits = 0xffffffff;
4128 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4129 if(rice_parameter_search_dist) {
4130 if(suggested_rice_parameter < rice_parameter_search_dist)
4131 min_rice_parameter = 0;
4133 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
4134 max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
4135 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
4136 #ifdef DEBUG_VERBOSE
4137 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
4139 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
4143 min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
4145 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4147 rice_parameter = suggested_rice_parameter;
4149 #ifdef EXACT_RICE_BITS_CALCULATION
4150 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
4152 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
4154 if(partition_bits < best_partition_bits) {
4155 best_rice_parameter = rice_parameter;
4156 best_partition_bits = partition_bits;
4158 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4161 if(search_for_escapes) {
4162 flat_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[0] * residual_samples;
4163 if(flat_bits <= best_partition_bits) {
4164 raw_bits[0] = raw_bits_per_partition[0];
4165 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
4166 best_partition_bits = flat_bits;
4169 parameters[0] = best_rice_parameter;
4170 bits_ += best_partition_bits;
4173 unsigned partition, residual_sample;
4174 unsigned partition_samples;
4175 FLAC__uint64 mean, k;
4176 const unsigned partitions = 1u << partition_order;
4177 for(partition = residual_sample = 0; partition < partitions; partition++) {
4178 partition_samples = (residual_samples+predictor_order) >> partition_order;
4179 if(partition == 0) {
4180 if(partition_samples <= predictor_order)
4183 partition_samples -= predictor_order;
4185 mean = abs_residual_partition_sums[partition];
4186 /* we are basically calculating the size in bits of the
4187 * average residual magnitude in the partition:
4188 * rice_parameter = floor(log2(mean/partition_samples))
4189 * 'mean' is not a good name for the variable, it is
4190 * actually the sum of magnitudes of all residual values
4191 * in the partition, so the actual mean is
4192 * mean/partition_samples
4194 for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
4196 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
4197 #ifdef DEBUG_VERBOSE
4198 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
4200 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
4203 best_partition_bits = 0xffffffff;
4204 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4205 if(rice_parameter_search_dist) {
4206 if(rice_parameter < rice_parameter_search_dist)
4207 min_rice_parameter = 0;
4209 min_rice_parameter = rice_parameter - rice_parameter_search_dist;
4210 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
4211 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
4212 #ifdef DEBUG_VERBOSE
4213 fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
4215 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
4219 min_rice_parameter = max_rice_parameter = rice_parameter;
4221 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4223 #ifdef EXACT_RICE_BITS_CALCULATION
4224 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
4226 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
4228 if(partition_bits < best_partition_bits) {
4229 best_rice_parameter = rice_parameter;
4230 best_partition_bits = partition_bits;
4232 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4235 if(search_for_escapes) {
4236 flat_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[partition] * partition_samples;
4237 if(flat_bits <= best_partition_bits) {
4238 raw_bits[partition] = raw_bits_per_partition[partition];
4239 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
4240 best_partition_bits = flat_bits;
4243 parameters[partition] = best_rice_parameter;
4244 bits_ += best_partition_bits;
4245 residual_sample += partition_samples;
4253 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
4258 for(i = 0; i < samples && !(x&1); i++)
4265 for(shift = 0; !(x&1); shift++)
4270 for(i = 0; i < samples; i++)
4271 signal[i] >>= shift;
4277 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4281 for(channel = 0; channel < channels; channel++)
4282 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
4284 fifo->tail += wide_samples;
4286 FLAC__ASSERT(fifo->tail <= fifo->size);
4289 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4292 unsigned sample, wide_sample;
4293 unsigned tail = fifo->tail;
4295 sample = input_offset * channels;
4296 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
4297 for(channel = 0; channel < channels; channel++)
4298 fifo->data[channel][tail] = input[sample++];
4303 FLAC__ASSERT(fifo->tail <= fifo->size);
4306 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4308 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4309 const size_t encoded_bytes = encoder->private_->verify.output.bytes;
4312 if(encoder->private_->verify.needs_magic_hack) {
4313 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
4314 *bytes = FLAC__STREAM_SYNC_LENGTH;
4315 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
4316 encoder->private_->verify.needs_magic_hack = false;
4319 if(encoded_bytes == 0) {
4321 * If we get here, a FIFO underflow has occurred,
4322 * which means there is a bug somewhere.
4325 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
4327 else if(encoded_bytes < *bytes)
4328 *bytes = encoded_bytes;
4329 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
4330 encoder->private_->verify.output.data += *bytes;
4331 encoder->private_->verify.output.bytes -= *bytes;
4334 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
4337 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
4339 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
4341 const unsigned channels = frame->header.channels;
4342 const unsigned blocksize = frame->header.blocksize;
4343 const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
4347 for(channel = 0; channel < channels; channel++) {
4348 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
4349 unsigned i, sample = 0;
4350 FLAC__int32 expect = 0, got = 0;
4352 for(i = 0; i < blocksize; i++) {
4353 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
4355 expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
4356 got = (FLAC__int32)buffer[channel][i];
4360 FLAC__ASSERT(i < blocksize);
4361 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
4362 encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
4363 encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
4364 encoder->private_->verify.error_stats.channel = channel;
4365 encoder->private_->verify.error_stats.sample = sample;
4366 encoder->private_->verify.error_stats.expected = expect;
4367 encoder->private_->verify.error_stats.got = got;
4368 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
4369 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
4372 /* dequeue the frame from the fifo */
4373 encoder->private_->verify.input_fifo.tail -= blocksize;
4374 FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
4375 for(channel = 0; channel < channels; channel++)
4376 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]));
4377 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4380 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4382 (void)decoder, (void)metadata, (void)client_data;
4385 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4387 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4388 (void)decoder, (void)status;
4389 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4392 FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4396 *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
4398 if (feof(encoder->private_->file))
4399 return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
4400 else if (ferror(encoder->private_->file))
4401 return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
4403 return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
4406 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4410 if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
4411 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4413 return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4416 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4422 offset = ftello(encoder->private_->file);
4425 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4428 *absolute_byte_offset = (FLAC__uint64)offset;
4429 return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4433 #ifdef FLAC__VALGRIND_TESTING
4434 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4436 size_t ret = fwrite(ptr, size, nmemb, stream);
4442 #define local__fwrite fwrite
4445 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
4447 (void)client_data, (void)current_frame;
4449 if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4450 FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
4452 /* We would like to be able to use 'samples > 0' in the
4453 * clause here but currently because of the nature of our
4454 * Ogg writing implementation, 'samples' is always 0 (see
4455 * ogg_encoder_aspect.c). The downside is extra progress
4458 encoder->private_->is_ogg? true :
4463 /* NOTE: We have to add +bytes, +samples, and +1 to the stats
4464 * because at this point in the callback chain, the stats
4465 * have not been updated. Only after we return and control
4466 * gets back to write_frame_() are the stats updated
4468 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);
4470 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4473 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4477 * This will forcibly set stdout to binary mode (for OSes that require it)
4479 FILE *get_binary_stdout_()
4481 /* if something breaks here it is probably due to the presence or
4482 * absence of an underscore before the identifiers 'setmode',
4483 * 'fileno', and/or 'O_BINARY'; check your system header files.
4485 #if defined _MSC_VER || defined __MINGW32__
4486 _setmode(_fileno(stdout), _O_BINARY);
4487 #elif defined __CYGWIN__
4488 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4489 setmode(_fileno(stdout), _O_BINARY);
4490 #elif defined __EMX__
4491 setmode(fileno(stdout), O_BINARY);