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.
33 #undef WINDOW_DEBUG_OUTPUT
39 #if defined _MSC_VER || defined __MINGW32__
40 #include <io.h> /* for _setmode() */
41 #include <fcntl.h> /* for _O_BINARY */
43 #if defined __CYGWIN__ || defined __EMX__
44 #include <io.h> /* for setmode(), O_BINARY */
45 #include <fcntl.h> /* for _O_BINARY */
49 #include <stdlib.h> /* for malloc() */
50 #include <string.h> /* for memcpy() */
51 #include <sys/types.h> /* for off_t */
52 #if defined _MSC_VER || defined __MINGW32__
53 /*@@@ [2G limit] hacks for MSVC6 */
57 #include "FLAC/assert.h"
58 #include "FLAC/stream_decoder.h"
59 #include "protected/stream_encoder.h"
60 #include "private/bitbuffer.h"
61 #include "private/bitmath.h"
62 #include "private/crc.h"
63 #include "private/cpu.h"
64 #include "private/fixed.h"
65 #include "private/format.h"
66 #include "private/lpc.h"
67 #include "private/md5.h"
68 #include "private/memory.h"
69 #include "private/stream_encoder_framing.h"
70 #include "private/window.h"
75 #define min(x,y) ((x)<(y)?(x):(y))
80 #define max(x,y) ((x)>(y)?(x):(y))
83 FLAC__int32 *data[FLAC__MAX_CHANNELS];
84 unsigned size; /* of each data[] in samples */
89 const FLAC__byte *data;
96 ENCODER_IN_METADATA = 1,
100 /***********************************************************************
102 * Private class method prototypes
104 ***********************************************************************/
106 static void set_defaults_(FLAC__StreamEncoder *encoder);
107 static void free_(FLAC__StreamEncoder *encoder);
108 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_size);
109 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples);
110 static FLAC__StreamEncoderWriteStatus write_frame_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples);
111 static void update_metadata_(const FLAC__StreamEncoder *encoder);
112 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame);
113 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame);
115 static FLAC__bool process_subframe_(
116 FLAC__StreamEncoder *encoder,
117 unsigned min_partition_order,
118 unsigned max_partition_order,
119 FLAC__bool precompute_partition_sums,
120 const FLAC__FrameHeader *frame_header,
121 unsigned subframe_bps,
122 const FLAC__int32 integer_signal[],
123 #ifndef FLAC__INTEGER_ONLY_LIBRARY
124 const FLAC__real real_signal[],
126 FLAC__Subframe *subframe[2],
127 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
128 FLAC__int32 *residual[2],
129 unsigned *best_subframe,
131 #ifdef WINDOW_DEBUG_OUTPUT
132 ,unsigned subframe_number
136 static FLAC__bool add_subframe_(
137 FLAC__StreamEncoder *encoder,
138 const FLAC__FrameHeader *frame_header,
139 unsigned subframe_bps,
140 const FLAC__Subframe *subframe,
141 FLAC__BitBuffer *frame
142 #ifdef WINDOW_DEBUG_OUTPUT
143 ,unsigned subframe_bits
147 static unsigned evaluate_constant_subframe_(
148 const FLAC__int32 signal,
149 unsigned subframe_bps,
150 FLAC__Subframe *subframe
153 static unsigned evaluate_fixed_subframe_(
154 FLAC__StreamEncoder *encoder,
155 const FLAC__int32 signal[],
156 FLAC__int32 residual[],
157 FLAC__uint32 abs_residual[],
158 FLAC__uint64 abs_residual_partition_sums[],
159 unsigned raw_bits_per_partition[],
161 unsigned subframe_bps,
163 unsigned rice_parameter,
164 unsigned min_partition_order,
165 unsigned max_partition_order,
166 FLAC__bool precompute_partition_sums,
167 FLAC__bool do_escape_coding,
168 unsigned rice_parameter_search_dist,
169 FLAC__Subframe *subframe,
170 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
173 #ifndef FLAC__INTEGER_ONLY_LIBRARY
174 static unsigned evaluate_lpc_subframe_(
175 FLAC__StreamEncoder *encoder,
176 const FLAC__int32 signal[],
177 FLAC__int32 residual[],
178 FLAC__uint32 abs_residual[],
179 FLAC__uint64 abs_residual_partition_sums[],
180 unsigned raw_bits_per_partition[],
181 const FLAC__real lp_coeff[],
183 unsigned subframe_bps,
185 unsigned qlp_coeff_precision,
186 unsigned rice_parameter,
187 unsigned min_partition_order,
188 unsigned max_partition_order,
189 FLAC__bool precompute_partition_sums,
190 FLAC__bool do_escape_coding,
191 unsigned rice_parameter_search_dist,
192 FLAC__Subframe *subframe,
193 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
194 #ifdef WINDOW_DEBUG_OUTPUT
195 ,unsigned frame_number
196 ,unsigned subframe_number
197 ,FLAC__ApodizationSpecification aspec
202 static unsigned evaluate_verbatim_subframe_(
203 const FLAC__int32 signal[],
205 unsigned subframe_bps,
206 FLAC__Subframe *subframe
209 static unsigned find_best_partition_order_(
210 struct FLAC__StreamEncoderPrivate *private_,
211 const FLAC__int32 residual[],
212 FLAC__uint32 abs_residual[],
213 FLAC__uint64 abs_residual_partition_sums[],
214 unsigned raw_bits_per_partition[],
215 unsigned residual_samples,
216 unsigned predictor_order,
217 unsigned rice_parameter,
218 unsigned min_partition_order,
219 unsigned max_partition_order,
220 FLAC__bool precompute_partition_sums,
221 FLAC__bool do_escape_coding,
222 unsigned rice_parameter_search_dist,
223 FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
226 static void precompute_partition_info_sums_(
227 const FLAC__uint32 abs_residual[],
228 FLAC__uint64 abs_residual_partition_sums[],
229 unsigned residual_samples,
230 unsigned predictor_order,
231 unsigned min_partition_order,
232 unsigned max_partition_order
235 static void precompute_partition_info_escapes_(
236 const FLAC__int32 residual[],
237 unsigned raw_bits_per_partition[],
238 unsigned residual_samples,
239 unsigned predictor_order,
240 unsigned min_partition_order,
241 unsigned max_partition_order
244 #ifdef DONT_ESTIMATE_RICE_BITS
245 static FLAC__bool set_partitioned_rice_(
246 const FLAC__uint32 abs_residual[],
247 const FLAC__int32 residual[],
248 const unsigned residual_samples,
249 const unsigned predictor_order,
250 const unsigned suggested_rice_parameter,
251 const unsigned rice_parameter_search_dist,
252 const unsigned partition_order,
253 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
257 static FLAC__bool set_partitioned_rice_with_precompute_(
258 const FLAC__int32 residual[],
259 const FLAC__uint64 abs_residual_partition_sums[],
260 const unsigned raw_bits_per_partition[],
261 const unsigned residual_samples,
262 const unsigned predictor_order,
263 const unsigned suggested_rice_parameter,
264 const unsigned rice_parameter_search_dist,
265 const unsigned partition_order,
266 const FLAC__bool search_for_escapes,
267 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
271 static FLAC__bool set_partitioned_rice_(
272 const FLAC__uint32 abs_residual[],
273 const unsigned residual_samples,
274 const unsigned predictor_order,
275 const unsigned suggested_rice_parameter,
276 const unsigned rice_parameter_search_dist,
277 const unsigned partition_order,
278 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
282 static FLAC__bool set_partitioned_rice_with_precompute_(
283 const FLAC__uint32 abs_residual[],
284 const FLAC__uint64 abs_residual_partition_sums[],
285 const unsigned raw_bits_per_partition[],
286 const unsigned residual_samples,
287 const unsigned predictor_order,
288 const unsigned suggested_rice_parameter,
289 const unsigned rice_parameter_search_dist,
290 const unsigned partition_order,
291 const FLAC__bool search_for_escapes,
292 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
297 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
299 /* verify-related routines: */
300 static void append_to_verify_fifo_(
301 verify_input_fifo *fifo,
302 const FLAC__int32 * const input[],
303 unsigned input_offset,
305 unsigned wide_samples
308 static void append_to_verify_fifo_interleaved_(
309 verify_input_fifo *fifo,
310 const FLAC__int32 input[],
311 unsigned input_offset,
313 unsigned wide_samples
316 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
317 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
318 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
319 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
321 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
322 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
323 static FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
324 static FILE *get_binary_stdout_();
326 #ifdef WINDOW_DEBUG_OUTPUT
327 static const char * const winstr[] = {
331 "blackman_harris_4term_92db_sidelobe",
346 /***********************************************************************
350 ***********************************************************************/
352 typedef struct FLAC__StreamEncoderPrivate {
353 unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
354 FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
355 FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
356 #ifndef FLAC__INTEGER_ONLY_LIBRARY
357 FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* the floating-point version of the input signal */
358 FLAC__real *real_signal_mid_side[2]; /* the floating-point version of the mid-side input signal (stereo only) */
359 FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
360 FLAC__real *windowed_signal; /* the real_signal[] * current window[] */
362 unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
363 unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
364 FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
365 FLAC__int32 *residual_workspace_mid_side[2][2];
366 FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
367 FLAC__Subframe subframe_workspace_mid_side[2][2];
368 FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
369 FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
370 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
371 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
372 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
373 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
374 unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index into the above workspaces */
375 unsigned best_subframe_mid_side[2];
376 unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
377 unsigned best_subframe_bits_mid_side[2];
378 FLAC__uint32 *abs_residual; /* workspace where abs(candidate residual) is stored */
379 FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
380 unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
381 FLAC__BitBuffer *frame; /* the current frame being worked on */
382 unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
383 unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
384 FLAC__ChannelAssignment last_channel_assignment;
385 FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
386 FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
387 unsigned current_sample_number;
388 unsigned current_frame_number;
389 struct FLAC__MD5Context md5context;
390 FLAC__CPUInfo cpuinfo;
391 #ifndef FLAC__INTEGER_ONLY_LIBRARY
392 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
394 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
396 #ifndef FLAC__INTEGER_ONLY_LIBRARY
397 void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
398 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[]);
399 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[]);
400 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[]);
402 FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
403 FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
404 FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
405 FLAC__bool precompute_partition_sums; /* our initial guess as to whether precomputing the partitions sums will be a speed improvement */
406 FLAC__bool disable_constant_subframes;
407 FLAC__bool disable_fixed_subframes;
408 FLAC__bool disable_verbatim_subframes;
409 FLAC__StreamEncoderSeekCallback seek_callback;
410 FLAC__StreamEncoderTellCallback tell_callback;
411 FLAC__StreamEncoderWriteCallback write_callback;
412 FLAC__StreamEncoderMetadataCallback metadata_callback;
413 FLAC__StreamEncoderProgressCallback progress_callback;
415 unsigned first_seekpoint_to_check;
416 FILE *file; /* only used when encoding to a file */
417 FLAC__uint64 bytes_written;
418 FLAC__uint64 samples_written;
419 unsigned frames_written;
420 unsigned total_frames_estimate;
421 /* unaligned (original) pointers to allocated data */
422 FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
423 FLAC__int32 *integer_signal_mid_side_unaligned[2];
424 #ifndef FLAC__INTEGER_ONLY_LIBRARY
425 FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS];
426 FLAC__real *real_signal_mid_side_unaligned[2];
427 FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
428 FLAC__real *windowed_signal_unaligned;
430 FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
431 FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
432 FLAC__uint32 *abs_residual_unaligned;
433 FLAC__uint64 *abs_residual_partition_sums_unaligned;
434 unsigned *raw_bits_per_partition_unaligned;
436 * These fields have been moved here from private function local
437 * declarations merely to save stack space during encoding.
439 #ifndef FLAC__INTEGER_ONLY_LIBRARY
440 FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
442 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
444 * The data for the verify section
447 FLAC__StreamDecoder *decoder;
448 EncoderStateHint state_hint;
449 FLAC__bool needs_magic_hack;
450 verify_input_fifo input_fifo;
451 verify_output output;
453 FLAC__uint64 absolute_sample;
454 unsigned frame_number;
457 FLAC__int32 expected;
461 FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
462 } FLAC__StreamEncoderPrivate;
464 /***********************************************************************
466 * Public static class data
468 ***********************************************************************/
470 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
471 "FLAC__STREAM_ENCODER_OK",
472 "FLAC__STREAM_ENCODER_UNINITIALIZED",
473 "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
474 "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
475 "FLAC__STREAM_ENCODER_CLIENT_ERROR",
476 "FLAC__STREAM_ENCODER_IO_ERROR",
477 "FLAC__STREAM_ENCODER_FRAMING_ERROR",
478 "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
481 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
482 "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
483 "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
484 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
485 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
486 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
487 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
488 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
489 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
490 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
491 "FLAC__STREAM_ENCODER_INIT_STATUS_MID_SIDE_CHANNELS_MISMATCH",
492 "FLAC__STREAM_ENCODER_INIT_STATUS_ILLEGAL_MID_SIDE_FORCE",
493 "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
494 "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
495 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
496 "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
499 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
500 "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
501 "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
504 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
505 "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
506 "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
507 "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
510 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
511 "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
512 "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
513 "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
516 /***********************************************************************
518 * Class constructor/destructor
521 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new()
523 FLAC__StreamEncoder *encoder;
526 FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
528 encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
533 encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
534 if(encoder->protected_ == 0) {
539 encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
540 if(encoder->private_ == 0) {
541 free(encoder->protected_);
546 encoder->private_->frame = FLAC__bitbuffer_new();
547 if(encoder->private_->frame == 0) {
548 free(encoder->private_);
549 free(encoder->protected_);
554 encoder->private_->file = 0;
556 set_defaults_(encoder);
558 encoder->private_->is_being_deleted = false;
560 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
561 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
562 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
564 for(i = 0; i < 2; i++) {
565 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
566 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
568 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
569 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
570 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
572 for(i = 0; i < 2; i++) {
573 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
574 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
577 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
578 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
579 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
581 for(i = 0; i < 2; i++) {
582 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
583 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
585 for(i = 0; i < 2; i++)
586 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
588 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
593 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
597 FLAC__ASSERT(0 != encoder);
598 FLAC__ASSERT(0 != encoder->protected_);
599 FLAC__ASSERT(0 != encoder->private_);
600 FLAC__ASSERT(0 != encoder->private_->frame);
602 encoder->private_->is_being_deleted = true;
604 FLAC__stream_encoder_finish(encoder);
606 if(0 != encoder->private_->verify.decoder)
607 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
609 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
610 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
611 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
613 for(i = 0; i < 2; i++) {
614 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
615 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
617 for(i = 0; i < 2; i++)
618 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
620 FLAC__bitbuffer_delete(encoder->private_->frame);
621 free(encoder->private_);
622 free(encoder->protected_);
626 /***********************************************************************
628 * Public class methods
630 ***********************************************************************/
632 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(FLAC__StreamEncoder *encoder, FLAC__StreamEncoderWriteCallback write_callback, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderTellCallback tell_callback, FLAC__StreamEncoderMetadataCallback metadata_callback, void *client_data)
635 FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
637 FLAC__ASSERT(0 != encoder);
639 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
640 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
642 if(0 == write_callback || (seek_callback && 0 == tell_callback))
643 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
645 if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
646 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
648 if(encoder->protected_->do_mid_side_stereo && encoder->protected_->channels != 2)
649 return FLAC__STREAM_ENCODER_INIT_STATUS_MID_SIDE_CHANNELS_MISMATCH;
651 if(encoder->protected_->loose_mid_side_stereo && !encoder->protected_->do_mid_side_stereo)
652 return FLAC__STREAM_ENCODER_INIT_STATUS_ILLEGAL_MID_SIDE_FORCE;
654 if(encoder->protected_->bits_per_sample >= 32)
655 encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
657 if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
658 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
660 if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
661 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
663 if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
664 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
666 if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
667 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
669 if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
670 return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
672 if(encoder->protected_->qlp_coeff_precision == 0) {
673 if(encoder->protected_->bits_per_sample < 16) {
674 /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
675 /* @@@ until then we'll make a guess */
676 encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
678 else if(encoder->protected_->bits_per_sample == 16) {
679 if(encoder->protected_->blocksize <= 192)
680 encoder->protected_->qlp_coeff_precision = 7;
681 else if(encoder->protected_->blocksize <= 384)
682 encoder->protected_->qlp_coeff_precision = 8;
683 else if(encoder->protected_->blocksize <= 576)
684 encoder->protected_->qlp_coeff_precision = 9;
685 else if(encoder->protected_->blocksize <= 1152)
686 encoder->protected_->qlp_coeff_precision = 10;
687 else if(encoder->protected_->blocksize <= 2304)
688 encoder->protected_->qlp_coeff_precision = 11;
689 else if(encoder->protected_->blocksize <= 4608)
690 encoder->protected_->qlp_coeff_precision = 12;
692 encoder->protected_->qlp_coeff_precision = 13;
695 if(encoder->protected_->blocksize <= 384)
696 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
697 else if(encoder->protected_->blocksize <= 1152)
698 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
700 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
702 FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
704 else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
705 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
707 if(encoder->protected_->streamable_subset) {
709 encoder->protected_->blocksize != 192 &&
710 encoder->protected_->blocksize != 576 &&
711 encoder->protected_->blocksize != 1152 &&
712 encoder->protected_->blocksize != 2304 &&
713 encoder->protected_->blocksize != 4608 &&
714 encoder->protected_->blocksize != 256 &&
715 encoder->protected_->blocksize != 512 &&
716 encoder->protected_->blocksize != 1024 &&
717 encoder->protected_->blocksize != 2048 &&
718 encoder->protected_->blocksize != 4096 &&
719 encoder->protected_->blocksize != 8192 &&
720 encoder->protected_->blocksize != 16384
722 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
724 encoder->protected_->sample_rate != 8000 &&
725 encoder->protected_->sample_rate != 16000 &&
726 encoder->protected_->sample_rate != 22050 &&
727 encoder->protected_->sample_rate != 24000 &&
728 encoder->protected_->sample_rate != 32000 &&
729 encoder->protected_->sample_rate != 44100 &&
730 encoder->protected_->sample_rate != 48000 &&
731 encoder->protected_->sample_rate != 96000
733 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
735 encoder->protected_->bits_per_sample != 8 &&
736 encoder->protected_->bits_per_sample != 12 &&
737 encoder->protected_->bits_per_sample != 16 &&
738 encoder->protected_->bits_per_sample != 20 &&
739 encoder->protected_->bits_per_sample != 24
741 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
742 if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
743 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
746 if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
747 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
748 if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
749 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
751 /* validate metadata */
752 if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
753 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
754 metadata_has_seektable = false;
755 metadata_has_vorbis_comment = false;
756 metadata_picture_has_type1 = false;
757 metadata_picture_has_type2 = false;
758 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
759 const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
760 if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
761 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
762 else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
763 if(metadata_has_seektable) /* only one is allowed */
764 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
765 metadata_has_seektable = true;
766 if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
767 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
769 else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
770 if(metadata_has_vorbis_comment) /* only one is allowed */
771 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
772 metadata_has_vorbis_comment = true;
774 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
775 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
776 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
778 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
779 if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
780 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
781 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
782 if(metadata_picture_has_type1) /* there should only be 1 per stream */
783 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
784 metadata_picture_has_type1 = true;
785 /* standard icon must be 32x32 pixel PNG */
787 m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
789 (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
790 m->data.picture.width != 32 ||
791 m->data.picture.height != 32
794 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
796 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
797 if(metadata_picture_has_type2) /* there should only be 1 per stream */
798 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
799 metadata_picture_has_type2 = true;
804 encoder->private_->input_capacity = 0;
805 for(i = 0; i < encoder->protected_->channels; i++) {
806 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
807 #ifndef FLAC__INTEGER_ONLY_LIBRARY
808 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
811 for(i = 0; i < 2; i++) {
812 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
813 #ifndef FLAC__INTEGER_ONLY_LIBRARY
814 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
817 #ifndef FLAC__INTEGER_ONLY_LIBRARY
818 for(i = 0; i < encoder->protected_->num_apodizations; i++)
819 encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
820 encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
822 for(i = 0; i < encoder->protected_->channels; i++) {
823 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
824 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
825 encoder->private_->best_subframe[i] = 0;
827 for(i = 0; i < 2; i++) {
828 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
829 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
830 encoder->private_->best_subframe_mid_side[i] = 0;
832 encoder->private_->abs_residual_unaligned = encoder->private_->abs_residual = 0;
833 encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
834 encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
835 #ifndef FLAC__INTEGER_ONLY_LIBRARY
836 encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
838 /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
839 /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply÷ by hand */
840 FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
841 FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
842 FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
843 FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
844 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);
846 if(encoder->private_->loose_mid_side_stereo_frames == 0)
847 encoder->private_->loose_mid_side_stereo_frames = 1;
848 encoder->private_->loose_mid_side_stereo_frame_count = 0;
849 encoder->private_->current_sample_number = 0;
850 encoder->private_->current_frame_number = 0;
852 encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
853 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? */
854 encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
857 * get the CPU info and set the function pointers
859 FLAC__cpu_info(&encoder->private_->cpuinfo);
860 /* first default to the non-asm routines */
861 #ifndef FLAC__INTEGER_ONLY_LIBRARY
862 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
864 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
865 #ifndef FLAC__INTEGER_ONLY_LIBRARY
866 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
867 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
868 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
870 /* now override with asm where appropriate */
871 #ifndef FLAC__INTEGER_ONLY_LIBRARY
872 # ifndef FLAC__NO_ASM
873 if(encoder->private_->cpuinfo.use_asm) {
874 # ifdef FLAC__CPU_IA32
875 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
876 # ifdef FLAC__HAS_NASM
878 if(encoder->private_->cpuinfo.data.ia32.sse) {
879 if(encoder->protected_->max_lpc_order < 4)
880 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
881 else if(encoder->protected_->max_lpc_order < 8)
882 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
883 else if(encoder->protected_->max_lpc_order < 12)
884 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
886 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
889 # endif /* FLAC__SSE_OS */
890 if(encoder->private_->cpuinfo.data.ia32._3dnow)
891 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
893 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
894 if(encoder->private_->cpuinfo.data.ia32.mmx) {
895 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
896 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
899 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
900 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
902 if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
903 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
904 # endif /* FLAC__HAS_NASM */
905 # endif /* FLAC__CPU_IA32 */
907 # endif /* !FLAC__NO_ASM */
908 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
909 /* finally override based on wide-ness if necessary */
910 if(encoder->private_->use_wide_by_block) {
911 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
914 /* we require precompute_partition_sums if do_escape_coding because of their intertwined nature */
915 encoder->private_->precompute_partition_sums = (encoder->protected_->max_residual_partition_order > encoder->protected_->min_residual_partition_order) || encoder->protected_->do_escape_coding;
917 /* set state to OK; from here on, errors are fatal and we'll override the state then */
918 encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
920 encoder->private_->write_callback = write_callback;
921 encoder->private_->seek_callback = seek_callback;
922 encoder->private_->tell_callback = tell_callback;
923 encoder->private_->metadata_callback = metadata_callback;
924 encoder->private_->client_data = client_data;
926 if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
927 /* the above function sets the state for us in case of an error */
928 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
931 if(!FLAC__bitbuffer_init(encoder->private_->frame)) {
932 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
933 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
937 * Set up the verify stuff if necessary
939 if(encoder->protected_->verify) {
941 * First, set up the fifo which will hold the
942 * original signal to compare against
944 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize;
945 for(i = 0; i < encoder->protected_->channels; i++) {
946 if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder->private_->verify.input_fifo.size))) {
947 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
948 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
951 encoder->private_->verify.input_fifo.tail = 0;
954 * Now set up a stream decoder for verification
956 encoder->private_->verify.decoder = FLAC__stream_decoder_new();
957 if(0 == encoder->private_->verify.decoder) {
958 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
959 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
962 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) {
963 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
964 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
967 encoder->private_->verify.error_stats.absolute_sample = 0;
968 encoder->private_->verify.error_stats.frame_number = 0;
969 encoder->private_->verify.error_stats.channel = 0;
970 encoder->private_->verify.error_stats.sample = 0;
971 encoder->private_->verify.error_stats.expected = 0;
972 encoder->private_->verify.error_stats.got = 0;
975 * These must be done before we write any metadata, because that
976 * calls the write_callback, which uses these values.
978 encoder->private_->first_seekpoint_to_check = 0;
979 encoder->private_->samples_written = 0;
980 encoder->protected_->streaminfo_offset = 0;
981 encoder->protected_->seektable_offset = 0;
982 encoder->protected_->audio_offset = 0;
985 * write the stream header
987 if(encoder->protected_->verify)
988 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
989 if(!FLAC__bitbuffer_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
990 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
991 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
993 if(!write_bitbuffer_(encoder, 0)) {
994 /* the above function sets the state for us in case of an error */
995 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
999 * write the STREAMINFO metadata block
1001 if(encoder->protected_->verify)
1002 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1003 encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1004 encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1005 encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1006 encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1007 encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1008 encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1009 encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1010 encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1011 encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1012 encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1013 encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1014 memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1015 FLAC__MD5Init(&encoder->private_->md5context);
1016 if(!FLAC__bitbuffer_clear(encoder->private_->frame)) {
1017 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1018 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1020 if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1021 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1022 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1024 if(!write_bitbuffer_(encoder, 0)) {
1025 /* the above function sets the state for us in case of an error */
1026 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1030 * Now that the STREAMINFO block is written, we can init this to an
1031 * absurdly-high value...
1033 encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1034 /* ... and clear this to 0 */
1035 encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1038 * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1039 * if not, we will write an empty one (FLAC__add_metadata_block()
1040 * automatically supplies the vendor string).
1042 * WATCHOUT: libOggFLAC depends on us to write this block after the
1043 * STREAMINFO since that's what the mapping requires. (In the case
1044 * that metadata_has_vorbis_comment is true it will have already
1045 * insured that the metadata list is properly ordered.)
1047 if(!metadata_has_vorbis_comment) {
1048 FLAC__StreamMetadata vorbis_comment;
1049 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1050 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1051 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1052 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1053 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1054 vorbis_comment.data.vorbis_comment.num_comments = 0;
1055 vorbis_comment.data.vorbis_comment.comments = 0;
1056 if(!FLAC__bitbuffer_clear(encoder->private_->frame)) {
1057 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1058 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1060 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1061 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1062 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1064 if(!write_bitbuffer_(encoder, 0)) {
1065 /* the above function sets the state for us in case of an error */
1066 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1071 * write the user's metadata blocks
1073 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1074 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1075 if(!FLAC__bitbuffer_clear(encoder->private_->frame)) {
1076 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1077 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1079 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1080 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1081 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1083 if(!write_bitbuffer_(encoder, 0)) {
1084 /* the above function sets the state for us in case of an error */
1085 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1089 /* now that all the metadata is written, we save the stream offset */
1090 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 */
1091 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1092 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1095 if(encoder->protected_->verify)
1096 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1098 return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1101 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data)
1103 FLAC__StreamEncoderInitStatus init_status;
1105 FLAC__ASSERT(0 != encoder);
1106 FLAC__ASSERT(0 != file);
1109 * To make sure that our file does not go unclosed after an error, we
1110 * must assign the FILE pointer before any further error can occur in
1113 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1114 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1116 /* double protection */
1118 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1119 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1123 file = get_binary_stdout_(); /* just to be safe */
1125 encoder->private_->file = file;
1127 encoder->private_->progress_callback = progress_callback;
1128 encoder->private_->bytes_written = 0;
1129 encoder->private_->samples_written = 0;
1130 encoder->private_->frames_written = 0;
1132 init_status = FLAC__stream_encoder_init_stream(encoder, file_write_callback_, file_seek_callback_, file_tell_callback_, /*metadata_callback=*/0, client_data);
1133 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1134 /* the above function sets the state for us in case of an error */
1139 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1141 FLAC__ASSERT(blocksize != 0);
1142 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1148 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data)
1152 FLAC__ASSERT(0 != encoder);
1155 * To make sure that our file does not go unclosed after an error, we
1156 * have to do the same entrance checks here that are later performed
1157 * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1159 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1160 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1162 file = filename? fopen(filename, "w+b") : stdout;
1165 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1166 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1169 return FLAC__stream_encoder_init_FILE(encoder, file, progress_callback, client_data);
1172 FLAC_API void FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1174 FLAC__ASSERT(0 != encoder);
1175 FLAC__ASSERT(0 != encoder->private_);
1176 FLAC__ASSERT(0 != encoder->protected_);
1178 if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1181 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1182 if(encoder->private_->current_sample_number != 0) {
1183 encoder->protected_->blocksize = encoder->private_->current_sample_number;
1184 process_frame_(encoder, true); /* true => is last frame */
1188 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1190 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1191 if(encoder->private_->seek_callback)
1192 update_metadata_(encoder);
1193 if(encoder->private_->metadata_callback)
1194 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1197 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder)
1198 FLAC__stream_decoder_finish(encoder->private_->verify.decoder);
1200 if(0 != encoder->private_->file) {
1201 if(encoder->private_->file != stdout)
1202 fclose(encoder->private_->file);
1203 encoder->private_->file = 0;
1207 set_defaults_(encoder);
1209 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1212 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1214 FLAC__ASSERT(0 != encoder);
1215 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1217 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1218 encoder->protected_->verify = value;
1223 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1225 FLAC__ASSERT(0 != encoder);
1226 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1228 encoder->protected_->streamable_subset = value;
1232 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1234 FLAC__ASSERT(0 != encoder);
1235 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1237 encoder->protected_->do_mid_side_stereo = value;
1241 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1243 FLAC__ASSERT(0 != encoder);
1244 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1246 encoder->protected_->loose_mid_side_stereo = value;
1250 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1252 FLAC__ASSERT(0 != encoder);
1253 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1255 encoder->protected_->channels = value;
1259 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1261 FLAC__ASSERT(0 != encoder);
1262 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1264 encoder->protected_->bits_per_sample = value;
1268 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1270 FLAC__ASSERT(0 != encoder);
1271 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1273 encoder->protected_->sample_rate = value;
1277 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1279 FLAC__ASSERT(0 != encoder);
1280 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1282 encoder->protected_->blocksize = value;
1286 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1288 FLAC__ASSERT(0 != encoder);
1289 FLAC__ASSERT(0 != specification);
1290 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1292 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1293 (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1295 encoder->protected_->num_apodizations = 0;
1297 const char *s = strchr(specification, ';');
1298 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1299 if (n==8 && 0 == strncmp("bartlett" , specification, n))
1300 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1301 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1302 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1303 else if(n==8 && 0 == strncmp("blackman" , specification, n))
1304 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1305 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1306 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1307 else if(n==6 && 0 == strncmp("connes" , specification, n))
1308 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1309 else if(n==7 && 0 == strncmp("flattop" , specification, n))
1310 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1311 else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
1312 FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1313 if (stddev > 0.0 && stddev <= 0.5) {
1314 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1315 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1318 else if(n==7 && 0 == strncmp("hamming" , specification, n))
1319 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1320 else if(n==4 && 0 == strncmp("hann" , specification, n))
1321 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1322 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1323 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1324 else if(n==7 && 0 == strncmp("nuttall" , specification, n))
1325 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1326 else if(n==9 && 0 == strncmp("rectangle" , specification, n))
1327 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1328 else if(n==8 && 0 == strncmp("triangle" , specification, n))
1329 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1330 else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
1331 FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1332 if (p >= 0.0 && p <= 1.0) {
1333 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1334 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1337 else if(n==5 && 0 == strncmp("welch" , specification, n))
1338 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1339 if (encoder->protected_->num_apodizations == 32)
1342 specification = s+1;
1346 if(encoder->protected_->num_apodizations == 0) {
1347 encoder->protected_->num_apodizations = 1;
1348 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1349 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1351 #ifdef WINDOW_DEBUG_OUTPUT
1352 {unsigned n;for(n=0;n<encoder->protected_->num_apodizations;n++)fprintf(stderr,"@@@@@@ parsed apodization[%zu]: %s\n",n,winstr[encoder->protected_->apodizations[n].type]);}
1358 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1360 FLAC__ASSERT(0 != encoder);
1361 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1363 encoder->protected_->max_lpc_order = value;
1367 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1369 FLAC__ASSERT(0 != encoder);
1370 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1372 encoder->protected_->qlp_coeff_precision = value;
1376 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1378 FLAC__ASSERT(0 != encoder);
1379 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1381 encoder->protected_->do_qlp_coeff_prec_search = value;
1385 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1387 FLAC__ASSERT(0 != encoder);
1388 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1391 /*@@@ deprecated: */
1392 encoder->protected_->do_escape_coding = value;
1399 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1401 FLAC__ASSERT(0 != encoder);
1402 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1404 encoder->protected_->do_exhaustive_model_search = value;
1408 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1410 FLAC__ASSERT(0 != encoder);
1411 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1413 encoder->protected_->min_residual_partition_order = value;
1417 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1419 FLAC__ASSERT(0 != encoder);
1420 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1422 encoder->protected_->max_residual_partition_order = value;
1426 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1428 FLAC__ASSERT(0 != encoder);
1429 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1432 /*@@@ deprecated: */
1433 encoder->protected_->rice_parameter_search_dist = value;
1440 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1442 FLAC__ASSERT(0 != encoder);
1443 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1445 encoder->protected_->total_samples_estimate = value;
1449 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1451 FLAC__ASSERT(0 != encoder);
1452 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1454 encoder->protected_->metadata = metadata;
1455 encoder->protected_->num_metadata_blocks = num_blocks;
1456 if(0 != metadata && num_blocks > 0) {
1458 for(i = 0; i < num_blocks; i++) {
1459 if(0 != metadata[i] && metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
1460 encoder->private_->seek_table = &metadata[i]->data.seek_table;
1461 break; /* take only the first one */
1469 * These three functions are not static, but not publically exposed in
1470 * include/FLAC/ either. They are used by the test suite.
1472 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1474 FLAC__ASSERT(0 != encoder);
1475 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1477 encoder->private_->disable_constant_subframes = value;
1481 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1483 FLAC__ASSERT(0 != encoder);
1484 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1486 encoder->private_->disable_fixed_subframes = value;
1490 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1492 FLAC__ASSERT(0 != encoder);
1493 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1495 encoder->private_->disable_verbatim_subframes = value;
1499 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1501 FLAC__ASSERT(0 != encoder);
1502 return encoder->protected_->state;
1505 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1507 FLAC__ASSERT(0 != encoder);
1508 if(encoder->protected_->verify)
1509 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1511 return FLAC__STREAM_DECODER_UNINITIALIZED;
1514 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1516 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1517 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1519 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1522 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)
1524 FLAC__ASSERT(0 != encoder);
1525 if(0 != absolute_sample)
1526 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1527 if(0 != frame_number)
1528 *frame_number = encoder->private_->verify.error_stats.frame_number;
1530 *channel = encoder->private_->verify.error_stats.channel;
1532 *sample = encoder->private_->verify.error_stats.sample;
1534 *expected = encoder->private_->verify.error_stats.expected;
1536 *got = encoder->private_->verify.error_stats.got;
1539 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1541 FLAC__ASSERT(0 != encoder);
1542 return encoder->protected_->verify;
1545 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1547 FLAC__ASSERT(0 != encoder);
1548 return encoder->protected_->streamable_subset;
1551 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1553 FLAC__ASSERT(0 != encoder);
1554 return encoder->protected_->do_mid_side_stereo;
1557 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1559 FLAC__ASSERT(0 != encoder);
1560 return encoder->protected_->loose_mid_side_stereo;
1563 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1565 FLAC__ASSERT(0 != encoder);
1566 return encoder->protected_->channels;
1569 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1571 FLAC__ASSERT(0 != encoder);
1572 return encoder->protected_->bits_per_sample;
1575 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1577 FLAC__ASSERT(0 != encoder);
1578 return encoder->protected_->sample_rate;
1581 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1583 FLAC__ASSERT(0 != encoder);
1584 return encoder->protected_->blocksize;
1587 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1589 FLAC__ASSERT(0 != encoder);
1590 return encoder->protected_->max_lpc_order;
1593 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1595 FLAC__ASSERT(0 != encoder);
1596 return encoder->protected_->qlp_coeff_precision;
1599 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1601 FLAC__ASSERT(0 != encoder);
1602 return encoder->protected_->do_qlp_coeff_prec_search;
1605 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1607 FLAC__ASSERT(0 != encoder);
1608 return encoder->protected_->do_escape_coding;
1611 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1613 FLAC__ASSERT(0 != encoder);
1614 return encoder->protected_->do_exhaustive_model_search;
1617 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1619 FLAC__ASSERT(0 != encoder);
1620 return encoder->protected_->min_residual_partition_order;
1623 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1625 FLAC__ASSERT(0 != encoder);
1626 return encoder->protected_->max_residual_partition_order;
1629 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1631 FLAC__ASSERT(0 != encoder);
1632 return encoder->protected_->rice_parameter_search_dist;
1635 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1637 FLAC__ASSERT(0 != encoder);
1638 return encoder->protected_->total_samples_estimate;
1641 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1643 unsigned i, j, channel;
1644 FLAC__int32 x, mid, side;
1645 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1647 FLAC__ASSERT(0 != encoder);
1648 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1652 * we have several flavors of the same basic loop, optimized for
1653 * different conditions:
1655 if(encoder->protected_->max_lpc_order > 0) {
1656 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1658 * stereo coding: unroll channel loop
1659 * with LPC: calculate floating point version of signal
1662 if(encoder->protected_->verify)
1663 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1665 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1666 x = mid = side = buffer[0][j];
1667 encoder->private_->integer_signal[0][i] = x;
1668 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1669 encoder->private_->real_signal[0][i] = (FLAC__real)x;
1672 encoder->private_->integer_signal[1][i] = x;
1673 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1674 encoder->private_->real_signal[1][i] = (FLAC__real)x;
1678 mid >>= 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
1679 encoder->private_->integer_signal_mid_side[1][i] = side;
1680 encoder->private_->integer_signal_mid_side[0][i] = mid;
1681 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1682 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
1683 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
1685 encoder->private_->current_sample_number++;
1687 if(i == blocksize) {
1688 if(!process_frame_(encoder, false)) /* false => not last frame */
1691 } while(j < samples);
1695 * independent channel coding: buffer each channel in inner loop
1696 * with LPC: calculate floating point version of signal
1699 if(encoder->protected_->verify)
1700 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1702 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1703 for(channel = 0; channel < channels; channel++) {
1704 x = buffer[channel][j];
1705 encoder->private_->integer_signal[channel][i] = x;
1706 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1707 encoder->private_->real_signal[channel][i] = (FLAC__real)x;
1710 encoder->private_->current_sample_number++;
1712 if(i == blocksize) {
1713 if(!process_frame_(encoder, false)) /* false => not last frame */
1716 } while(j < samples);
1720 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1722 * stereo coding: unroll channel loop
1723 * without LPC: no need to calculate floating point version of signal
1726 if(encoder->protected_->verify)
1727 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1729 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1730 encoder->private_->integer_signal[0][i] = mid = side = buffer[0][j];
1732 encoder->private_->integer_signal[1][i] = x;
1735 mid >>= 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
1736 encoder->private_->integer_signal_mid_side[1][i] = side;
1737 encoder->private_->integer_signal_mid_side[0][i] = mid;
1738 encoder->private_->current_sample_number++;
1740 if(i == blocksize) {
1741 if(!process_frame_(encoder, false)) /* false => not last frame */
1744 } while(j < samples);
1748 * independent channel coding: buffer each channel in inner loop
1749 * without LPC: no need to calculate floating point version of signal
1752 if(encoder->protected_->verify)
1753 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1755 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1756 for(channel = 0; channel < channels; channel++)
1757 encoder->private_->integer_signal[channel][i] = buffer[channel][j];
1758 encoder->private_->current_sample_number++;
1760 if(i == blocksize) {
1761 if(!process_frame_(encoder, false)) /* false => not last frame */
1764 } while(j < samples);
1771 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
1773 unsigned i, j, k, channel;
1774 FLAC__int32 x, mid, side;
1775 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1777 FLAC__ASSERT(0 != encoder);
1778 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1782 * we have several flavors of the same basic loop, optimized for
1783 * different conditions:
1785 if(encoder->protected_->max_lpc_order > 0) {
1786 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1788 * stereo coding: unroll channel loop
1789 * with LPC: calculate floating point version of signal
1792 if(encoder->protected_->verify)
1793 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1795 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1796 x = mid = side = buffer[k++];
1797 encoder->private_->integer_signal[0][i] = x;
1798 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1799 encoder->private_->real_signal[0][i] = (FLAC__real)x;
1802 encoder->private_->integer_signal[1][i] = x;
1803 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1804 encoder->private_->real_signal[1][i] = (FLAC__real)x;
1808 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
1809 encoder->private_->integer_signal_mid_side[1][i] = side;
1810 encoder->private_->integer_signal_mid_side[0][i] = mid;
1811 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1812 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
1813 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
1815 encoder->private_->current_sample_number++;
1817 if(i == blocksize) {
1818 if(!process_frame_(encoder, false)) /* false => not last frame */
1821 } while(j < samples);
1825 * independent channel coding: buffer each channel in inner loop
1826 * with LPC: calculate floating point version of signal
1829 if(encoder->protected_->verify)
1830 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1832 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1833 for(channel = 0; channel < channels; channel++) {
1835 encoder->private_->integer_signal[channel][i] = x;
1836 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1837 encoder->private_->real_signal[channel][i] = (FLAC__real)x;
1840 encoder->private_->current_sample_number++;
1842 if(i == blocksize) {
1843 if(!process_frame_(encoder, false)) /* false => not last frame */
1846 } while(j < samples);
1850 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1852 * stereo coding: unroll channel loop
1853 * without LPC: no need to calculate floating point version of signal
1856 if(encoder->protected_->verify)
1857 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1859 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1860 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
1862 encoder->private_->integer_signal[1][i] = x;
1865 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
1866 encoder->private_->integer_signal_mid_side[1][i] = side;
1867 encoder->private_->integer_signal_mid_side[0][i] = mid;
1868 encoder->private_->current_sample_number++;
1870 if(i == blocksize) {
1871 if(!process_frame_(encoder, false)) /* false => not last frame */
1874 } while(j < samples);
1878 * independent channel coding: buffer each channel in inner loop
1879 * without LPC: no need to calculate floating point version of signal
1882 if(encoder->protected_->verify)
1883 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1885 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1886 for(channel = 0; channel < channels; channel++)
1887 encoder->private_->integer_signal[channel][i] = buffer[k++];
1888 encoder->private_->current_sample_number++;
1890 if(i == blocksize) {
1891 if(!process_frame_(encoder, false)) /* false => not last frame */
1894 } while(j < samples);
1901 /***********************************************************************
1903 * Private class methods
1905 ***********************************************************************/
1907 void set_defaults_(FLAC__StreamEncoder *encoder)
1909 FLAC__ASSERT(0 != encoder);
1911 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1912 encoder->protected_->verify = true;
1914 encoder->protected_->verify = false;
1916 encoder->protected_->streamable_subset = true;
1917 encoder->protected_->do_mid_side_stereo = false;
1918 encoder->protected_->loose_mid_side_stereo = false;
1919 encoder->protected_->channels = 2;
1920 encoder->protected_->bits_per_sample = 16;
1921 encoder->protected_->sample_rate = 44100;
1922 encoder->protected_->blocksize = 1152;
1923 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1924 encoder->protected_->num_apodizations = 1;
1925 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1926 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1928 encoder->protected_->max_lpc_order = 0;
1929 encoder->protected_->qlp_coeff_precision = 0;
1930 encoder->protected_->do_qlp_coeff_prec_search = false;
1931 encoder->protected_->do_exhaustive_model_search = false;
1932 encoder->protected_->do_escape_coding = false;
1933 encoder->protected_->min_residual_partition_order = 0;
1934 encoder->protected_->max_residual_partition_order = 0;
1935 encoder->protected_->rice_parameter_search_dist = 0;
1936 encoder->protected_->total_samples_estimate = 0;
1937 encoder->protected_->metadata = 0;
1938 encoder->protected_->num_metadata_blocks = 0;
1940 encoder->private_->seek_table = 0;
1941 encoder->private_->disable_constant_subframes = false;
1942 encoder->private_->disable_fixed_subframes = false;
1943 encoder->private_->disable_verbatim_subframes = false;
1944 encoder->private_->write_callback = 0;
1945 encoder->private_->seek_callback = 0;
1946 encoder->private_->tell_callback = 0;
1947 encoder->private_->metadata_callback = 0;
1948 encoder->private_->progress_callback = 0;
1949 encoder->private_->client_data = 0;
1952 void free_(FLAC__StreamEncoder *encoder)
1954 unsigned i, channel;
1956 FLAC__ASSERT(0 != encoder);
1957 for(i = 0; i < encoder->protected_->channels; i++) {
1958 if(0 != encoder->private_->integer_signal_unaligned[i]) {
1959 free(encoder->private_->integer_signal_unaligned[i]);
1960 encoder->private_->integer_signal_unaligned[i] = 0;
1962 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1963 if(0 != encoder->private_->real_signal_unaligned[i]) {
1964 free(encoder->private_->real_signal_unaligned[i]);
1965 encoder->private_->real_signal_unaligned[i] = 0;
1969 for(i = 0; i < 2; i++) {
1970 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
1971 free(encoder->private_->integer_signal_mid_side_unaligned[i]);
1972 encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
1974 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1975 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
1976 free(encoder->private_->real_signal_mid_side_unaligned[i]);
1977 encoder->private_->real_signal_mid_side_unaligned[i] = 0;
1981 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1982 for(i = 0; i < encoder->protected_->num_apodizations; i++) {
1983 if(0 != encoder->private_->window_unaligned[i]) {
1984 free(encoder->private_->window_unaligned[i]);
1985 encoder->private_->window_unaligned[i] = 0;
1988 if(0 != encoder->private_->windowed_signal_unaligned) {
1989 free(encoder->private_->windowed_signal_unaligned);
1990 encoder->private_->windowed_signal_unaligned = 0;
1993 for(channel = 0; channel < encoder->protected_->channels; channel++) {
1994 for(i = 0; i < 2; i++) {
1995 if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
1996 free(encoder->private_->residual_workspace_unaligned[channel][i]);
1997 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2001 for(channel = 0; channel < 2; channel++) {
2002 for(i = 0; i < 2; i++) {
2003 if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2004 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2005 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2009 if(0 != encoder->private_->abs_residual_unaligned) {
2010 free(encoder->private_->abs_residual_unaligned);
2011 encoder->private_->abs_residual_unaligned = 0;
2013 if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2014 free(encoder->private_->abs_residual_partition_sums_unaligned);
2015 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2017 if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2018 free(encoder->private_->raw_bits_per_partition_unaligned);
2019 encoder->private_->raw_bits_per_partition_unaligned = 0;
2021 if(encoder->protected_->verify) {
2022 for(i = 0; i < encoder->protected_->channels; i++) {
2023 if(0 != encoder->private_->verify.input_fifo.data[i]) {
2024 free(encoder->private_->verify.input_fifo.data[i]);
2025 encoder->private_->verify.input_fifo.data[i] = 0;
2029 FLAC__bitbuffer_free(encoder->private_->frame);
2032 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_size)
2035 unsigned i, channel;
2037 FLAC__ASSERT(new_size > 0);
2038 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2039 FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2041 /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2042 if(new_size <= encoder->private_->input_capacity)
2047 /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
2048 * requires that the input arrays (in our case the integer signals)
2049 * have a buffer of up to 3 zeroes in front (at negative indices) for
2050 * alignment purposes; we use 4 to keep the data well-aligned.
2053 for(i = 0; ok && i < encoder->protected_->channels; i++) {
2054 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size+4, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2055 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2056 if(encoder->protected_->max_lpc_order > 0)
2057 ok = ok && FLAC__memory_alloc_aligned_real_array(new_size, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2059 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2060 encoder->private_->integer_signal[i] += 4;
2062 for(i = 0; ok && i < 2; i++) {
2063 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size+4, &encoder->private_->integer_signal_mid_side_unaligned[i], &encoder->private_->integer_signal_mid_side[i]);
2064 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2065 if(encoder->protected_->max_lpc_order > 0)
2066 ok = ok && FLAC__memory_alloc_aligned_real_array(new_size, &encoder->private_->real_signal_mid_side_unaligned[i], &encoder->private_->real_signal_mid_side[i]);
2068 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2069 encoder->private_->integer_signal_mid_side[i] += 4;
2071 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2072 if(ok && encoder->protected_->max_lpc_order > 0) {
2073 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2074 ok = ok && FLAC__memory_alloc_aligned_real_array(new_size, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2075 ok = ok && FLAC__memory_alloc_aligned_real_array(new_size, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2078 for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2079 for(i = 0; ok && i < 2; i++) {
2080 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2083 for(channel = 0; ok && channel < 2; channel++) {
2084 for(i = 0; ok && i < 2; i++) {
2085 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size, &encoder->private_->residual_workspace_mid_side_unaligned[channel][i], &encoder->private_->residual_workspace_mid_side[channel][i]);
2088 ok = ok && FLAC__memory_alloc_aligned_uint32_array(new_size, &encoder->private_->abs_residual_unaligned, &encoder->private_->abs_residual);
2089 if(encoder->private_->precompute_partition_sums || encoder->protected_->do_escape_coding) /* we require precompute_partition_sums if do_escape_coding because of their intertwined nature */
2090 ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_size * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2091 if(encoder->protected_->do_escape_coding)
2092 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_size * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2095 encoder->private_->input_capacity = new_size;
2097 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2099 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2100 if(ok && encoder->protected_->max_lpc_order > 0) {
2101 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2102 switch(encoder->protected_->apodizations[i].type) {
2103 case FLAC__APODIZATION_BARTLETT:
2104 FLAC__window_bartlett(encoder->private_->window[i], new_size);
2106 case FLAC__APODIZATION_BARTLETT_HANN:
2107 FLAC__window_bartlett_hann(encoder->private_->window[i], new_size);
2109 case FLAC__APODIZATION_BLACKMAN:
2110 FLAC__window_blackman(encoder->private_->window[i], new_size);
2112 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2113 FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_size);
2115 case FLAC__APODIZATION_CONNES:
2116 FLAC__window_connes(encoder->private_->window[i], new_size);
2118 case FLAC__APODIZATION_FLATTOP:
2119 FLAC__window_flattop(encoder->private_->window[i], new_size);
2121 case FLAC__APODIZATION_GAUSS:
2122 FLAC__window_gauss(encoder->private_->window[i], new_size, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2124 case FLAC__APODIZATION_HAMMING:
2125 FLAC__window_hamming(encoder->private_->window[i], new_size);
2127 case FLAC__APODIZATION_HANN:
2128 FLAC__window_hann(encoder->private_->window[i], new_size);
2130 case FLAC__APODIZATION_KAISER_BESSEL:
2131 FLAC__window_kaiser_bessel(encoder->private_->window[i], new_size);
2133 case FLAC__APODIZATION_NUTTALL:
2134 FLAC__window_nuttall(encoder->private_->window[i], new_size);
2136 case FLAC__APODIZATION_RECTANGLE:
2137 FLAC__window_rectangle(encoder->private_->window[i], new_size);
2139 case FLAC__APODIZATION_TRIANGLE:
2140 FLAC__window_triangle(encoder->private_->window[i], new_size);
2142 case FLAC__APODIZATION_TUKEY:
2143 FLAC__window_tukey(encoder->private_->window[i], new_size, encoder->protected_->apodizations[i].parameters.tukey.p);
2145 case FLAC__APODIZATION_WELCH:
2146 FLAC__window_welch(encoder->private_->window[i], new_size);
2150 /* double protection */
2151 FLAC__window_hann(encoder->private_->window[i], new_size);
2161 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples)
2163 const FLAC__byte *buffer;
2166 FLAC__ASSERT(FLAC__bitbuffer_is_byte_aligned(encoder->private_->frame));
2168 FLAC__bitbuffer_get_buffer(encoder->private_->frame, &buffer, &bytes);
2170 if(encoder->protected_->verify) {
2171 encoder->private_->verify.output.data = buffer;
2172 encoder->private_->verify.output.bytes = bytes;
2173 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2174 encoder->private_->verify.needs_magic_hack = true;
2177 if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2178 FLAC__bitbuffer_release_buffer(encoder->private_->frame);
2179 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2180 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2186 if(write_frame_(encoder, buffer, bytes, samples) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2187 FLAC__bitbuffer_release_buffer(encoder->private_->frame);
2188 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2192 FLAC__bitbuffer_release_buffer(encoder->private_->frame);
2195 encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2196 encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2202 FLAC__StreamEncoderWriteStatus write_frame_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples)
2204 FLAC__StreamEncoderWriteStatus status;
2205 FLAC__uint64 output_position = 0;
2207 /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2208 if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2209 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2210 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2214 * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2217 FLAC__MetadataType type = (buffer[0] & 0x7f);
2218 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2219 encoder->protected_->streaminfo_offset = output_position;
2220 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2221 encoder->protected_->seektable_offset = output_position;
2225 * Mark the current seek point if hit (if audio_offset == 0 that
2226 * means we're still writing metadata and haven't hit the first
2229 if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2230 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2231 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2232 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2233 FLAC__uint64 test_sample;
2235 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2236 test_sample = encoder->private_->seek_table->points[i].sample_number;
2237 if(test_sample > frame_last_sample) {
2240 else if(test_sample >= frame_first_sample) {
2241 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2242 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2243 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2244 encoder->private_->first_seekpoint_to_check++;
2245 /* DO NOT: "break;" and here's why:
2246 * The seektable template may contain more than one target
2247 * sample for any given frame; we will keep looping, generating
2248 * duplicate seekpoints for them, and we'll clean it up later,
2249 * just before writing the seektable back to the metadata.
2253 encoder->private_->first_seekpoint_to_check++;
2258 status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2260 if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2261 encoder->private_->bytes_written += bytes;
2262 encoder->private_->samples_written += samples;
2263 /* we keep a high watermark on the number of frames written because
2264 * when the encoder goes back to write metadata, 'current_frame'
2265 * will drop back to 0.
2267 encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2270 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2275 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2276 void update_metadata_(const FLAC__StreamEncoder *encoder)
2278 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2279 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2280 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2281 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2282 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2283 const unsigned bps = metadata->data.stream_info.bits_per_sample;
2284 FLAC__StreamEncoderSeekStatus seek_status;
2286 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2288 /* All this is based on intimate knowledge of the stream header
2289 * layout, but a change to the header format that would break this
2290 * would also break all streams encoded in the previous format.
2294 * Write MD5 signature
2297 const unsigned md5_offset =
2298 FLAC__STREAM_METADATA_HEADER_LENGTH +
2300 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2301 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2302 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2303 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2304 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2305 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2306 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2307 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2310 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2311 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2312 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2315 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2316 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2322 * Write total samples
2325 const unsigned total_samples_byte_offset =
2326 FLAC__STREAM_METADATA_HEADER_LENGTH +
2328 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2329 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2330 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2331 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2332 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2333 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2334 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2338 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2339 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2340 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2341 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2342 b[4] = (FLAC__byte)(samples & 0xFF);
2343 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) {
2344 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2345 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2348 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2349 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2355 * Write min/max framesize
2358 const unsigned min_framesize_offset =
2359 FLAC__STREAM_METADATA_HEADER_LENGTH +
2361 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2362 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2365 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2366 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2367 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2368 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2369 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2370 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2371 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) {
2372 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2373 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2376 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2377 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2385 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2388 FLAC__format_seektable_sort(encoder->private_->seek_table);
2390 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2392 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) {
2393 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2394 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2398 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2401 xx = encoder->private_->seek_table->points[i].sample_number;
2402 b[7] = (FLAC__byte)xx; xx >>= 8;
2403 b[6] = (FLAC__byte)xx; xx >>= 8;
2404 b[5] = (FLAC__byte)xx; xx >>= 8;
2405 b[4] = (FLAC__byte)xx; xx >>= 8;
2406 b[3] = (FLAC__byte)xx; xx >>= 8;
2407 b[2] = (FLAC__byte)xx; xx >>= 8;
2408 b[1] = (FLAC__byte)xx; xx >>= 8;
2409 b[0] = (FLAC__byte)xx; xx >>= 8;
2410 xx = encoder->private_->seek_table->points[i].stream_offset;
2411 b[15] = (FLAC__byte)xx; xx >>= 8;
2412 b[14] = (FLAC__byte)xx; xx >>= 8;
2413 b[13] = (FLAC__byte)xx; xx >>= 8;
2414 b[12] = (FLAC__byte)xx; xx >>= 8;
2415 b[11] = (FLAC__byte)xx; xx >>= 8;
2416 b[10] = (FLAC__byte)xx; xx >>= 8;
2417 b[9] = (FLAC__byte)xx; xx >>= 8;
2418 b[8] = (FLAC__byte)xx; xx >>= 8;
2419 x = encoder->private_->seek_table->points[i].frame_samples;
2420 b[17] = (FLAC__byte)x; x >>= 8;
2421 b[16] = (FLAC__byte)x; x >>= 8;
2422 if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2423 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2430 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame)
2432 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2435 * Accumulate raw signal to the MD5 signature
2437 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)) {
2438 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2443 * Process the frame header and subframes into the frame bitbuffer
2445 if(!process_subframes_(encoder, is_last_frame)) {
2446 /* the above function sets the state for us in case of an error */
2451 * Zero-pad the frame to a byte_boundary
2453 if(!FLAC__bitbuffer_zero_pad_to_byte_boundary(encoder->private_->frame)) {
2454 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2459 * CRC-16 the whole thing
2461 FLAC__ASSERT(FLAC__bitbuffer_is_byte_aligned(encoder->private_->frame));
2462 FLAC__bitbuffer_write_raw_uint32(encoder->private_->frame, FLAC__bitbuffer_get_write_crc16(encoder->private_->frame), FLAC__FRAME_FOOTER_CRC_LEN);
2467 if(!write_bitbuffer_(encoder, encoder->protected_->blocksize)) {
2468 /* the above function sets the state for us in case of an error */
2473 * Get ready for the next frame
2475 encoder->private_->current_sample_number = 0;
2476 encoder->private_->current_frame_number++;
2477 encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
2482 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame)
2484 FLAC__FrameHeader frame_header;
2485 unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
2486 FLAC__bool do_independent, do_mid_side, precompute_partition_sums;
2489 * Calculate the min,max Rice partition orders
2492 max_partition_order = 0;
2495 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
2496 max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
2498 min_partition_order = min(min_partition_order, max_partition_order);
2500 precompute_partition_sums = encoder->private_->precompute_partition_sums && ((max_partition_order > min_partition_order) || encoder->protected_->do_escape_coding);
2505 if(!FLAC__bitbuffer_clear(encoder->private_->frame)) {
2506 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2509 frame_header.blocksize = encoder->protected_->blocksize;
2510 frame_header.sample_rate = encoder->protected_->sample_rate;
2511 frame_header.channels = encoder->protected_->channels;
2512 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
2513 frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
2514 frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2515 frame_header.number.frame_number = encoder->private_->current_frame_number;
2518 * Figure out what channel assignments to try
2520 if(encoder->protected_->do_mid_side_stereo) {
2521 if(encoder->protected_->loose_mid_side_stereo) {
2522 if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
2523 do_independent = true;
2527 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
2528 do_mid_side = !do_independent;
2532 do_independent = true;
2537 do_independent = true;
2538 do_mid_side = false;
2541 FLAC__ASSERT(do_independent || do_mid_side);
2544 * Check for wasted bits; set effective bps for each subframe
2546 if(do_independent) {
2547 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2548 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
2549 encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
2550 encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
2554 FLAC__ASSERT(encoder->protected_->channels == 2);
2555 for(channel = 0; channel < 2; channel++) {
2556 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
2557 encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
2558 encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
2563 * First do a normal encoding pass of each independent channel
2565 if(do_independent) {
2566 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2570 min_partition_order,
2571 max_partition_order,
2572 precompute_partition_sums,
2574 encoder->private_->subframe_bps[channel],
2575 encoder->private_->integer_signal[channel],
2576 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2577 encoder->private_->real_signal[channel],
2579 encoder->private_->subframe_workspace_ptr[channel],
2580 encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
2581 encoder->private_->residual_workspace[channel],
2582 encoder->private_->best_subframe+channel,
2583 encoder->private_->best_subframe_bits+channel
2584 #ifdef WINDOW_DEBUG_OUTPUT
2594 * Now do mid and side channels if requested
2597 FLAC__ASSERT(encoder->protected_->channels == 2);
2599 for(channel = 0; channel < 2; channel++) {
2603 min_partition_order,
2604 max_partition_order,
2605 precompute_partition_sums,
2607 encoder->private_->subframe_bps_mid_side[channel],
2608 encoder->private_->integer_signal_mid_side[channel],
2609 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2610 encoder->private_->real_signal_mid_side[channel],
2612 encoder->private_->subframe_workspace_ptr_mid_side[channel],
2613 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
2614 encoder->private_->residual_workspace_mid_side[channel],
2615 encoder->private_->best_subframe_mid_side+channel,
2616 encoder->private_->best_subframe_bits_mid_side+channel
2617 #ifdef WINDOW_DEBUG_OUTPUT
2627 * Compose the frame bitbuffer
2630 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
2631 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
2632 FLAC__ChannelAssignment channel_assignment;
2633 #ifdef WINDOW_DEBUG_OUTPUT
2634 unsigned left_bits = 0, right_bits = 0;
2637 FLAC__ASSERT(encoder->protected_->channels == 2);
2639 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
2640 channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
2643 unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
2645 FLAC__ChannelAssignment ca;
2647 FLAC__ASSERT(do_independent && do_mid_side);
2649 /* We have to figure out which channel assignent results in the smallest frame */
2650 bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
2651 bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
2652 bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
2653 bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
2655 for(channel_assignment = (FLAC__ChannelAssignment)0, min_bits = bits[0], ca = (FLAC__ChannelAssignment)1; (int)ca <= 3; ca = (FLAC__ChannelAssignment)((int)ca + 1)) {
2656 if(bits[ca] < min_bits) {
2657 min_bits = bits[ca];
2658 channel_assignment = ca;
2663 frame_header.channel_assignment = channel_assignment;
2665 if(!FLAC__frame_add_header(&frame_header, encoder->protected_->streamable_subset, encoder->private_->frame)) {
2666 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
2670 switch(channel_assignment) {
2671 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2672 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
2673 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
2674 #ifdef WINDOW_DEBUG_OUTPUT
2675 left_bits = encoder->private_->best_subframe_bits [0];
2676 right_bits = encoder->private_->best_subframe_bits [1];
2679 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2680 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
2681 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
2682 #ifdef WINDOW_DEBUG_OUTPUT
2683 left_bits = encoder->private_->best_subframe_bits [0];
2684 right_bits = encoder->private_->best_subframe_bits_mid_side [1];
2687 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2688 left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
2689 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
2690 #ifdef WINDOW_DEBUG_OUTPUT
2691 left_bits = encoder->private_->best_subframe_bits_mid_side [1];
2692 right_bits = encoder->private_->best_subframe_bits [1];
2695 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2696 left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
2697 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
2698 #ifdef WINDOW_DEBUG_OUTPUT
2699 left_bits = encoder->private_->best_subframe_bits_mid_side [0];
2700 right_bits = encoder->private_->best_subframe_bits_mid_side [1];
2707 switch(channel_assignment) {
2708 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2709 left_bps = encoder->private_->subframe_bps [0];
2710 right_bps = encoder->private_->subframe_bps [1];
2712 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2713 left_bps = encoder->private_->subframe_bps [0];
2714 right_bps = encoder->private_->subframe_bps_mid_side[1];
2716 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2717 left_bps = encoder->private_->subframe_bps_mid_side[1];
2718 right_bps = encoder->private_->subframe_bps [1];
2720 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2721 left_bps = encoder->private_->subframe_bps_mid_side[0];
2722 right_bps = encoder->private_->subframe_bps_mid_side[1];
2728 /* note that encoder_add_subframe_ sets the state for us in case of an error */
2729 #ifdef WINDOW_DEBUG_OUTPUT
2730 if(!add_subframe_(encoder, &frame_header, left_bps , left_subframe , encoder->private_->frame, left_bits))
2732 if(!add_subframe_(encoder, &frame_header, right_bps, right_subframe, encoder->private_->frame, right_bits))
2735 if(!add_subframe_(encoder, &frame_header, left_bps , left_subframe , encoder->private_->frame))
2737 if(!add_subframe_(encoder, &frame_header, right_bps, right_subframe, encoder->private_->frame))
2742 if(!FLAC__frame_add_header(&frame_header, encoder->protected_->streamable_subset, encoder->private_->frame)) {
2743 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
2747 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2748 #ifdef WINDOW_DEBUG_OUTPUT
2749 if(!add_subframe_(encoder, &frame_header, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame, encoder->private_->best_subframe_bits[channel]))
2751 if(!add_subframe_(encoder, &frame_header, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame))
2754 /* the above function sets the state for us in case of an error */
2760 if(encoder->protected_->loose_mid_side_stereo) {
2761 encoder->private_->loose_mid_side_stereo_frame_count++;
2762 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
2763 encoder->private_->loose_mid_side_stereo_frame_count = 0;
2766 encoder->private_->last_channel_assignment = frame_header.channel_assignment;
2771 FLAC__bool process_subframe_(
2772 FLAC__StreamEncoder *encoder,
2773 unsigned min_partition_order,
2774 unsigned max_partition_order,
2775 FLAC__bool precompute_partition_sums,
2776 const FLAC__FrameHeader *frame_header,
2777 unsigned subframe_bps,
2778 const FLAC__int32 integer_signal[],
2779 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2780 const FLAC__real real_signal[],
2782 FLAC__Subframe *subframe[2],
2783 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
2784 FLAC__int32 *residual[2],
2785 unsigned *best_subframe,
2787 #ifdef WINDOW_DEBUG_OUTPUT
2788 ,unsigned subframe_number
2792 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2793 FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
2795 FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
2797 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2798 FLAC__double lpc_residual_bits_per_sample;
2799 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 */
2800 FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
2801 unsigned min_lpc_order, max_lpc_order, lpc_order;
2802 unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
2804 unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
2805 unsigned rice_parameter;
2806 unsigned _candidate_bits, _best_bits;
2807 unsigned _best_subframe;
2809 /* verbatim subframe is the baseline against which we measure other compressed subframes */
2811 if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
2812 _best_bits = UINT_MAX;
2814 _best_bits = evaluate_verbatim_subframe_(integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
2816 if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
2817 unsigned signal_is_constant = false;
2818 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);
2819 /* check for constant subframe */
2821 !encoder->private_->disable_constant_subframes &&
2822 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2823 fixed_residual_bits_per_sample[1] == 0.0
2825 fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
2828 /* the above means it's possible all samples are the same value; now double-check it: */
2830 signal_is_constant = true;
2831 for(i = 1; i < frame_header->blocksize; i++) {
2832 if(integer_signal[0] != integer_signal[i]) {
2833 signal_is_constant = false;
2838 if(signal_is_constant) {
2839 _candidate_bits = evaluate_constant_subframe_(integer_signal[0], subframe_bps, subframe[!_best_subframe]);
2840 if(_candidate_bits < _best_bits) {
2841 _best_subframe = !_best_subframe;
2842 _best_bits = _candidate_bits;
2846 if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
2848 if(encoder->protected_->do_exhaustive_model_search) {
2849 min_fixed_order = 0;
2850 max_fixed_order = FLAC__MAX_FIXED_ORDER;
2853 min_fixed_order = max_fixed_order = guess_fixed_order;
2855 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
2856 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2857 if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
2858 continue; /* don't even try */
2859 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 */
2861 if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
2862 continue; /* don't even try */
2863 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 */
2865 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
2866 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2867 #ifdef DEBUG_VERBOSE
2868 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2870 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2873 evaluate_fixed_subframe_(
2876 residual[!_best_subframe],
2877 encoder->private_->abs_residual,
2878 encoder->private_->abs_residual_partition_sums,
2879 encoder->private_->raw_bits_per_partition,
2880 frame_header->blocksize,
2884 min_partition_order,
2885 max_partition_order,
2886 precompute_partition_sums,
2887 encoder->protected_->do_escape_coding,
2888 encoder->protected_->rice_parameter_search_dist,
2889 subframe[!_best_subframe],
2890 partitioned_rice_contents[!_best_subframe]
2892 if(_candidate_bits < _best_bits) {
2893 _best_subframe = !_best_subframe;
2894 _best_bits = _candidate_bits;
2899 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2901 if(encoder->protected_->max_lpc_order > 0) {
2902 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
2903 max_lpc_order = frame_header->blocksize-1;
2905 max_lpc_order = encoder->protected_->max_lpc_order;
2906 if(max_lpc_order > 0) {
2908 for (a = 0; a < encoder->protected_->num_apodizations; a++) {
2909 FLAC__lpc_window_data(real_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
2910 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
2911 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
2912 if(autoc[0] != 0.0) {
2913 FLAC__lpc_compute_lp_coefficients(autoc, max_lpc_order, encoder->private_->lp_coeff, lpc_error);
2914 if(encoder->protected_->do_exhaustive_model_search) {
2918 const unsigned guess_lpc_order =
2919 FLAC__lpc_compute_best_order(
2922 frame_header->blocksize,
2924 encoder->protected_->do_qlp_coeff_prec_search?
2925 FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
2926 encoder->protected_->qlp_coeff_precision
2929 min_lpc_order = max_lpc_order = guess_lpc_order;
2931 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
2932 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
2933 if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
2934 continue; /* don't even try */
2935 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
2936 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
2937 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2938 #ifdef DEBUG_VERBOSE
2939 fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2941 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2943 if(encoder->protected_->do_qlp_coeff_prec_search) {
2944 min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
2945 /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
2946 if(subframe_bps <= 17) {
2947 max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
2948 max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
2951 max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
2954 min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
2956 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
2958 evaluate_lpc_subframe_(
2961 residual[!_best_subframe],
2962 encoder->private_->abs_residual,
2963 encoder->private_->abs_residual_partition_sums,
2964 encoder->private_->raw_bits_per_partition,
2965 encoder->private_->lp_coeff[lpc_order-1],
2966 frame_header->blocksize,
2969 qlp_coeff_precision,
2971 min_partition_order,
2972 max_partition_order,
2973 precompute_partition_sums,
2974 encoder->protected_->do_escape_coding,
2975 encoder->protected_->rice_parameter_search_dist,
2976 subframe[!_best_subframe],
2977 partitioned_rice_contents[!_best_subframe]
2978 #ifdef WINDOW_DEBUG_OUTPUT
2979 ,frame_header->number.frame_number
2981 ,encoder->protected_->apodizations[a]
2984 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
2985 if(_candidate_bits < _best_bits) {
2986 _best_subframe = !_best_subframe;
2987 _best_bits = _candidate_bits;
2996 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3000 /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3001 if(_best_bits == UINT_MAX) {
3002 FLAC__ASSERT(_best_subframe == 0);
3003 _best_bits = evaluate_verbatim_subframe_(integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3006 *best_subframe = _best_subframe;
3007 *best_bits = _best_bits;
3012 FLAC__bool add_subframe_(
3013 FLAC__StreamEncoder *encoder,
3014 const FLAC__FrameHeader *frame_header,
3015 unsigned subframe_bps,
3016 const FLAC__Subframe *subframe,
3017 FLAC__BitBuffer *frame
3018 #ifdef WINDOW_DEBUG_OUTPUT
3019 ,unsigned subframe_bits
3023 switch(subframe->type) {
3024 case FLAC__SUBFRAME_TYPE_CONSTANT:
3025 if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3026 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3030 case FLAC__SUBFRAME_TYPE_FIXED:
3031 if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), frame_header->blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3032 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3036 case FLAC__SUBFRAME_TYPE_LPC:
3037 #ifdef WINDOW_DEBUG_OUTPUT
3038 fprintf(stderr, "WIN:\tframe=%u\tsubframe=?\torder=%u\twindow=%s\tbits=%u\n", frame_header->number.frame_number, subframe->data.lpc.order, subframe->data.lpc.window_type, subframe_bits);
3040 if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), frame_header->blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3041 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3045 case FLAC__SUBFRAME_TYPE_VERBATIM:
3046 if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), frame_header->blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3047 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3058 unsigned evaluate_constant_subframe_(
3059 const FLAC__int32 signal,
3060 unsigned subframe_bps,
3061 FLAC__Subframe *subframe
3064 subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3065 subframe->data.constant.value = signal;
3067 return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe_bps;
3070 unsigned evaluate_fixed_subframe_(
3071 FLAC__StreamEncoder *encoder,
3072 const FLAC__int32 signal[],
3073 FLAC__int32 residual[],
3074 FLAC__uint32 abs_residual[],
3075 FLAC__uint64 abs_residual_partition_sums[],
3076 unsigned raw_bits_per_partition[],
3078 unsigned subframe_bps,
3080 unsigned rice_parameter,
3081 unsigned min_partition_order,
3082 unsigned max_partition_order,
3083 FLAC__bool precompute_partition_sums,
3084 FLAC__bool do_escape_coding,
3085 unsigned rice_parameter_search_dist,
3086 FLAC__Subframe *subframe,
3087 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3090 unsigned i, residual_bits;
3091 const unsigned residual_samples = blocksize - order;
3093 FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3095 subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3097 subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3098 subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3099 subframe->data.fixed.residual = residual;
3102 find_best_partition_order_(
3106 abs_residual_partition_sums,
3107 raw_bits_per_partition,
3111 min_partition_order,
3112 max_partition_order,
3113 precompute_partition_sums,
3115 rice_parameter_search_dist,
3116 &subframe->data.fixed.entropy_coding_method.data.partitioned_rice
3119 subframe->data.fixed.order = order;
3120 for(i = 0; i < order; i++)
3121 subframe->data.fixed.warmup[i] = signal[i];
3123 return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (order * subframe_bps) + residual_bits;
3126 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3127 unsigned evaluate_lpc_subframe_(
3128 FLAC__StreamEncoder *encoder,
3129 const FLAC__int32 signal[],
3130 FLAC__int32 residual[],
3131 FLAC__uint32 abs_residual[],
3132 FLAC__uint64 abs_residual_partition_sums[],
3133 unsigned raw_bits_per_partition[],
3134 const FLAC__real lp_coeff[],
3136 unsigned subframe_bps,
3138 unsigned qlp_coeff_precision,
3139 unsigned rice_parameter,
3140 unsigned min_partition_order,
3141 unsigned max_partition_order,
3142 FLAC__bool precompute_partition_sums,
3143 FLAC__bool do_escape_coding,
3144 unsigned rice_parameter_search_dist,
3145 FLAC__Subframe *subframe,
3146 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3147 #ifdef WINDOW_DEBUG_OUTPUT
3148 ,unsigned frame_number
3149 ,unsigned subframe_number
3150 ,FLAC__ApodizationSpecification aspec
3154 FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
3155 unsigned i, residual_bits;
3156 int quantization, ret;
3157 const unsigned residual_samples = blocksize - order;
3159 /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3160 if(subframe_bps <= 16) {
3161 FLAC__ASSERT(order > 0);
3162 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3163 qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3166 #ifdef WINDOW_DEBUG_OUTPUT
3167 if (aspec.type == FLAC__APODIZATION_GAUSS)
3168 snprintf(subframe->data.lpc.window_type, sizeof subframe->data.lpc.window_type, "%s(%0.5f)", winstr[aspec.type], aspec.parameters.gauss.stddev);
3169 else if (aspec.type == FLAC__APODIZATION_TUKEY)
3170 snprintf(subframe->data.lpc.window_type, sizeof subframe->data.lpc.window_type, "%s(%0.5f)", winstr[aspec.type], aspec.parameters.tukey.p);
3172 strncpy(subframe->data.lpc.window_type, winstr[aspec.type], sizeof subframe->data.lpc.window_type);
3175 ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3177 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3179 if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3180 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3181 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3183 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3185 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3187 subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3189 subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3190 subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3191 subframe->data.lpc.residual = residual;
3194 find_best_partition_order_(
3198 abs_residual_partition_sums,
3199 raw_bits_per_partition,
3203 min_partition_order,
3204 max_partition_order,
3205 precompute_partition_sums,
3207 rice_parameter_search_dist,
3208 &subframe->data.fixed.entropy_coding_method.data.partitioned_rice
3211 subframe->data.lpc.order = order;
3212 subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3213 subframe->data.lpc.quantization_level = quantization;
3214 memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3215 for(i = 0; i < order; i++)
3216 subframe->data.lpc.warmup[i] = signal[i];
3218 #ifdef WINDOW_DEBUG_OUTPUT
3219 fprintf(stderr, "SWIN:\tframe=%u\tsubframe=%u\torder=%u\twindow=%s\tbits=%u\n", frame_number, subframe_number, order, subframe->data.lpc.window_type, FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits);
3221 return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits;
3225 unsigned evaluate_verbatim_subframe_(
3226 const FLAC__int32 signal[],
3228 unsigned subframe_bps,
3229 FLAC__Subframe *subframe
3232 subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3234 subframe->data.verbatim.data = signal;
3236 return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (blocksize * subframe_bps);
3239 unsigned find_best_partition_order_(
3240 FLAC__StreamEncoderPrivate *private_,
3241 const FLAC__int32 residual[],
3242 FLAC__uint32 abs_residual[],
3243 FLAC__uint64 abs_residual_partition_sums[],
3244 unsigned raw_bits_per_partition[],
3245 unsigned residual_samples,
3246 unsigned predictor_order,
3247 unsigned rice_parameter,
3248 unsigned min_partition_order,
3249 unsigned max_partition_order,
3250 FLAC__bool precompute_partition_sums,
3251 FLAC__bool do_escape_coding,
3252 unsigned rice_parameter_search_dist,
3253 FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
3257 unsigned residual_bits, best_residual_bits = 0;
3258 unsigned residual_sample;
3259 unsigned best_parameters_index = 0;
3260 const unsigned blocksize = residual_samples + predictor_order;
3262 /* compute abs(residual) for use later */
3263 for(residual_sample = 0; residual_sample < residual_samples; residual_sample++) {
3264 r = residual[residual_sample];
3265 abs_residual[residual_sample] = (FLAC__uint32)(r<0? -r : r);
3268 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3269 min_partition_order = min(min_partition_order, max_partition_order);
3271 if(precompute_partition_sums) {
3272 int partition_order;
3275 precompute_partition_info_sums_(abs_residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order);
3277 if(do_escape_coding)
3278 precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3280 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3281 #ifdef DONT_ESTIMATE_RICE_BITS
3283 set_partitioned_rice_with_precompute_(
3285 abs_residual_partition_sums+sum,
3286 raw_bits_per_partition+sum,
3290 rice_parameter_search_dist,
3291 (unsigned)partition_order,
3293 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3299 set_partitioned_rice_with_precompute_(
3301 abs_residual_partition_sums+sum,
3302 raw_bits_per_partition+sum,
3306 rice_parameter_search_dist,
3307 (unsigned)partition_order,
3309 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3315 FLAC__ASSERT(best_residual_bits != 0);
3318 sum += 1u << partition_order;
3319 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3320 best_residual_bits = residual_bits;
3321 best_parameters_index = !best_parameters_index;
3322 best_partitioned_rice->order = partition_order;
3327 unsigned partition_order;
3328 for(partition_order = min_partition_order; partition_order <= max_partition_order; partition_order++) {
3329 #ifdef DONT_ESTIMATE_RICE_BITS
3331 set_partitioned_rice_(
3337 rice_parameter_search_dist,
3339 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3345 set_partitioned_rice_(
3350 rice_parameter_search_dist,
3352 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3358 FLAC__ASSERT(best_residual_bits != 0);
3361 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3362 best_residual_bits = residual_bits;
3363 best_parameters_index = !best_parameters_index;
3364 best_partitioned_rice->order = partition_order;
3370 * We are allowed to de-const the pointer based on our special knowledge;
3371 * it is const to the outside world.
3374 FLAC__EntropyCodingMethod_PartitionedRiceContents* best_partitioned_rice_contents = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_partitioned_rice->contents;
3375 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(best_partitioned_rice_contents, max(6, best_partitioned_rice->order));
3376 memcpy(best_partitioned_rice_contents->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
3377 memcpy(best_partitioned_rice_contents->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
3380 return best_residual_bits;
3383 void precompute_partition_info_sums_(
3384 const FLAC__uint32 abs_residual[],
3385 FLAC__uint64 abs_residual_partition_sums[],
3386 unsigned residual_samples,
3387 unsigned predictor_order,
3388 unsigned min_partition_order,
3389 unsigned max_partition_order
3392 int partition_order;
3393 unsigned from_partition, to_partition = 0;
3394 const unsigned blocksize = residual_samples + predictor_order;
3396 /* first do max_partition_order */
3397 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3398 FLAC__uint64 abs_residual_partition_sum;
3400 unsigned partition, partition_sample, partition_samples, residual_sample;
3401 const unsigned partitions = 1u << partition_order;
3402 const unsigned default_partition_samples = blocksize >> partition_order;
3404 FLAC__ASSERT(default_partition_samples > predictor_order);
3406 for(partition = residual_sample = 0; partition < partitions; partition++) {
3407 partition_samples = default_partition_samples;
3409 partition_samples -= predictor_order;
3410 abs_residual_partition_sum = 0;
3411 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
3412 abs_r = abs_residual[residual_sample];
3413 abs_residual_partition_sum += abs_r;
3416 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3418 to_partition = partitions;
3422 /* now merge partitions for lower orders */
3423 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
3426 const unsigned partitions = 1u << partition_order;
3427 for(i = 0; i < partitions; i++) {
3428 s = abs_residual_partition_sums[from_partition];
3430 abs_residual_partition_sums[to_partition] = s + abs_residual_partition_sums[from_partition];
3437 void precompute_partition_info_escapes_(
3438 const FLAC__int32 residual[],
3439 unsigned raw_bits_per_partition[],
3440 unsigned residual_samples,
3441 unsigned predictor_order,
3442 unsigned min_partition_order,
3443 unsigned max_partition_order
3446 int partition_order;
3447 unsigned from_partition, to_partition = 0;
3448 const unsigned blocksize = residual_samples + predictor_order;
3450 /* first do max_partition_order */
3451 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3452 FLAC__int32 r, residual_partition_min, residual_partition_max;
3453 unsigned silog2_min, silog2_max;
3454 unsigned partition, partition_sample, partition_samples, residual_sample;
3455 const unsigned partitions = 1u << partition_order;
3456 const unsigned default_partition_samples = blocksize >> partition_order;
3458 FLAC__ASSERT(default_partition_samples > predictor_order);
3460 for(partition = residual_sample = 0; partition < partitions; partition++) {
3461 partition_samples = default_partition_samples;
3463 partition_samples -= predictor_order;
3464 residual_partition_min = residual_partition_max = 0;
3465 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
3466 r = residual[residual_sample];
3467 if(r < residual_partition_min)
3468 residual_partition_min = r;
3469 else if(r > residual_partition_max)
3470 residual_partition_max = r;
3473 silog2_min = FLAC__bitmath_silog2(residual_partition_min);
3474 silog2_max = FLAC__bitmath_silog2(residual_partition_max);
3475 raw_bits_per_partition[partition] = max(silog2_min, silog2_max);
3477 to_partition = partitions;
3478 break; /*@@@@@@ yuck, should remove the 'for' loop instead */
3481 /* now merge partitions for lower orders */
3482 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
3485 const unsigned partitions = 1u << partition_order;
3486 for(i = 0; i < partitions; i++) {
3487 m = raw_bits_per_partition[from_partition];
3489 raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
3496 #ifdef VARIABLE_RICE_BITS
3497 #undef VARIABLE_RICE_BITS
3499 #ifndef DONT_ESTIMATE_RICE_BITS
3500 #define VARIABLE_RICE_BITS(value, parameter) ((value) >> (parameter))
3503 #ifdef DONT_ESTIMATE_RICE_BITS
3504 FLAC__bool set_partitioned_rice_(
3505 const FLAC__uint32 abs_residual[],
3506 const FLAC__int32 residual[],
3507 const unsigned residual_samples,
3508 const unsigned predictor_order,
3509 const unsigned suggested_rice_parameter,
3510 const unsigned rice_parameter_search_dist,
3511 const unsigned partition_order,
3512 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3516 FLAC__bool set_partitioned_rice_(
3517 const FLAC__uint32 abs_residual[],
3518 const unsigned residual_samples,
3519 const unsigned predictor_order,
3520 const unsigned suggested_rice_parameter,
3521 const unsigned rice_parameter_search_dist,
3522 const unsigned partition_order,
3523 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3528 unsigned rice_parameter, partition_bits;
3529 #ifndef NO_RICE_SEARCH
3530 unsigned best_partition_bits;
3531 unsigned min_rice_parameter, max_rice_parameter, best_rice_parameter = 0;
3533 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
3534 unsigned *parameters;
3536 FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
3538 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
3539 parameters = partitioned_rice_contents->parameters;
3541 if(partition_order == 0) {
3544 #ifndef NO_RICE_SEARCH
3545 if(rice_parameter_search_dist) {
3546 if(suggested_rice_parameter < rice_parameter_search_dist)
3547 min_rice_parameter = 0;
3549 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
3550 max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
3551 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3552 #ifdef DEBUG_VERBOSE
3553 fprintf(stderr, "clipping rice_parameter (%u -> %u) @2\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3555 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3559 min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
3561 best_partition_bits = 0xffffffff;
3562 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3564 #ifdef VARIABLE_RICE_BITS
3565 const unsigned rice_parameter_estimate = rice_parameter-1;
3566 partition_bits = (1+rice_parameter) * residual_samples;
3570 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
3571 for(i = 0; i < residual_samples; i++) {
3572 #ifdef VARIABLE_RICE_BITS
3573 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter_estimate);
3575 partition_bits += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter); /* NOTE: we will need to pass in residual[] in addition to abs_residual[] */
3578 #ifndef NO_RICE_SEARCH
3579 if(partition_bits < best_partition_bits) {
3580 best_rice_parameter = rice_parameter;
3581 best_partition_bits = partition_bits;
3585 parameters[0] = best_rice_parameter;
3586 bits_ += best_partition_bits;
3589 unsigned partition, residual_sample, save_residual_sample, partition_sample;
3590 unsigned partition_samples;
3591 FLAC__uint64 mean, k;
3592 const unsigned partitions = 1u << partition_order;
3593 for(partition = residual_sample = 0; partition < partitions; partition++) {
3594 partition_samples = (residual_samples+predictor_order) >> partition_order;
3595 if(partition == 0) {
3596 if(partition_samples <= predictor_order)
3599 partition_samples -= predictor_order;
3602 save_residual_sample = residual_sample;
3603 for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++)
3604 mean += abs_residual[residual_sample];
3605 residual_sample = save_residual_sample;
3606 /* we are basically calculating the size in bits of the
3607 * average residual magnitude in the partition:
3608 * rice_parameter = floor(log2(mean/partition_samples))
3609 * 'mean' is not a good name for the variable, it is
3610 * actually the sum of magnitudes of all residual values
3611 * in the partition, so the actual mean is
3612 * mean/partition_samples
3614 for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
3616 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3617 #ifdef DEBUG_VERBOSE
3618 fprintf(stderr, "clipping rice_parameter (%u -> %u) @3\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3620 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3623 #ifndef NO_RICE_SEARCH
3624 if(rice_parameter_search_dist) {
3625 if(rice_parameter < rice_parameter_search_dist)
3626 min_rice_parameter = 0;
3628 min_rice_parameter = rice_parameter - rice_parameter_search_dist;
3629 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
3630 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3631 #ifdef DEBUG_VERBOSE
3632 fprintf(stderr, "clipping rice_parameter (%u -> %u) @4\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3634 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3638 min_rice_parameter = max_rice_parameter = rice_parameter;
3640 best_partition_bits = 0xffffffff;
3641 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3643 #ifdef VARIABLE_RICE_BITS
3644 const unsigned rice_parameter_estimate = rice_parameter-1;
3645 partition_bits = (1+rice_parameter) * partition_samples;
3649 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
3650 save_residual_sample = residual_sample;
3651 for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++) {
3652 #ifdef VARIABLE_RICE_BITS
3653 partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter_estimate);
3655 partition_bits += FLAC__bitbuffer_rice_bits(residual[residual_sample], rice_parameter); /* NOTE: we will need to pass in residual[] in addition to abs_residual[] */
3658 #ifndef NO_RICE_SEARCH
3659 if(rice_parameter != max_rice_parameter)
3660 residual_sample = save_residual_sample;
3661 if(partition_bits < best_partition_bits) {
3662 best_rice_parameter = rice_parameter;
3663 best_partition_bits = partition_bits;
3667 parameters[partition] = best_rice_parameter;
3668 bits_ += best_partition_bits;
3676 #ifdef DONT_ESTIMATE_RICE_BITS
3677 FLAC__bool set_partitioned_rice_with_precompute_(
3678 const FLAC__int32 residual[],
3679 const FLAC__uint64 abs_residual_partition_sums[],
3680 const unsigned raw_bits_per_partition[],
3681 const unsigned residual_samples,
3682 const unsigned predictor_order,
3683 const unsigned suggested_rice_parameter,
3684 const unsigned rice_parameter_search_dist,
3685 const unsigned partition_order,
3686 const FLAC__bool search_for_escapes,
3687 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3691 FLAC__bool set_partitioned_rice_with_precompute_(
3692 const FLAC__uint32 abs_residual[],
3693 const FLAC__uint64 abs_residual_partition_sums[],
3694 const unsigned raw_bits_per_partition[],
3695 const unsigned residual_samples,
3696 const unsigned predictor_order,
3697 const unsigned suggested_rice_parameter,
3698 const unsigned rice_parameter_search_dist,
3699 const unsigned partition_order,
3700 const FLAC__bool search_for_escapes,
3701 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3706 unsigned rice_parameter, partition_bits;
3707 #ifndef NO_RICE_SEARCH
3708 unsigned best_partition_bits;
3709 unsigned min_rice_parameter, max_rice_parameter, best_rice_parameter = 0;
3712 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
3713 unsigned *parameters, *raw_bits;
3715 FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
3717 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
3718 parameters = partitioned_rice_contents->parameters;
3719 raw_bits = partitioned_rice_contents->raw_bits;
3721 if(partition_order == 0) {
3724 #ifndef NO_RICE_SEARCH
3725 if(rice_parameter_search_dist) {
3726 if(suggested_rice_parameter < rice_parameter_search_dist)
3727 min_rice_parameter = 0;
3729 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
3730 max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
3731 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3732 #ifdef DEBUG_VERBOSE
3733 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3735 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3739 min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
3741 best_partition_bits = 0xffffffff;
3742 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3744 #ifdef VARIABLE_RICE_BITS
3745 const unsigned rice_parameter_estimate = rice_parameter-1;
3746 partition_bits = (1+rice_parameter) * residual_samples;
3750 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
3751 for(i = 0; i < residual_samples; i++) {
3752 #ifdef VARIABLE_RICE_BITS
3753 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter_estimate);
3755 partition_bits += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
3758 #ifndef NO_RICE_SEARCH
3759 if(partition_bits < best_partition_bits) {
3760 best_rice_parameter = rice_parameter;
3761 best_partition_bits = partition_bits;
3765 if(search_for_escapes) {
3766 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;
3767 if(flat_bits <= best_partition_bits) {
3768 raw_bits[0] = raw_bits_per_partition[0];
3769 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
3770 best_partition_bits = flat_bits;
3773 parameters[0] = best_rice_parameter;
3774 bits_ += best_partition_bits;
3777 unsigned partition, residual_sample, save_residual_sample, partition_sample;
3778 unsigned partition_samples;
3779 FLAC__uint64 mean, k;
3780 const unsigned partitions = 1u << partition_order;
3781 for(partition = residual_sample = 0; partition < partitions; partition++) {
3782 partition_samples = (residual_samples+predictor_order) >> partition_order;
3783 if(partition == 0) {
3784 if(partition_samples <= predictor_order)
3787 partition_samples -= predictor_order;
3789 mean = abs_residual_partition_sums[partition];
3790 /* we are basically calculating the size in bits of the
3791 * average residual magnitude in the partition:
3792 * rice_parameter = floor(log2(mean/partition_samples))
3793 * 'mean' is not a good name for the variable, it is
3794 * actually the sum of magnitudes of all residual values
3795 * in the partition, so the actual mean is
3796 * mean/partition_samples
3798 for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
3800 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3801 #ifdef DEBUG_VERBOSE
3802 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3804 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3807 #ifndef NO_RICE_SEARCH
3808 if(rice_parameter_search_dist) {
3809 if(rice_parameter < rice_parameter_search_dist)
3810 min_rice_parameter = 0;
3812 min_rice_parameter = rice_parameter - rice_parameter_search_dist;
3813 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
3814 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3815 #ifdef DEBUG_VERBOSE
3816 fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3818 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3822 min_rice_parameter = max_rice_parameter = rice_parameter;
3824 best_partition_bits = 0xffffffff;
3825 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3827 #ifdef VARIABLE_RICE_BITS
3828 const unsigned rice_parameter_estimate = rice_parameter-1;
3829 partition_bits = (1+rice_parameter) * partition_samples;
3833 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
3834 save_residual_sample = residual_sample;
3835 for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++) {
3836 #ifdef VARIABLE_RICE_BITS
3837 partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter_estimate);
3839 partition_bits += FLAC__bitbuffer_rice_bits(residual[residual_sample], rice_parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
3842 #ifndef NO_RICE_SEARCH
3843 if(rice_parameter != max_rice_parameter)
3844 residual_sample = save_residual_sample;
3845 if(partition_bits < best_partition_bits) {
3846 best_rice_parameter = rice_parameter;
3847 best_partition_bits = partition_bits;
3851 if(search_for_escapes) {
3852 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;
3853 if(flat_bits <= best_partition_bits) {
3854 raw_bits[partition] = raw_bits_per_partition[partition];
3855 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
3856 best_partition_bits = flat_bits;
3859 parameters[partition] = best_rice_parameter;
3860 bits_ += best_partition_bits;
3868 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
3873 for(i = 0; i < samples && !(x&1); i++)
3880 for(shift = 0; !(x&1); shift++)
3885 for(i = 0; i < samples; i++)
3886 signal[i] >>= shift;
3892 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
3896 for(channel = 0; channel < channels; channel++)
3897 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
3899 fifo->tail += wide_samples;
3901 FLAC__ASSERT(fifo->tail <= fifo->size);
3904 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
3907 unsigned sample, wide_sample;
3908 unsigned tail = fifo->tail;
3910 sample = input_offset * channels;
3911 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
3912 for(channel = 0; channel < channels; channel++)
3913 fifo->data[channel][tail] = input[sample++];
3918 FLAC__ASSERT(fifo->tail <= fifo->size);
3921 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
3923 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
3924 const unsigned encoded_bytes = encoder->private_->verify.output.bytes;
3927 if(encoder->private_->verify.needs_magic_hack) {
3928 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
3929 *bytes = FLAC__STREAM_SYNC_LENGTH;
3930 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
3931 encoder->private_->verify.needs_magic_hack = false;
3934 if(encoded_bytes == 0) {
3936 * If we get here, a FIFO underflow has occurred,
3937 * which means there is a bug somewhere.
3940 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
3942 else if(encoded_bytes < *bytes)
3943 *bytes = encoded_bytes;
3944 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
3945 encoder->private_->verify.output.data += *bytes;
3946 encoder->private_->verify.output.bytes -= *bytes;
3949 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
3952 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
3954 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
3956 const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
3957 const unsigned blocksize = frame->header.blocksize;
3958 const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
3960 for(channel = 0; channel < channels; channel++) {
3961 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
3962 unsigned i, sample = 0;
3963 FLAC__int32 expect = 0, got = 0;
3965 for(i = 0; i < blocksize; i++) {
3966 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
3968 expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
3969 got = (FLAC__int32)buffer[channel][i];
3973 FLAC__ASSERT(i < blocksize);
3974 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
3975 encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
3976 encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
3977 encoder->private_->verify.error_stats.channel = channel;
3978 encoder->private_->verify.error_stats.sample = sample;
3979 encoder->private_->verify.error_stats.expected = expect;
3980 encoder->private_->verify.error_stats.got = got;
3981 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
3982 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
3985 /* dequeue the frame from the fifo */
3986 for(channel = 0; channel < channels; channel++) {
3987 memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail - blocksize);
3989 encoder->private_->verify.input_fifo.tail -= blocksize;
3990 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
3993 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
3995 (void)decoder, (void)metadata, (void)client_data;
3998 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4000 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4001 (void)decoder, (void)status;
4002 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4005 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4009 if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
4010 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4012 return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4015 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4021 offset = ftello(encoder->private_->file);
4024 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4027 *absolute_byte_offset = (FLAC__uint64)offset;
4028 return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4032 #ifdef FLAC__VALGRIND_TESTING
4033 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4035 size_t ret = fwrite(ptr, size, nmemb, stream);
4041 #define local__fwrite fwrite
4044 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
4046 (void)client_data, (void)samples, (void)current_frame;
4048 if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4049 if(0 != encoder->private_->progress_callback && samples > 0)
4050 encoder->private_->progress_callback(encoder, encoder->private_->bytes_written, encoder->private_->samples_written, encoder->private_->frames_written, encoder->private_->total_frames_estimate, encoder->private_->client_data);
4051 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4054 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4058 * This will forcibly set stdout to binary mode (for OSes that require it)
4060 FILE *get_binary_stdout_()
4062 /* if something breaks here it is probably due to the presence or
4063 * absence of an underscore before the identifiers 'setmode',
4064 * 'fileno', and/or 'O_BINARY'; check your system header files.
4066 #if defined _MSC_VER || defined __MINGW32__
4067 _setmode(_fileno(stdout), _O_BINARY);
4068 #elif defined __CYGWIN__
4069 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4070 setmode(_fileno(stdout), _O_BINARY);
4071 #elif defined __EMX__
4072 setmode(fileno(stdout), O_BINARY);