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 #if _MSC_VER <= 1200 /* @@@ [2G limit] */
58 #include "FLAC/assert.h"
59 #include "FLAC/stream_decoder.h"
60 #include "protected/stream_encoder.h"
61 #include "private/bitbuffer.h"
62 #include "private/bitmath.h"
63 #include "private/crc.h"
64 #include "private/cpu.h"
65 #include "private/fixed.h"
66 #include "private/format.h"
67 #include "private/lpc.h"
68 #include "private/md5.h"
69 #include "private/memory.h"
70 #include "private/stream_encoder_framing.h"
71 #include "private/window.h"
76 #define min(x,y) ((x)<(y)?(x):(y))
81 #define max(x,y) ((x)>(y)?(x):(y))
84 FLAC__int32 *data[FLAC__MAX_CHANNELS];
85 unsigned size; /* of each data[] in samples */
90 const FLAC__byte *data;
97 ENCODER_IN_METADATA = 1,
101 /***********************************************************************
103 * Private class method prototypes
105 ***********************************************************************/
107 static void set_defaults_(FLAC__StreamEncoder *encoder);
108 static void free_(FLAC__StreamEncoder *encoder);
109 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_size);
110 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples);
111 static FLAC__StreamEncoderWriteStatus write_frame_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples);
112 static void update_metadata_(const FLAC__StreamEncoder *encoder);
113 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame);
114 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame);
116 static FLAC__bool process_subframe_(
117 FLAC__StreamEncoder *encoder,
118 unsigned min_partition_order,
119 unsigned max_partition_order,
120 FLAC__bool precompute_partition_sums,
121 const FLAC__FrameHeader *frame_header,
122 unsigned subframe_bps,
123 const FLAC__int32 integer_signal[],
124 #ifndef FLAC__INTEGER_ONLY_LIBRARY
125 const FLAC__real real_signal[],
127 FLAC__Subframe *subframe[2],
128 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
129 FLAC__int32 *residual[2],
130 unsigned *best_subframe,
132 #ifdef WINDOW_DEBUG_OUTPUT
133 ,unsigned subframe_number
137 static FLAC__bool add_subframe_(
138 FLAC__StreamEncoder *encoder,
139 const FLAC__FrameHeader *frame_header,
140 unsigned subframe_bps,
141 const FLAC__Subframe *subframe,
142 FLAC__BitBuffer *frame
143 #ifdef WINDOW_DEBUG_OUTPUT
144 ,unsigned subframe_bits
148 static unsigned evaluate_constant_subframe_(
149 const FLAC__int32 signal,
150 unsigned subframe_bps,
151 FLAC__Subframe *subframe
154 static unsigned evaluate_fixed_subframe_(
155 FLAC__StreamEncoder *encoder,
156 const FLAC__int32 signal[],
157 FLAC__int32 residual[],
158 FLAC__uint32 abs_residual[],
159 FLAC__uint64 abs_residual_partition_sums[],
160 unsigned raw_bits_per_partition[],
162 unsigned subframe_bps,
164 unsigned rice_parameter,
165 unsigned min_partition_order,
166 unsigned max_partition_order,
167 FLAC__bool precompute_partition_sums,
168 FLAC__bool do_escape_coding,
169 unsigned rice_parameter_search_dist,
170 FLAC__Subframe *subframe,
171 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
174 #ifndef FLAC__INTEGER_ONLY_LIBRARY
175 static unsigned evaluate_lpc_subframe_(
176 FLAC__StreamEncoder *encoder,
177 const FLAC__int32 signal[],
178 FLAC__int32 residual[],
179 FLAC__uint32 abs_residual[],
180 FLAC__uint64 abs_residual_partition_sums[],
181 unsigned raw_bits_per_partition[],
182 const FLAC__real lp_coeff[],
184 unsigned subframe_bps,
186 unsigned qlp_coeff_precision,
187 unsigned rice_parameter,
188 unsigned min_partition_order,
189 unsigned max_partition_order,
190 FLAC__bool precompute_partition_sums,
191 FLAC__bool do_escape_coding,
192 unsigned rice_parameter_search_dist,
193 FLAC__Subframe *subframe,
194 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
195 #ifdef WINDOW_DEBUG_OUTPUT
196 ,unsigned frame_number
197 ,unsigned subframe_number
198 ,FLAC__ApodizationSpecification aspec
203 static unsigned evaluate_verbatim_subframe_(
204 const FLAC__int32 signal[],
206 unsigned subframe_bps,
207 FLAC__Subframe *subframe
210 static unsigned find_best_partition_order_(
211 struct FLAC__StreamEncoderPrivate *private_,
212 const FLAC__int32 residual[],
213 FLAC__uint32 abs_residual[],
214 FLAC__uint64 abs_residual_partition_sums[],
215 unsigned raw_bits_per_partition[],
216 unsigned residual_samples,
217 unsigned predictor_order,
218 unsigned rice_parameter,
219 unsigned min_partition_order,
220 unsigned max_partition_order,
221 FLAC__bool precompute_partition_sums,
222 FLAC__bool do_escape_coding,
223 unsigned rice_parameter_search_dist,
224 FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
227 static void precompute_partition_info_sums_(
228 const FLAC__uint32 abs_residual[],
229 FLAC__uint64 abs_residual_partition_sums[],
230 unsigned residual_samples,
231 unsigned predictor_order,
232 unsigned min_partition_order,
233 unsigned max_partition_order
236 static void precompute_partition_info_escapes_(
237 const FLAC__int32 residual[],
238 unsigned raw_bits_per_partition[],
239 unsigned residual_samples,
240 unsigned predictor_order,
241 unsigned min_partition_order,
242 unsigned max_partition_order
245 #ifdef DONT_ESTIMATE_RICE_BITS
246 static FLAC__bool set_partitioned_rice_(
247 const FLAC__uint32 abs_residual[],
248 const FLAC__int32 residual[],
249 const unsigned residual_samples,
250 const unsigned predictor_order,
251 const unsigned suggested_rice_parameter,
252 const unsigned rice_parameter_search_dist,
253 const unsigned partition_order,
254 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
258 static FLAC__bool set_partitioned_rice_with_precompute_(
259 const FLAC__int32 residual[],
260 const FLAC__uint64 abs_residual_partition_sums[],
261 const unsigned raw_bits_per_partition[],
262 const unsigned residual_samples,
263 const unsigned predictor_order,
264 const unsigned suggested_rice_parameter,
265 const unsigned rice_parameter_search_dist,
266 const unsigned partition_order,
267 const FLAC__bool search_for_escapes,
268 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
272 static FLAC__bool set_partitioned_rice_(
273 const FLAC__uint32 abs_residual[],
274 const unsigned residual_samples,
275 const unsigned predictor_order,
276 const unsigned suggested_rice_parameter,
277 const unsigned rice_parameter_search_dist,
278 const unsigned partition_order,
279 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
283 static FLAC__bool set_partitioned_rice_with_precompute_(
284 const FLAC__uint32 abs_residual[],
285 const FLAC__uint64 abs_residual_partition_sums[],
286 const unsigned raw_bits_per_partition[],
287 const unsigned residual_samples,
288 const unsigned predictor_order,
289 const unsigned suggested_rice_parameter,
290 const unsigned rice_parameter_search_dist,
291 const unsigned partition_order,
292 const FLAC__bool search_for_escapes,
293 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
298 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
300 /* verify-related routines: */
301 static void append_to_verify_fifo_(
302 verify_input_fifo *fifo,
303 const FLAC__int32 * const input[],
304 unsigned input_offset,
306 unsigned wide_samples
309 static void append_to_verify_fifo_interleaved_(
310 verify_input_fifo *fifo,
311 const FLAC__int32 input[],
312 unsigned input_offset,
314 unsigned wide_samples
317 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
318 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
319 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
320 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
322 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
323 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
324 static FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
325 static FILE *get_binary_stdout_();
327 #ifdef WINDOW_DEBUG_OUTPUT
328 static const char * const winstr[] = {
332 "blackman_harris_4term_92db_sidelobe",
347 /***********************************************************************
351 ***********************************************************************/
353 typedef struct FLAC__StreamEncoderPrivate {
354 unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
355 FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
356 FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
357 #ifndef FLAC__INTEGER_ONLY_LIBRARY
358 FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* the floating-point version of the input signal */
359 FLAC__real *real_signal_mid_side[2]; /* the floating-point version of the mid-side input signal (stereo only) */
360 FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
361 FLAC__real *windowed_signal; /* the real_signal[] * current window[] */
363 unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
364 unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
365 FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
366 FLAC__int32 *residual_workspace_mid_side[2][2];
367 FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
368 FLAC__Subframe subframe_workspace_mid_side[2][2];
369 FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
370 FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
371 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
372 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
373 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
374 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
375 unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index into the above workspaces */
376 unsigned best_subframe_mid_side[2];
377 unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
378 unsigned best_subframe_bits_mid_side[2];
379 FLAC__uint32 *abs_residual; /* workspace where abs(candidate residual) is stored */
380 FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
381 unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
382 FLAC__BitBuffer *frame; /* the current frame being worked on */
383 unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
384 unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
385 FLAC__ChannelAssignment last_channel_assignment;
386 FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
387 FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
388 unsigned current_sample_number;
389 unsigned current_frame_number;
390 struct FLAC__MD5Context md5context;
391 FLAC__CPUInfo cpuinfo;
392 #ifndef FLAC__INTEGER_ONLY_LIBRARY
393 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
395 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
397 #ifndef FLAC__INTEGER_ONLY_LIBRARY
398 void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
399 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[]);
400 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[]);
401 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[]);
403 FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
404 FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
405 FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
406 FLAC__bool precompute_partition_sums; /* our initial guess as to whether precomputing the partitions sums will be a speed improvement */
407 FLAC__bool disable_constant_subframes;
408 FLAC__bool disable_fixed_subframes;
409 FLAC__bool disable_verbatim_subframes;
410 FLAC__StreamEncoderSeekCallback seek_callback;
411 FLAC__StreamEncoderTellCallback tell_callback;
412 FLAC__StreamEncoderWriteCallback write_callback;
413 FLAC__StreamEncoderMetadataCallback metadata_callback;
414 FLAC__StreamEncoderProgressCallback progress_callback;
416 unsigned first_seekpoint_to_check;
417 FILE *file; /* only used when encoding to a file */
418 FLAC__uint64 bytes_written;
419 FLAC__uint64 samples_written;
420 unsigned frames_written;
421 unsigned total_frames_estimate;
422 /* unaligned (original) pointers to allocated data */
423 FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
424 FLAC__int32 *integer_signal_mid_side_unaligned[2];
425 #ifndef FLAC__INTEGER_ONLY_LIBRARY
426 FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS];
427 FLAC__real *real_signal_mid_side_unaligned[2];
428 FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
429 FLAC__real *windowed_signal_unaligned;
431 FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
432 FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
433 FLAC__uint32 *abs_residual_unaligned;
434 FLAC__uint64 *abs_residual_partition_sums_unaligned;
435 unsigned *raw_bits_per_partition_unaligned;
437 * These fields have been moved here from private function local
438 * declarations merely to save stack space during encoding.
440 #ifndef FLAC__INTEGER_ONLY_LIBRARY
441 FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
443 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
445 * The data for the verify section
448 FLAC__StreamDecoder *decoder;
449 EncoderStateHint state_hint;
450 FLAC__bool needs_magic_hack;
451 verify_input_fifo input_fifo;
452 verify_output output;
454 FLAC__uint64 absolute_sample;
455 unsigned frame_number;
458 FLAC__int32 expected;
462 FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
463 } FLAC__StreamEncoderPrivate;
465 /***********************************************************************
467 * Public static class data
469 ***********************************************************************/
471 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
472 "FLAC__STREAM_ENCODER_OK",
473 "FLAC__STREAM_ENCODER_UNINITIALIZED",
474 "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
475 "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
476 "FLAC__STREAM_ENCODER_CLIENT_ERROR",
477 "FLAC__STREAM_ENCODER_IO_ERROR",
478 "FLAC__STREAM_ENCODER_FRAMING_ERROR",
479 "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
482 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
483 "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
484 "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
485 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
486 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
487 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
488 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
489 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
490 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
491 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
492 "FLAC__STREAM_ENCODER_INIT_STATUS_MID_SIDE_CHANNELS_MISMATCH",
493 "FLAC__STREAM_ENCODER_INIT_STATUS_ILLEGAL_MID_SIDE_FORCE",
494 "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
495 "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
496 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
497 "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
500 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
501 "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
502 "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
505 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
506 "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
507 "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
508 "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
511 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
512 "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
513 "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
514 "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
517 /***********************************************************************
519 * Class constructor/destructor
522 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new()
524 FLAC__StreamEncoder *encoder;
527 FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
529 encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
534 encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
535 if(encoder->protected_ == 0) {
540 encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
541 if(encoder->private_ == 0) {
542 free(encoder->protected_);
547 encoder->private_->frame = FLAC__bitbuffer_new();
548 if(encoder->private_->frame == 0) {
549 free(encoder->private_);
550 free(encoder->protected_);
555 encoder->private_->file = 0;
557 set_defaults_(encoder);
559 encoder->private_->is_being_deleted = false;
561 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
562 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
563 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
565 for(i = 0; i < 2; i++) {
566 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
567 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
569 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
570 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
571 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
573 for(i = 0; i < 2; i++) {
574 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
575 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
578 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
579 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
580 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
582 for(i = 0; i < 2; i++) {
583 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
584 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
586 for(i = 0; i < 2; i++)
587 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
589 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
594 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
598 FLAC__ASSERT(0 != encoder);
599 FLAC__ASSERT(0 != encoder->protected_);
600 FLAC__ASSERT(0 != encoder->private_);
601 FLAC__ASSERT(0 != encoder->private_->frame);
603 encoder->private_->is_being_deleted = true;
605 FLAC__stream_encoder_finish(encoder);
607 if(0 != encoder->private_->verify.decoder)
608 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
610 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
611 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
612 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
614 for(i = 0; i < 2; i++) {
615 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
616 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
618 for(i = 0; i < 2; i++)
619 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
621 FLAC__bitbuffer_delete(encoder->private_->frame);
622 free(encoder->private_);
623 free(encoder->protected_);
627 /***********************************************************************
629 * Public class methods
631 ***********************************************************************/
633 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)
636 FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
638 FLAC__ASSERT(0 != encoder);
640 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
641 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
643 if(0 == write_callback || (seek_callback && 0 == tell_callback))
644 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
646 if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
647 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
649 if(encoder->protected_->do_mid_side_stereo && encoder->protected_->channels != 2)
650 return FLAC__STREAM_ENCODER_INIT_STATUS_MID_SIDE_CHANNELS_MISMATCH;
652 if(encoder->protected_->loose_mid_side_stereo && !encoder->protected_->do_mid_side_stereo)
653 return FLAC__STREAM_ENCODER_INIT_STATUS_ILLEGAL_MID_SIDE_FORCE;
655 if(encoder->protected_->bits_per_sample >= 32)
656 encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
658 if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
659 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
661 if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
662 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
664 if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
665 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
667 if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
668 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
670 if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
671 return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
673 if(encoder->protected_->qlp_coeff_precision == 0) {
674 if(encoder->protected_->bits_per_sample < 16) {
675 /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
676 /* @@@ until then we'll make a guess */
677 encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
679 else if(encoder->protected_->bits_per_sample == 16) {
680 if(encoder->protected_->blocksize <= 192)
681 encoder->protected_->qlp_coeff_precision = 7;
682 else if(encoder->protected_->blocksize <= 384)
683 encoder->protected_->qlp_coeff_precision = 8;
684 else if(encoder->protected_->blocksize <= 576)
685 encoder->protected_->qlp_coeff_precision = 9;
686 else if(encoder->protected_->blocksize <= 1152)
687 encoder->protected_->qlp_coeff_precision = 10;
688 else if(encoder->protected_->blocksize <= 2304)
689 encoder->protected_->qlp_coeff_precision = 11;
690 else if(encoder->protected_->blocksize <= 4608)
691 encoder->protected_->qlp_coeff_precision = 12;
693 encoder->protected_->qlp_coeff_precision = 13;
696 if(encoder->protected_->blocksize <= 384)
697 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
698 else if(encoder->protected_->blocksize <= 1152)
699 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
701 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
703 FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
705 else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
706 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
708 if(encoder->protected_->streamable_subset) {
710 encoder->protected_->blocksize != 192 &&
711 encoder->protected_->blocksize != 576 &&
712 encoder->protected_->blocksize != 1152 &&
713 encoder->protected_->blocksize != 2304 &&
714 encoder->protected_->blocksize != 4608 &&
715 encoder->protected_->blocksize != 256 &&
716 encoder->protected_->blocksize != 512 &&
717 encoder->protected_->blocksize != 1024 &&
718 encoder->protected_->blocksize != 2048 &&
719 encoder->protected_->blocksize != 4096 &&
720 encoder->protected_->blocksize != 8192 &&
721 encoder->protected_->blocksize != 16384
723 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
725 encoder->protected_->sample_rate != 8000 &&
726 encoder->protected_->sample_rate != 16000 &&
727 encoder->protected_->sample_rate != 22050 &&
728 encoder->protected_->sample_rate != 24000 &&
729 encoder->protected_->sample_rate != 32000 &&
730 encoder->protected_->sample_rate != 44100 &&
731 encoder->protected_->sample_rate != 48000 &&
732 encoder->protected_->sample_rate != 96000
734 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
736 encoder->protected_->bits_per_sample != 8 &&
737 encoder->protected_->bits_per_sample != 12 &&
738 encoder->protected_->bits_per_sample != 16 &&
739 encoder->protected_->bits_per_sample != 20 &&
740 encoder->protected_->bits_per_sample != 24
742 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
743 if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
744 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
746 encoder->protected_->sample_rate <= 48000 &&
748 encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
749 encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
752 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
756 if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
757 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
758 if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
759 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
761 /* validate metadata */
762 if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
763 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
764 metadata_has_seektable = false;
765 metadata_has_vorbis_comment = false;
766 metadata_picture_has_type1 = false;
767 metadata_picture_has_type2 = false;
768 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
769 const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
770 if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
771 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
772 else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
773 if(metadata_has_seektable) /* only one is allowed */
774 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
775 metadata_has_seektable = true;
776 if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
777 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
779 else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
780 if(metadata_has_vorbis_comment) /* only one is allowed */
781 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
782 metadata_has_vorbis_comment = true;
784 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
785 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
786 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
788 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
789 if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
790 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
791 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
792 if(metadata_picture_has_type1) /* there should only be 1 per stream */
793 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
794 metadata_picture_has_type1 = true;
795 /* standard icon must be 32x32 pixel PNG */
797 m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
799 (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
800 m->data.picture.width != 32 ||
801 m->data.picture.height != 32
804 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
806 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
807 if(metadata_picture_has_type2) /* there should only be 1 per stream */
808 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
809 metadata_picture_has_type2 = true;
814 encoder->private_->input_capacity = 0;
815 for(i = 0; i < encoder->protected_->channels; i++) {
816 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
817 #ifndef FLAC__INTEGER_ONLY_LIBRARY
818 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
821 for(i = 0; i < 2; i++) {
822 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
823 #ifndef FLAC__INTEGER_ONLY_LIBRARY
824 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
827 #ifndef FLAC__INTEGER_ONLY_LIBRARY
828 for(i = 0; i < encoder->protected_->num_apodizations; i++)
829 encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
830 encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
832 for(i = 0; i < encoder->protected_->channels; i++) {
833 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
834 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
835 encoder->private_->best_subframe[i] = 0;
837 for(i = 0; i < 2; i++) {
838 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
839 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
840 encoder->private_->best_subframe_mid_side[i] = 0;
842 encoder->private_->abs_residual_unaligned = encoder->private_->abs_residual = 0;
843 encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
844 encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
845 #ifndef FLAC__INTEGER_ONLY_LIBRARY
846 encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
848 /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
849 /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply÷ by hand */
850 FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
851 FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
852 FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
853 FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
854 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);
856 if(encoder->private_->loose_mid_side_stereo_frames == 0)
857 encoder->private_->loose_mid_side_stereo_frames = 1;
858 encoder->private_->loose_mid_side_stereo_frame_count = 0;
859 encoder->private_->current_sample_number = 0;
860 encoder->private_->current_frame_number = 0;
862 encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
863 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? */
864 encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
867 * get the CPU info and set the function pointers
869 FLAC__cpu_info(&encoder->private_->cpuinfo);
870 /* first default to the non-asm routines */
871 #ifndef FLAC__INTEGER_ONLY_LIBRARY
872 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
874 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
875 #ifndef FLAC__INTEGER_ONLY_LIBRARY
876 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
877 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
878 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
880 /* now override with asm where appropriate */
881 #ifndef FLAC__INTEGER_ONLY_LIBRARY
882 # ifndef FLAC__NO_ASM
883 if(encoder->private_->cpuinfo.use_asm) {
884 # ifdef FLAC__CPU_IA32
885 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
886 # ifdef FLAC__HAS_NASM
888 if(encoder->private_->cpuinfo.data.ia32.sse) {
889 if(encoder->protected_->max_lpc_order < 4)
890 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
891 else if(encoder->protected_->max_lpc_order < 8)
892 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
893 else if(encoder->protected_->max_lpc_order < 12)
894 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
896 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
899 # endif /* FLAC__SSE_OS */
900 if(encoder->private_->cpuinfo.data.ia32._3dnow)
901 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
903 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
904 if(encoder->private_->cpuinfo.data.ia32.mmx) {
905 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
906 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
909 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
910 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
912 if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
913 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
914 # endif /* FLAC__HAS_NASM */
915 # endif /* FLAC__CPU_IA32 */
917 # endif /* !FLAC__NO_ASM */
918 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
919 /* finally override based on wide-ness if necessary */
920 if(encoder->private_->use_wide_by_block) {
921 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
924 /* we require precompute_partition_sums if do_escape_coding because of their intertwined nature */
925 encoder->private_->precompute_partition_sums = (encoder->protected_->max_residual_partition_order > encoder->protected_->min_residual_partition_order) || encoder->protected_->do_escape_coding;
927 /* set state to OK; from here on, errors are fatal and we'll override the state then */
928 encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
930 encoder->private_->write_callback = write_callback;
931 encoder->private_->seek_callback = seek_callback;
932 encoder->private_->tell_callback = tell_callback;
933 encoder->private_->metadata_callback = metadata_callback;
934 encoder->private_->client_data = client_data;
936 if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
937 /* the above function sets the state for us in case of an error */
938 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
941 if(!FLAC__bitbuffer_init(encoder->private_->frame)) {
942 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
943 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
947 * Set up the verify stuff if necessary
949 if(encoder->protected_->verify) {
951 * First, set up the fifo which will hold the
952 * original signal to compare against
954 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize;
955 for(i = 0; i < encoder->protected_->channels; i++) {
956 if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder->private_->verify.input_fifo.size))) {
957 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
958 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
961 encoder->private_->verify.input_fifo.tail = 0;
964 * Now set up a stream decoder for verification
966 encoder->private_->verify.decoder = FLAC__stream_decoder_new();
967 if(0 == encoder->private_->verify.decoder) {
968 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
969 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
972 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) {
973 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
974 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
977 encoder->private_->verify.error_stats.absolute_sample = 0;
978 encoder->private_->verify.error_stats.frame_number = 0;
979 encoder->private_->verify.error_stats.channel = 0;
980 encoder->private_->verify.error_stats.sample = 0;
981 encoder->private_->verify.error_stats.expected = 0;
982 encoder->private_->verify.error_stats.got = 0;
985 * These must be done before we write any metadata, because that
986 * calls the write_callback, which uses these values.
988 encoder->private_->first_seekpoint_to_check = 0;
989 encoder->private_->samples_written = 0;
990 encoder->protected_->streaminfo_offset = 0;
991 encoder->protected_->seektable_offset = 0;
992 encoder->protected_->audio_offset = 0;
995 * write the stream header
997 if(encoder->protected_->verify)
998 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
999 if(!FLAC__bitbuffer_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1000 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1001 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1003 if(!write_bitbuffer_(encoder, 0)) {
1004 /* the above function sets the state for us in case of an error */
1005 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1009 * write the STREAMINFO metadata block
1011 if(encoder->protected_->verify)
1012 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1013 encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1014 encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1015 encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1016 encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1017 encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1018 encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1019 encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1020 encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1021 encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1022 encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1023 encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1024 memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1025 FLAC__MD5Init(&encoder->private_->md5context);
1026 if(!FLAC__bitbuffer_clear(encoder->private_->frame)) {
1027 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1028 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1030 if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1031 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1032 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1034 if(!write_bitbuffer_(encoder, 0)) {
1035 /* the above function sets the state for us in case of an error */
1036 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1040 * Now that the STREAMINFO block is written, we can init this to an
1041 * absurdly-high value...
1043 encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1044 /* ... and clear this to 0 */
1045 encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1048 * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1049 * if not, we will write an empty one (FLAC__add_metadata_block()
1050 * automatically supplies the vendor string).
1052 * WATCHOUT: libOggFLAC depends on us to write this block after the
1053 * STREAMINFO since that's what the mapping requires. (In the case
1054 * that metadata_has_vorbis_comment is true it will have already
1055 * insured that the metadata list is properly ordered.)
1057 if(!metadata_has_vorbis_comment) {
1058 FLAC__StreamMetadata vorbis_comment;
1059 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1060 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1061 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1062 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1063 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1064 vorbis_comment.data.vorbis_comment.num_comments = 0;
1065 vorbis_comment.data.vorbis_comment.comments = 0;
1066 if(!FLAC__bitbuffer_clear(encoder->private_->frame)) {
1067 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1068 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1070 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1071 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1072 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1074 if(!write_bitbuffer_(encoder, 0)) {
1075 /* the above function sets the state for us in case of an error */
1076 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1081 * write the user's metadata blocks
1083 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1084 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1085 if(!FLAC__bitbuffer_clear(encoder->private_->frame)) {
1086 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1087 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1089 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1090 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1091 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1093 if(!write_bitbuffer_(encoder, 0)) {
1094 /* the above function sets the state for us in case of an error */
1095 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1099 /* now that all the metadata is written, we save the stream offset */
1100 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 */
1101 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1102 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1105 if(encoder->protected_->verify)
1106 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1108 return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1111 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data)
1113 FLAC__StreamEncoderInitStatus init_status;
1115 FLAC__ASSERT(0 != encoder);
1116 FLAC__ASSERT(0 != file);
1118 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1119 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1121 /* double protection */
1123 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1124 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1128 * To make sure that our file does not go unclosed after an error, we
1129 * must assign the FILE pointer before any further error can occur in
1133 file = get_binary_stdout_(); /* just to be safe */
1135 encoder->private_->file = file;
1137 encoder->private_->progress_callback = progress_callback;
1138 encoder->private_->bytes_written = 0;
1139 encoder->private_->samples_written = 0;
1140 encoder->private_->frames_written = 0;
1142 init_status = FLAC__stream_encoder_init_stream(encoder, file_write_callback_, file_seek_callback_, file_tell_callback_, /*metadata_callback=*/0, client_data);
1143 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1144 /* the above function sets the state for us in case of an error */
1149 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1151 FLAC__ASSERT(blocksize != 0);
1152 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1158 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data)
1162 FLAC__ASSERT(0 != encoder);
1165 * To make sure that our file does not go unclosed after an error, we
1166 * have to do the same entrance checks here that are later performed
1167 * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1169 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1170 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1172 file = filename? fopen(filename, "w+b") : stdout;
1175 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1176 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1179 return FLAC__stream_encoder_init_FILE(encoder, file, progress_callback, client_data);
1182 FLAC_API void FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1184 FLAC__ASSERT(0 != encoder);
1185 FLAC__ASSERT(0 != encoder->private_);
1186 FLAC__ASSERT(0 != encoder->protected_);
1188 if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1191 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1192 if(encoder->private_->current_sample_number != 0) {
1193 encoder->protected_->blocksize = encoder->private_->current_sample_number;
1194 process_frame_(encoder, true); /* true => is last frame */
1198 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1200 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1201 if(encoder->private_->seek_callback)
1202 update_metadata_(encoder);
1203 if(encoder->private_->metadata_callback)
1204 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1207 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder)
1208 FLAC__stream_decoder_finish(encoder->private_->verify.decoder);
1210 if(0 != encoder->private_->file) {
1211 if(encoder->private_->file != stdout)
1212 fclose(encoder->private_->file);
1213 encoder->private_->file = 0;
1217 set_defaults_(encoder);
1219 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1222 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1224 FLAC__ASSERT(0 != encoder);
1225 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1227 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1228 encoder->protected_->verify = value;
1233 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1235 FLAC__ASSERT(0 != encoder);
1236 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1238 encoder->protected_->streamable_subset = value;
1242 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1244 FLAC__ASSERT(0 != encoder);
1245 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1247 encoder->protected_->do_mid_side_stereo = value;
1251 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1253 FLAC__ASSERT(0 != encoder);
1254 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1256 encoder->protected_->loose_mid_side_stereo = value;
1260 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1262 FLAC__ASSERT(0 != encoder);
1263 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1265 encoder->protected_->channels = value;
1269 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1271 FLAC__ASSERT(0 != encoder);
1272 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1274 encoder->protected_->bits_per_sample = value;
1278 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1280 FLAC__ASSERT(0 != encoder);
1281 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1283 encoder->protected_->sample_rate = value;
1287 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1289 FLAC__ASSERT(0 != encoder);
1290 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1292 encoder->protected_->blocksize = value;
1296 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1298 FLAC__ASSERT(0 != encoder);
1299 FLAC__ASSERT(0 != specification);
1300 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1302 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1303 (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1305 encoder->protected_->num_apodizations = 0;
1307 const char *s = strchr(specification, ';');
1308 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1309 if (n==8 && 0 == strncmp("bartlett" , specification, n))
1310 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1311 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1312 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1313 else if(n==8 && 0 == strncmp("blackman" , specification, n))
1314 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1315 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1316 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1317 else if(n==6 && 0 == strncmp("connes" , specification, n))
1318 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1319 else if(n==7 && 0 == strncmp("flattop" , specification, n))
1320 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1321 else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
1322 FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1323 if (stddev > 0.0 && stddev <= 0.5) {
1324 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1325 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1328 else if(n==7 && 0 == strncmp("hamming" , specification, n))
1329 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1330 else if(n==4 && 0 == strncmp("hann" , specification, n))
1331 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1332 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1333 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1334 else if(n==7 && 0 == strncmp("nuttall" , specification, n))
1335 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1336 else if(n==9 && 0 == strncmp("rectangle" , specification, n))
1337 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1338 else if(n==8 && 0 == strncmp("triangle" , specification, n))
1339 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1340 else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
1341 FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1342 if (p >= 0.0 && p <= 1.0) {
1343 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1344 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1347 else if(n==5 && 0 == strncmp("welch" , specification, n))
1348 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1349 if (encoder->protected_->num_apodizations == 32)
1352 specification = s+1;
1356 if(encoder->protected_->num_apodizations == 0) {
1357 encoder->protected_->num_apodizations = 1;
1358 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1359 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1361 #ifdef WINDOW_DEBUG_OUTPUT
1362 {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]);}
1368 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1370 FLAC__ASSERT(0 != encoder);
1371 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1373 encoder->protected_->max_lpc_order = value;
1377 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1379 FLAC__ASSERT(0 != encoder);
1380 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1382 encoder->protected_->qlp_coeff_precision = value;
1386 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1388 FLAC__ASSERT(0 != encoder);
1389 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1391 encoder->protected_->do_qlp_coeff_prec_search = value;
1395 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1397 FLAC__ASSERT(0 != encoder);
1398 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1401 /*@@@ deprecated: */
1402 encoder->protected_->do_escape_coding = value;
1409 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1411 FLAC__ASSERT(0 != encoder);
1412 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1414 encoder->protected_->do_exhaustive_model_search = value;
1418 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1420 FLAC__ASSERT(0 != encoder);
1421 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1423 encoder->protected_->min_residual_partition_order = value;
1427 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1429 FLAC__ASSERT(0 != encoder);
1430 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1432 encoder->protected_->max_residual_partition_order = value;
1436 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1438 FLAC__ASSERT(0 != encoder);
1439 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1442 /*@@@ deprecated: */
1443 encoder->protected_->rice_parameter_search_dist = value;
1450 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1452 FLAC__ASSERT(0 != encoder);
1453 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1455 encoder->protected_->total_samples_estimate = value;
1459 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1461 FLAC__ASSERT(0 != encoder);
1462 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1464 encoder->protected_->metadata = metadata;
1465 encoder->protected_->num_metadata_blocks = num_blocks;
1466 if(0 != metadata && num_blocks > 0) {
1468 for(i = 0; i < num_blocks; i++) {
1469 if(0 != metadata[i] && metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
1470 encoder->private_->seek_table = &metadata[i]->data.seek_table;
1471 break; /* take only the first one */
1479 * These three functions are not static, but not publically exposed in
1480 * include/FLAC/ either. They are used by the test suite.
1482 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1484 FLAC__ASSERT(0 != encoder);
1485 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1487 encoder->private_->disable_constant_subframes = value;
1491 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1493 FLAC__ASSERT(0 != encoder);
1494 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1496 encoder->private_->disable_fixed_subframes = value;
1500 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1502 FLAC__ASSERT(0 != encoder);
1503 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1505 encoder->private_->disable_verbatim_subframes = value;
1509 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1511 FLAC__ASSERT(0 != encoder);
1512 return encoder->protected_->state;
1515 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1517 FLAC__ASSERT(0 != encoder);
1518 if(encoder->protected_->verify)
1519 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1521 return FLAC__STREAM_DECODER_UNINITIALIZED;
1524 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1526 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1527 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1529 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1532 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)
1534 FLAC__ASSERT(0 != encoder);
1535 if(0 != absolute_sample)
1536 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1537 if(0 != frame_number)
1538 *frame_number = encoder->private_->verify.error_stats.frame_number;
1540 *channel = encoder->private_->verify.error_stats.channel;
1542 *sample = encoder->private_->verify.error_stats.sample;
1544 *expected = encoder->private_->verify.error_stats.expected;
1546 *got = encoder->private_->verify.error_stats.got;
1549 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1551 FLAC__ASSERT(0 != encoder);
1552 return encoder->protected_->verify;
1555 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1557 FLAC__ASSERT(0 != encoder);
1558 return encoder->protected_->streamable_subset;
1561 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1563 FLAC__ASSERT(0 != encoder);
1564 return encoder->protected_->do_mid_side_stereo;
1567 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1569 FLAC__ASSERT(0 != encoder);
1570 return encoder->protected_->loose_mid_side_stereo;
1573 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1575 FLAC__ASSERT(0 != encoder);
1576 return encoder->protected_->channels;
1579 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1581 FLAC__ASSERT(0 != encoder);
1582 return encoder->protected_->bits_per_sample;
1585 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1587 FLAC__ASSERT(0 != encoder);
1588 return encoder->protected_->sample_rate;
1591 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1593 FLAC__ASSERT(0 != encoder);
1594 return encoder->protected_->blocksize;
1597 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1599 FLAC__ASSERT(0 != encoder);
1600 return encoder->protected_->max_lpc_order;
1603 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1605 FLAC__ASSERT(0 != encoder);
1606 return encoder->protected_->qlp_coeff_precision;
1609 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1611 FLAC__ASSERT(0 != encoder);
1612 return encoder->protected_->do_qlp_coeff_prec_search;
1615 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1617 FLAC__ASSERT(0 != encoder);
1618 return encoder->protected_->do_escape_coding;
1621 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1623 FLAC__ASSERT(0 != encoder);
1624 return encoder->protected_->do_exhaustive_model_search;
1627 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1629 FLAC__ASSERT(0 != encoder);
1630 return encoder->protected_->min_residual_partition_order;
1633 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1635 FLAC__ASSERT(0 != encoder);
1636 return encoder->protected_->max_residual_partition_order;
1639 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1641 FLAC__ASSERT(0 != encoder);
1642 return encoder->protected_->rice_parameter_search_dist;
1645 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1647 FLAC__ASSERT(0 != encoder);
1648 return encoder->protected_->total_samples_estimate;
1651 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1653 unsigned i, j, channel;
1654 FLAC__int32 x, mid, side;
1655 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1657 FLAC__ASSERT(0 != encoder);
1658 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1662 * we have several flavors of the same basic loop, optimized for
1663 * different conditions:
1665 if(encoder->protected_->max_lpc_order > 0) {
1666 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1668 * stereo coding: unroll channel loop
1669 * with LPC: calculate floating point version of signal
1672 if(encoder->protected_->verify)
1673 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1675 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1676 x = mid = side = buffer[0][j];
1677 encoder->private_->integer_signal[0][i] = x;
1678 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1679 encoder->private_->real_signal[0][i] = (FLAC__real)x;
1682 encoder->private_->integer_signal[1][i] = x;
1683 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1684 encoder->private_->real_signal[1][i] = (FLAC__real)x;
1688 mid >>= 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
1689 encoder->private_->integer_signal_mid_side[1][i] = side;
1690 encoder->private_->integer_signal_mid_side[0][i] = mid;
1691 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1692 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
1693 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
1695 encoder->private_->current_sample_number++;
1697 if(i == blocksize) {
1698 if(!process_frame_(encoder, false)) /* false => not last frame */
1701 } while(j < samples);
1705 * independent channel coding: buffer each channel in inner loop
1706 * with LPC: calculate floating point version of signal
1709 if(encoder->protected_->verify)
1710 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1712 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1713 for(channel = 0; channel < channels; channel++) {
1714 x = buffer[channel][j];
1715 encoder->private_->integer_signal[channel][i] = x;
1716 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1717 encoder->private_->real_signal[channel][i] = (FLAC__real)x;
1720 encoder->private_->current_sample_number++;
1722 if(i == blocksize) {
1723 if(!process_frame_(encoder, false)) /* false => not last frame */
1726 } while(j < samples);
1730 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1732 * stereo coding: unroll channel loop
1733 * without LPC: no need to calculate floating point version of signal
1736 if(encoder->protected_->verify)
1737 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1739 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1740 encoder->private_->integer_signal[0][i] = mid = side = buffer[0][j];
1742 encoder->private_->integer_signal[1][i] = x;
1745 mid >>= 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
1746 encoder->private_->integer_signal_mid_side[1][i] = side;
1747 encoder->private_->integer_signal_mid_side[0][i] = mid;
1748 encoder->private_->current_sample_number++;
1750 if(i == blocksize) {
1751 if(!process_frame_(encoder, false)) /* false => not last frame */
1754 } while(j < samples);
1758 * independent channel coding: buffer each channel in inner loop
1759 * without LPC: no need to calculate floating point version of signal
1762 if(encoder->protected_->verify)
1763 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1765 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1766 for(channel = 0; channel < channels; channel++)
1767 encoder->private_->integer_signal[channel][i] = buffer[channel][j];
1768 encoder->private_->current_sample_number++;
1770 if(i == blocksize) {
1771 if(!process_frame_(encoder, false)) /* false => not last frame */
1774 } while(j < samples);
1781 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
1783 unsigned i, j, k, channel;
1784 FLAC__int32 x, mid, side;
1785 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1787 FLAC__ASSERT(0 != encoder);
1788 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1792 * we have several flavors of the same basic loop, optimized for
1793 * different conditions:
1795 if(encoder->protected_->max_lpc_order > 0) {
1796 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1798 * stereo coding: unroll channel loop
1799 * with LPC: calculate floating point version of signal
1802 if(encoder->protected_->verify)
1803 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1805 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1806 x = mid = side = buffer[k++];
1807 encoder->private_->integer_signal[0][i] = x;
1808 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1809 encoder->private_->real_signal[0][i] = (FLAC__real)x;
1812 encoder->private_->integer_signal[1][i] = x;
1813 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1814 encoder->private_->real_signal[1][i] = (FLAC__real)x;
1818 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
1819 encoder->private_->integer_signal_mid_side[1][i] = side;
1820 encoder->private_->integer_signal_mid_side[0][i] = mid;
1821 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1822 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
1823 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
1825 encoder->private_->current_sample_number++;
1827 if(i == blocksize) {
1828 if(!process_frame_(encoder, false)) /* false => not last frame */
1831 } while(j < samples);
1835 * independent channel coding: buffer each channel in inner loop
1836 * with LPC: calculate floating point version of signal
1839 if(encoder->protected_->verify)
1840 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1842 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1843 for(channel = 0; channel < channels; channel++) {
1845 encoder->private_->integer_signal[channel][i] = x;
1846 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1847 encoder->private_->real_signal[channel][i] = (FLAC__real)x;
1850 encoder->private_->current_sample_number++;
1852 if(i == blocksize) {
1853 if(!process_frame_(encoder, false)) /* false => not last frame */
1856 } while(j < samples);
1860 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1862 * stereo coding: unroll channel loop
1863 * without LPC: no need to calculate floating point version of signal
1866 if(encoder->protected_->verify)
1867 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1869 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1870 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
1872 encoder->private_->integer_signal[1][i] = x;
1875 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
1876 encoder->private_->integer_signal_mid_side[1][i] = side;
1877 encoder->private_->integer_signal_mid_side[0][i] = mid;
1878 encoder->private_->current_sample_number++;
1880 if(i == blocksize) {
1881 if(!process_frame_(encoder, false)) /* false => not last frame */
1884 } while(j < samples);
1888 * independent channel coding: buffer each channel in inner loop
1889 * without LPC: no need to calculate floating point version of signal
1892 if(encoder->protected_->verify)
1893 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1895 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1896 for(channel = 0; channel < channels; channel++)
1897 encoder->private_->integer_signal[channel][i] = buffer[k++];
1898 encoder->private_->current_sample_number++;
1900 if(i == blocksize) {
1901 if(!process_frame_(encoder, false)) /* false => not last frame */
1904 } while(j < samples);
1911 /***********************************************************************
1913 * Private class methods
1915 ***********************************************************************/
1917 void set_defaults_(FLAC__StreamEncoder *encoder)
1919 FLAC__ASSERT(0 != encoder);
1921 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1922 encoder->protected_->verify = true;
1924 encoder->protected_->verify = false;
1926 encoder->protected_->streamable_subset = true;
1927 encoder->protected_->do_mid_side_stereo = false;
1928 encoder->protected_->loose_mid_side_stereo = false;
1929 encoder->protected_->channels = 2;
1930 encoder->protected_->bits_per_sample = 16;
1931 encoder->protected_->sample_rate = 44100;
1932 encoder->protected_->blocksize = 1152;
1933 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1934 encoder->protected_->num_apodizations = 1;
1935 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1936 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1938 encoder->protected_->max_lpc_order = 0;
1939 encoder->protected_->qlp_coeff_precision = 0;
1940 encoder->protected_->do_qlp_coeff_prec_search = false;
1941 encoder->protected_->do_exhaustive_model_search = false;
1942 encoder->protected_->do_escape_coding = false;
1943 encoder->protected_->min_residual_partition_order = 0;
1944 encoder->protected_->max_residual_partition_order = 0;
1945 encoder->protected_->rice_parameter_search_dist = 0;
1946 encoder->protected_->total_samples_estimate = 0;
1947 encoder->protected_->metadata = 0;
1948 encoder->protected_->num_metadata_blocks = 0;
1950 encoder->private_->seek_table = 0;
1951 encoder->private_->disable_constant_subframes = false;
1952 encoder->private_->disable_fixed_subframes = false;
1953 encoder->private_->disable_verbatim_subframes = false;
1954 encoder->private_->write_callback = 0;
1955 encoder->private_->seek_callback = 0;
1956 encoder->private_->tell_callback = 0;
1957 encoder->private_->metadata_callback = 0;
1958 encoder->private_->progress_callback = 0;
1959 encoder->private_->client_data = 0;
1962 void free_(FLAC__StreamEncoder *encoder)
1964 unsigned i, channel;
1966 FLAC__ASSERT(0 != encoder);
1967 for(i = 0; i < encoder->protected_->channels; i++) {
1968 if(0 != encoder->private_->integer_signal_unaligned[i]) {
1969 free(encoder->private_->integer_signal_unaligned[i]);
1970 encoder->private_->integer_signal_unaligned[i] = 0;
1972 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1973 if(0 != encoder->private_->real_signal_unaligned[i]) {
1974 free(encoder->private_->real_signal_unaligned[i]);
1975 encoder->private_->real_signal_unaligned[i] = 0;
1979 for(i = 0; i < 2; i++) {
1980 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
1981 free(encoder->private_->integer_signal_mid_side_unaligned[i]);
1982 encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
1984 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1985 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
1986 free(encoder->private_->real_signal_mid_side_unaligned[i]);
1987 encoder->private_->real_signal_mid_side_unaligned[i] = 0;
1991 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1992 for(i = 0; i < encoder->protected_->num_apodizations; i++) {
1993 if(0 != encoder->private_->window_unaligned[i]) {
1994 free(encoder->private_->window_unaligned[i]);
1995 encoder->private_->window_unaligned[i] = 0;
1998 if(0 != encoder->private_->windowed_signal_unaligned) {
1999 free(encoder->private_->windowed_signal_unaligned);
2000 encoder->private_->windowed_signal_unaligned = 0;
2003 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2004 for(i = 0; i < 2; i++) {
2005 if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2006 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2007 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2011 for(channel = 0; channel < 2; channel++) {
2012 for(i = 0; i < 2; i++) {
2013 if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2014 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2015 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2019 if(0 != encoder->private_->abs_residual_unaligned) {
2020 free(encoder->private_->abs_residual_unaligned);
2021 encoder->private_->abs_residual_unaligned = 0;
2023 if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2024 free(encoder->private_->abs_residual_partition_sums_unaligned);
2025 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2027 if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2028 free(encoder->private_->raw_bits_per_partition_unaligned);
2029 encoder->private_->raw_bits_per_partition_unaligned = 0;
2031 if(encoder->protected_->verify) {
2032 for(i = 0; i < encoder->protected_->channels; i++) {
2033 if(0 != encoder->private_->verify.input_fifo.data[i]) {
2034 free(encoder->private_->verify.input_fifo.data[i]);
2035 encoder->private_->verify.input_fifo.data[i] = 0;
2039 FLAC__bitbuffer_free(encoder->private_->frame);
2042 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_size)
2045 unsigned i, channel;
2047 FLAC__ASSERT(new_size > 0);
2048 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2049 FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2051 /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2052 if(new_size <= encoder->private_->input_capacity)
2057 /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
2058 * requires that the input arrays (in our case the integer signals)
2059 * have a buffer of up to 3 zeroes in front (at negative indices) for
2060 * alignment purposes; we use 4 to keep the data well-aligned.
2063 for(i = 0; ok && i < encoder->protected_->channels; i++) {
2064 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size+4, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2065 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2066 if(encoder->protected_->max_lpc_order > 0)
2067 ok = ok && FLAC__memory_alloc_aligned_real_array(new_size, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2069 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2070 encoder->private_->integer_signal[i] += 4;
2072 for(i = 0; ok && i < 2; i++) {
2073 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]);
2074 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2075 if(encoder->protected_->max_lpc_order > 0)
2076 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]);
2078 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2079 encoder->private_->integer_signal_mid_side[i] += 4;
2081 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2082 if(ok && encoder->protected_->max_lpc_order > 0) {
2083 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2084 ok = ok && FLAC__memory_alloc_aligned_real_array(new_size, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2085 ok = ok && FLAC__memory_alloc_aligned_real_array(new_size, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2088 for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2089 for(i = 0; ok && i < 2; i++) {
2090 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2093 for(channel = 0; ok && channel < 2; channel++) {
2094 for(i = 0; ok && i < 2; i++) {
2095 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]);
2098 ok = ok && FLAC__memory_alloc_aligned_uint32_array(new_size, &encoder->private_->abs_residual_unaligned, &encoder->private_->abs_residual);
2099 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 */
2100 ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_size * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2101 if(encoder->protected_->do_escape_coding)
2102 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_size * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2105 encoder->private_->input_capacity = new_size;
2107 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2109 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2110 if(ok && encoder->protected_->max_lpc_order > 0) {
2111 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2112 switch(encoder->protected_->apodizations[i].type) {
2113 case FLAC__APODIZATION_BARTLETT:
2114 FLAC__window_bartlett(encoder->private_->window[i], new_size);
2116 case FLAC__APODIZATION_BARTLETT_HANN:
2117 FLAC__window_bartlett_hann(encoder->private_->window[i], new_size);
2119 case FLAC__APODIZATION_BLACKMAN:
2120 FLAC__window_blackman(encoder->private_->window[i], new_size);
2122 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2123 FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_size);
2125 case FLAC__APODIZATION_CONNES:
2126 FLAC__window_connes(encoder->private_->window[i], new_size);
2128 case FLAC__APODIZATION_FLATTOP:
2129 FLAC__window_flattop(encoder->private_->window[i], new_size);
2131 case FLAC__APODIZATION_GAUSS:
2132 FLAC__window_gauss(encoder->private_->window[i], new_size, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2134 case FLAC__APODIZATION_HAMMING:
2135 FLAC__window_hamming(encoder->private_->window[i], new_size);
2137 case FLAC__APODIZATION_HANN:
2138 FLAC__window_hann(encoder->private_->window[i], new_size);
2140 case FLAC__APODIZATION_KAISER_BESSEL:
2141 FLAC__window_kaiser_bessel(encoder->private_->window[i], new_size);
2143 case FLAC__APODIZATION_NUTTALL:
2144 FLAC__window_nuttall(encoder->private_->window[i], new_size);
2146 case FLAC__APODIZATION_RECTANGLE:
2147 FLAC__window_rectangle(encoder->private_->window[i], new_size);
2149 case FLAC__APODIZATION_TRIANGLE:
2150 FLAC__window_triangle(encoder->private_->window[i], new_size);
2152 case FLAC__APODIZATION_TUKEY:
2153 FLAC__window_tukey(encoder->private_->window[i], new_size, encoder->protected_->apodizations[i].parameters.tukey.p);
2155 case FLAC__APODIZATION_WELCH:
2156 FLAC__window_welch(encoder->private_->window[i], new_size);
2160 /* double protection */
2161 FLAC__window_hann(encoder->private_->window[i], new_size);
2171 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples)
2173 const FLAC__byte *buffer;
2176 FLAC__ASSERT(FLAC__bitbuffer_is_byte_aligned(encoder->private_->frame));
2178 FLAC__bitbuffer_get_buffer(encoder->private_->frame, &buffer, &bytes);
2180 if(encoder->protected_->verify) {
2181 encoder->private_->verify.output.data = buffer;
2182 encoder->private_->verify.output.bytes = bytes;
2183 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2184 encoder->private_->verify.needs_magic_hack = true;
2187 if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2188 FLAC__bitbuffer_release_buffer(encoder->private_->frame);
2189 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2190 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2196 if(write_frame_(encoder, buffer, bytes, samples) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2197 FLAC__bitbuffer_release_buffer(encoder->private_->frame);
2198 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2202 FLAC__bitbuffer_release_buffer(encoder->private_->frame);
2205 encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2206 encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2212 FLAC__StreamEncoderWriteStatus write_frame_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples)
2214 FLAC__StreamEncoderWriteStatus status;
2215 FLAC__uint64 output_position = 0;
2217 /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2218 if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2219 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2220 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2224 * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2227 FLAC__MetadataType type = (buffer[0] & 0x7f);
2228 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2229 encoder->protected_->streaminfo_offset = output_position;
2230 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2231 encoder->protected_->seektable_offset = output_position;
2235 * Mark the current seek point if hit (if audio_offset == 0 that
2236 * means we're still writing metadata and haven't hit the first
2239 if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2240 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2241 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2242 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2243 FLAC__uint64 test_sample;
2245 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2246 test_sample = encoder->private_->seek_table->points[i].sample_number;
2247 if(test_sample > frame_last_sample) {
2250 else if(test_sample >= frame_first_sample) {
2251 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2252 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2253 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2254 encoder->private_->first_seekpoint_to_check++;
2255 /* DO NOT: "break;" and here's why:
2256 * The seektable template may contain more than one target
2257 * sample for any given frame; we will keep looping, generating
2258 * duplicate seekpoints for them, and we'll clean it up later,
2259 * just before writing the seektable back to the metadata.
2263 encoder->private_->first_seekpoint_to_check++;
2268 status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2270 if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2271 encoder->private_->bytes_written += bytes;
2272 encoder->private_->samples_written += samples;
2273 /* we keep a high watermark on the number of frames written because
2274 * when the encoder goes back to write metadata, 'current_frame'
2275 * will drop back to 0.
2277 encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2280 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2285 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2286 void update_metadata_(const FLAC__StreamEncoder *encoder)
2288 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2289 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2290 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2291 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2292 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2293 const unsigned bps = metadata->data.stream_info.bits_per_sample;
2294 FLAC__StreamEncoderSeekStatus seek_status;
2296 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2298 /* All this is based on intimate knowledge of the stream header
2299 * layout, but a change to the header format that would break this
2300 * would also break all streams encoded in the previous format.
2304 * Write MD5 signature
2307 const unsigned md5_offset =
2308 FLAC__STREAM_METADATA_HEADER_LENGTH +
2310 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2311 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2312 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2313 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2314 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2315 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2316 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2317 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2320 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2321 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2322 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2325 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2326 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2332 * Write total samples
2335 const unsigned total_samples_byte_offset =
2336 FLAC__STREAM_METADATA_HEADER_LENGTH +
2338 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2339 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2340 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2341 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2342 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2343 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2344 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2348 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2349 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2350 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2351 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2352 b[4] = (FLAC__byte)(samples & 0xFF);
2353 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) {
2354 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2355 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2358 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2359 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2365 * Write min/max framesize
2368 const unsigned min_framesize_offset =
2369 FLAC__STREAM_METADATA_HEADER_LENGTH +
2371 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2372 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2375 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2376 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2377 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2378 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2379 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2380 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2381 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) {
2382 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2383 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2386 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2387 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2395 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2398 FLAC__format_seektable_sort(encoder->private_->seek_table);
2400 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2402 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) {
2403 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2404 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2408 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2411 xx = encoder->private_->seek_table->points[i].sample_number;
2412 b[7] = (FLAC__byte)xx; xx >>= 8;
2413 b[6] = (FLAC__byte)xx; xx >>= 8;
2414 b[5] = (FLAC__byte)xx; xx >>= 8;
2415 b[4] = (FLAC__byte)xx; xx >>= 8;
2416 b[3] = (FLAC__byte)xx; xx >>= 8;
2417 b[2] = (FLAC__byte)xx; xx >>= 8;
2418 b[1] = (FLAC__byte)xx; xx >>= 8;
2419 b[0] = (FLAC__byte)xx; xx >>= 8;
2420 xx = encoder->private_->seek_table->points[i].stream_offset;
2421 b[15] = (FLAC__byte)xx; xx >>= 8;
2422 b[14] = (FLAC__byte)xx; xx >>= 8;
2423 b[13] = (FLAC__byte)xx; xx >>= 8;
2424 b[12] = (FLAC__byte)xx; xx >>= 8;
2425 b[11] = (FLAC__byte)xx; xx >>= 8;
2426 b[10] = (FLAC__byte)xx; xx >>= 8;
2427 b[9] = (FLAC__byte)xx; xx >>= 8;
2428 b[8] = (FLAC__byte)xx; xx >>= 8;
2429 x = encoder->private_->seek_table->points[i].frame_samples;
2430 b[17] = (FLAC__byte)x; x >>= 8;
2431 b[16] = (FLAC__byte)x; x >>= 8;
2432 if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2433 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2440 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame)
2442 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2445 * Accumulate raw signal to the MD5 signature
2447 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)) {
2448 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2453 * Process the frame header and subframes into the frame bitbuffer
2455 if(!process_subframes_(encoder, is_last_frame)) {
2456 /* the above function sets the state for us in case of an error */
2461 * Zero-pad the frame to a byte_boundary
2463 if(!FLAC__bitbuffer_zero_pad_to_byte_boundary(encoder->private_->frame)) {
2464 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2469 * CRC-16 the whole thing
2471 FLAC__ASSERT(FLAC__bitbuffer_is_byte_aligned(encoder->private_->frame));
2472 FLAC__bitbuffer_write_raw_uint32(encoder->private_->frame, FLAC__bitbuffer_get_write_crc16(encoder->private_->frame), FLAC__FRAME_FOOTER_CRC_LEN);
2477 if(!write_bitbuffer_(encoder, encoder->protected_->blocksize)) {
2478 /* the above function sets the state for us in case of an error */
2483 * Get ready for the next frame
2485 encoder->private_->current_sample_number = 0;
2486 encoder->private_->current_frame_number++;
2487 encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
2492 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame)
2494 FLAC__FrameHeader frame_header;
2495 unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
2496 FLAC__bool do_independent, do_mid_side, precompute_partition_sums;
2499 * Calculate the min,max Rice partition orders
2502 max_partition_order = 0;
2505 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
2506 max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
2508 min_partition_order = min(min_partition_order, max_partition_order);
2510 precompute_partition_sums = encoder->private_->precompute_partition_sums && ((max_partition_order > min_partition_order) || encoder->protected_->do_escape_coding);
2515 if(!FLAC__bitbuffer_clear(encoder->private_->frame)) {
2516 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2519 frame_header.blocksize = encoder->protected_->blocksize;
2520 frame_header.sample_rate = encoder->protected_->sample_rate;
2521 frame_header.channels = encoder->protected_->channels;
2522 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
2523 frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
2524 frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2525 frame_header.number.frame_number = encoder->private_->current_frame_number;
2528 * Figure out what channel assignments to try
2530 if(encoder->protected_->do_mid_side_stereo) {
2531 if(encoder->protected_->loose_mid_side_stereo) {
2532 if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
2533 do_independent = true;
2537 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
2538 do_mid_side = !do_independent;
2542 do_independent = true;
2547 do_independent = true;
2548 do_mid_side = false;
2551 FLAC__ASSERT(do_independent || do_mid_side);
2554 * Check for wasted bits; set effective bps for each subframe
2556 if(do_independent) {
2557 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2558 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
2559 encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
2560 encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
2564 FLAC__ASSERT(encoder->protected_->channels == 2);
2565 for(channel = 0; channel < 2; channel++) {
2566 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
2567 encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
2568 encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
2573 * First do a normal encoding pass of each independent channel
2575 if(do_independent) {
2576 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2580 min_partition_order,
2581 max_partition_order,
2582 precompute_partition_sums,
2584 encoder->private_->subframe_bps[channel],
2585 encoder->private_->integer_signal[channel],
2586 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2587 encoder->private_->real_signal[channel],
2589 encoder->private_->subframe_workspace_ptr[channel],
2590 encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
2591 encoder->private_->residual_workspace[channel],
2592 encoder->private_->best_subframe+channel,
2593 encoder->private_->best_subframe_bits+channel
2594 #ifdef WINDOW_DEBUG_OUTPUT
2604 * Now do mid and side channels if requested
2607 FLAC__ASSERT(encoder->protected_->channels == 2);
2609 for(channel = 0; channel < 2; channel++) {
2613 min_partition_order,
2614 max_partition_order,
2615 precompute_partition_sums,
2617 encoder->private_->subframe_bps_mid_side[channel],
2618 encoder->private_->integer_signal_mid_side[channel],
2619 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2620 encoder->private_->real_signal_mid_side[channel],
2622 encoder->private_->subframe_workspace_ptr_mid_side[channel],
2623 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
2624 encoder->private_->residual_workspace_mid_side[channel],
2625 encoder->private_->best_subframe_mid_side+channel,
2626 encoder->private_->best_subframe_bits_mid_side+channel
2627 #ifdef WINDOW_DEBUG_OUTPUT
2637 * Compose the frame bitbuffer
2640 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
2641 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
2642 FLAC__ChannelAssignment channel_assignment;
2643 #ifdef WINDOW_DEBUG_OUTPUT
2644 unsigned left_bits = 0, right_bits = 0;
2647 FLAC__ASSERT(encoder->protected_->channels == 2);
2649 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
2650 channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
2653 unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
2655 FLAC__ChannelAssignment ca;
2657 FLAC__ASSERT(do_independent && do_mid_side);
2659 /* We have to figure out which channel assignent results in the smallest frame */
2660 bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
2661 bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
2662 bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
2663 bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
2665 for(channel_assignment = (FLAC__ChannelAssignment)0, min_bits = bits[0], ca = (FLAC__ChannelAssignment)1; (int)ca <= 3; ca = (FLAC__ChannelAssignment)((int)ca + 1)) {
2666 if(bits[ca] < min_bits) {
2667 min_bits = bits[ca];
2668 channel_assignment = ca;
2673 frame_header.channel_assignment = channel_assignment;
2675 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
2676 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
2680 switch(channel_assignment) {
2681 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2682 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
2683 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
2684 #ifdef WINDOW_DEBUG_OUTPUT
2685 left_bits = encoder->private_->best_subframe_bits [0];
2686 right_bits = encoder->private_->best_subframe_bits [1];
2689 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2690 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
2691 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
2692 #ifdef WINDOW_DEBUG_OUTPUT
2693 left_bits = encoder->private_->best_subframe_bits [0];
2694 right_bits = encoder->private_->best_subframe_bits_mid_side [1];
2697 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2698 left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
2699 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
2700 #ifdef WINDOW_DEBUG_OUTPUT
2701 left_bits = encoder->private_->best_subframe_bits_mid_side [1];
2702 right_bits = encoder->private_->best_subframe_bits [1];
2705 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2706 left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
2707 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
2708 #ifdef WINDOW_DEBUG_OUTPUT
2709 left_bits = encoder->private_->best_subframe_bits_mid_side [0];
2710 right_bits = encoder->private_->best_subframe_bits_mid_side [1];
2717 switch(channel_assignment) {
2718 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2719 left_bps = encoder->private_->subframe_bps [0];
2720 right_bps = encoder->private_->subframe_bps [1];
2722 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2723 left_bps = encoder->private_->subframe_bps [0];
2724 right_bps = encoder->private_->subframe_bps_mid_side[1];
2726 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2727 left_bps = encoder->private_->subframe_bps_mid_side[1];
2728 right_bps = encoder->private_->subframe_bps [1];
2730 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2731 left_bps = encoder->private_->subframe_bps_mid_side[0];
2732 right_bps = encoder->private_->subframe_bps_mid_side[1];
2738 /* note that encoder_add_subframe_ sets the state for us in case of an error */
2739 #ifdef WINDOW_DEBUG_OUTPUT
2740 if(!add_subframe_(encoder, &frame_header, left_bps , left_subframe , encoder->private_->frame, left_bits))
2742 if(!add_subframe_(encoder, &frame_header, right_bps, right_subframe, encoder->private_->frame, right_bits))
2745 if(!add_subframe_(encoder, &frame_header, left_bps , left_subframe , encoder->private_->frame))
2747 if(!add_subframe_(encoder, &frame_header, right_bps, right_subframe, encoder->private_->frame))
2752 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
2753 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
2757 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2758 #ifdef WINDOW_DEBUG_OUTPUT
2759 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]))
2761 if(!add_subframe_(encoder, &frame_header, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame))
2764 /* the above function sets the state for us in case of an error */
2770 if(encoder->protected_->loose_mid_side_stereo) {
2771 encoder->private_->loose_mid_side_stereo_frame_count++;
2772 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
2773 encoder->private_->loose_mid_side_stereo_frame_count = 0;
2776 encoder->private_->last_channel_assignment = frame_header.channel_assignment;
2781 FLAC__bool process_subframe_(
2782 FLAC__StreamEncoder *encoder,
2783 unsigned min_partition_order,
2784 unsigned max_partition_order,
2785 FLAC__bool precompute_partition_sums,
2786 const FLAC__FrameHeader *frame_header,
2787 unsigned subframe_bps,
2788 const FLAC__int32 integer_signal[],
2789 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2790 const FLAC__real real_signal[],
2792 FLAC__Subframe *subframe[2],
2793 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
2794 FLAC__int32 *residual[2],
2795 unsigned *best_subframe,
2797 #ifdef WINDOW_DEBUG_OUTPUT
2798 ,unsigned subframe_number
2802 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2803 FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
2805 FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
2807 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2808 FLAC__double lpc_residual_bits_per_sample;
2809 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 */
2810 FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
2811 unsigned min_lpc_order, max_lpc_order, lpc_order;
2812 unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
2814 unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
2815 unsigned rice_parameter;
2816 unsigned _candidate_bits, _best_bits;
2817 unsigned _best_subframe;
2819 /* verbatim subframe is the baseline against which we measure other compressed subframes */
2821 if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
2822 _best_bits = UINT_MAX;
2824 _best_bits = evaluate_verbatim_subframe_(integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
2826 if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
2827 unsigned signal_is_constant = false;
2828 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);
2829 /* check for constant subframe */
2831 !encoder->private_->disable_constant_subframes &&
2832 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2833 fixed_residual_bits_per_sample[1] == 0.0
2835 fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
2838 /* the above means it's possible all samples are the same value; now double-check it: */
2840 signal_is_constant = true;
2841 for(i = 1; i < frame_header->blocksize; i++) {
2842 if(integer_signal[0] != integer_signal[i]) {
2843 signal_is_constant = false;
2848 if(signal_is_constant) {
2849 _candidate_bits = evaluate_constant_subframe_(integer_signal[0], subframe_bps, subframe[!_best_subframe]);
2850 if(_candidate_bits < _best_bits) {
2851 _best_subframe = !_best_subframe;
2852 _best_bits = _candidate_bits;
2856 if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
2858 if(encoder->protected_->do_exhaustive_model_search) {
2859 min_fixed_order = 0;
2860 max_fixed_order = FLAC__MAX_FIXED_ORDER;
2863 min_fixed_order = max_fixed_order = guess_fixed_order;
2865 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
2866 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2867 if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
2868 continue; /* don't even try */
2869 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 */
2871 if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
2872 continue; /* don't even try */
2873 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 */
2875 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
2876 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2877 #ifdef DEBUG_VERBOSE
2878 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2880 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2883 evaluate_fixed_subframe_(
2886 residual[!_best_subframe],
2887 encoder->private_->abs_residual,
2888 encoder->private_->abs_residual_partition_sums,
2889 encoder->private_->raw_bits_per_partition,
2890 frame_header->blocksize,
2894 min_partition_order,
2895 max_partition_order,
2896 precompute_partition_sums,
2897 encoder->protected_->do_escape_coding,
2898 encoder->protected_->rice_parameter_search_dist,
2899 subframe[!_best_subframe],
2900 partitioned_rice_contents[!_best_subframe]
2902 if(_candidate_bits < _best_bits) {
2903 _best_subframe = !_best_subframe;
2904 _best_bits = _candidate_bits;
2909 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2911 if(encoder->protected_->max_lpc_order > 0) {
2912 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
2913 max_lpc_order = frame_header->blocksize-1;
2915 max_lpc_order = encoder->protected_->max_lpc_order;
2916 if(max_lpc_order > 0) {
2918 for (a = 0; a < encoder->protected_->num_apodizations; a++) {
2919 FLAC__lpc_window_data(real_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
2920 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
2921 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
2922 if(autoc[0] != 0.0) {
2923 FLAC__lpc_compute_lp_coefficients(autoc, max_lpc_order, encoder->private_->lp_coeff, lpc_error);
2924 if(encoder->protected_->do_exhaustive_model_search) {
2928 const unsigned guess_lpc_order =
2929 FLAC__lpc_compute_best_order(
2932 frame_header->blocksize,
2934 encoder->protected_->do_qlp_coeff_prec_search?
2935 FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
2936 encoder->protected_->qlp_coeff_precision
2939 min_lpc_order = max_lpc_order = guess_lpc_order;
2941 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
2942 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
2943 if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
2944 continue; /* don't even try */
2945 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
2946 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
2947 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2948 #ifdef DEBUG_VERBOSE
2949 fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2951 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2953 if(encoder->protected_->do_qlp_coeff_prec_search) {
2954 min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
2955 /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
2956 if(subframe_bps <= 17) {
2957 max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
2958 max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
2961 max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
2964 min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
2966 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
2968 evaluate_lpc_subframe_(
2971 residual[!_best_subframe],
2972 encoder->private_->abs_residual,
2973 encoder->private_->abs_residual_partition_sums,
2974 encoder->private_->raw_bits_per_partition,
2975 encoder->private_->lp_coeff[lpc_order-1],
2976 frame_header->blocksize,
2979 qlp_coeff_precision,
2981 min_partition_order,
2982 max_partition_order,
2983 precompute_partition_sums,
2984 encoder->protected_->do_escape_coding,
2985 encoder->protected_->rice_parameter_search_dist,
2986 subframe[!_best_subframe],
2987 partitioned_rice_contents[!_best_subframe]
2988 #ifdef WINDOW_DEBUG_OUTPUT
2989 ,frame_header->number.frame_number
2991 ,encoder->protected_->apodizations[a]
2994 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
2995 if(_candidate_bits < _best_bits) {
2996 _best_subframe = !_best_subframe;
2997 _best_bits = _candidate_bits;
3006 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3010 /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3011 if(_best_bits == UINT_MAX) {
3012 FLAC__ASSERT(_best_subframe == 0);
3013 _best_bits = evaluate_verbatim_subframe_(integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3016 *best_subframe = _best_subframe;
3017 *best_bits = _best_bits;
3022 FLAC__bool add_subframe_(
3023 FLAC__StreamEncoder *encoder,
3024 const FLAC__FrameHeader *frame_header,
3025 unsigned subframe_bps,
3026 const FLAC__Subframe *subframe,
3027 FLAC__BitBuffer *frame
3028 #ifdef WINDOW_DEBUG_OUTPUT
3029 ,unsigned subframe_bits
3033 switch(subframe->type) {
3034 case FLAC__SUBFRAME_TYPE_CONSTANT:
3035 if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3036 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3040 case FLAC__SUBFRAME_TYPE_FIXED:
3041 if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), frame_header->blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3042 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3046 case FLAC__SUBFRAME_TYPE_LPC:
3047 #ifdef WINDOW_DEBUG_OUTPUT
3048 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);
3050 if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), frame_header->blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3051 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3055 case FLAC__SUBFRAME_TYPE_VERBATIM:
3056 if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), frame_header->blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3057 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3068 unsigned evaluate_constant_subframe_(
3069 const FLAC__int32 signal,
3070 unsigned subframe_bps,
3071 FLAC__Subframe *subframe
3074 subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3075 subframe->data.constant.value = signal;
3077 return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe_bps;
3080 unsigned evaluate_fixed_subframe_(
3081 FLAC__StreamEncoder *encoder,
3082 const FLAC__int32 signal[],
3083 FLAC__int32 residual[],
3084 FLAC__uint32 abs_residual[],
3085 FLAC__uint64 abs_residual_partition_sums[],
3086 unsigned raw_bits_per_partition[],
3088 unsigned subframe_bps,
3090 unsigned rice_parameter,
3091 unsigned min_partition_order,
3092 unsigned max_partition_order,
3093 FLAC__bool precompute_partition_sums,
3094 FLAC__bool do_escape_coding,
3095 unsigned rice_parameter_search_dist,
3096 FLAC__Subframe *subframe,
3097 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3100 unsigned i, residual_bits;
3101 const unsigned residual_samples = blocksize - order;
3103 FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3105 subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3107 subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3108 subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3109 subframe->data.fixed.residual = residual;
3112 find_best_partition_order_(
3116 abs_residual_partition_sums,
3117 raw_bits_per_partition,
3121 min_partition_order,
3122 max_partition_order,
3123 precompute_partition_sums,
3125 rice_parameter_search_dist,
3126 &subframe->data.fixed.entropy_coding_method.data.partitioned_rice
3129 subframe->data.fixed.order = order;
3130 for(i = 0; i < order; i++)
3131 subframe->data.fixed.warmup[i] = signal[i];
3133 return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (order * subframe_bps) + residual_bits;
3136 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3137 unsigned evaluate_lpc_subframe_(
3138 FLAC__StreamEncoder *encoder,
3139 const FLAC__int32 signal[],
3140 FLAC__int32 residual[],
3141 FLAC__uint32 abs_residual[],
3142 FLAC__uint64 abs_residual_partition_sums[],
3143 unsigned raw_bits_per_partition[],
3144 const FLAC__real lp_coeff[],
3146 unsigned subframe_bps,
3148 unsigned qlp_coeff_precision,
3149 unsigned rice_parameter,
3150 unsigned min_partition_order,
3151 unsigned max_partition_order,
3152 FLAC__bool precompute_partition_sums,
3153 FLAC__bool do_escape_coding,
3154 unsigned rice_parameter_search_dist,
3155 FLAC__Subframe *subframe,
3156 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3157 #ifdef WINDOW_DEBUG_OUTPUT
3158 ,unsigned frame_number
3159 ,unsigned subframe_number
3160 ,FLAC__ApodizationSpecification aspec
3164 FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
3165 unsigned i, residual_bits;
3166 int quantization, ret;
3167 const unsigned residual_samples = blocksize - order;
3169 /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3170 if(subframe_bps <= 16) {
3171 FLAC__ASSERT(order > 0);
3172 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3173 qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3176 #ifdef WINDOW_DEBUG_OUTPUT
3177 if (aspec.type == FLAC__APODIZATION_GAUSS)
3178 snprintf(subframe->data.lpc.window_type, sizeof subframe->data.lpc.window_type, "%s(%0.5f)", winstr[aspec.type], aspec.parameters.gauss.stddev);
3179 else if (aspec.type == FLAC__APODIZATION_TUKEY)
3180 snprintf(subframe->data.lpc.window_type, sizeof subframe->data.lpc.window_type, "%s(%0.5f)", winstr[aspec.type], aspec.parameters.tukey.p);
3182 strncpy(subframe->data.lpc.window_type, winstr[aspec.type], sizeof subframe->data.lpc.window_type);
3185 ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3187 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3189 if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3190 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3191 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3193 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3195 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3197 subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3199 subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3200 subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3201 subframe->data.lpc.residual = residual;
3204 find_best_partition_order_(
3208 abs_residual_partition_sums,
3209 raw_bits_per_partition,
3213 min_partition_order,
3214 max_partition_order,
3215 precompute_partition_sums,
3217 rice_parameter_search_dist,
3218 &subframe->data.fixed.entropy_coding_method.data.partitioned_rice
3221 subframe->data.lpc.order = order;
3222 subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3223 subframe->data.lpc.quantization_level = quantization;
3224 memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3225 for(i = 0; i < order; i++)
3226 subframe->data.lpc.warmup[i] = signal[i];
3228 #ifdef WINDOW_DEBUG_OUTPUT
3229 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);
3231 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;
3235 unsigned evaluate_verbatim_subframe_(
3236 const FLAC__int32 signal[],
3238 unsigned subframe_bps,
3239 FLAC__Subframe *subframe
3242 subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3244 subframe->data.verbatim.data = signal;
3246 return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (blocksize * subframe_bps);
3249 unsigned find_best_partition_order_(
3250 FLAC__StreamEncoderPrivate *private_,
3251 const FLAC__int32 residual[],
3252 FLAC__uint32 abs_residual[],
3253 FLAC__uint64 abs_residual_partition_sums[],
3254 unsigned raw_bits_per_partition[],
3255 unsigned residual_samples,
3256 unsigned predictor_order,
3257 unsigned rice_parameter,
3258 unsigned min_partition_order,
3259 unsigned max_partition_order,
3260 FLAC__bool precompute_partition_sums,
3261 FLAC__bool do_escape_coding,
3262 unsigned rice_parameter_search_dist,
3263 FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
3267 unsigned residual_bits, best_residual_bits = 0;
3268 unsigned residual_sample;
3269 unsigned best_parameters_index = 0;
3270 const unsigned blocksize = residual_samples + predictor_order;
3272 /* compute abs(residual) for use later */
3273 for(residual_sample = 0; residual_sample < residual_samples; residual_sample++) {
3274 r = residual[residual_sample];
3275 abs_residual[residual_sample] = (FLAC__uint32)(r<0? -r : r);
3278 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3279 min_partition_order = min(min_partition_order, max_partition_order);
3281 if(precompute_partition_sums) {
3282 int partition_order;
3285 precompute_partition_info_sums_(abs_residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order);
3287 if(do_escape_coding)
3288 precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3290 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3291 #ifdef DONT_ESTIMATE_RICE_BITS
3293 set_partitioned_rice_with_precompute_(
3295 abs_residual_partition_sums+sum,
3296 raw_bits_per_partition+sum,
3300 rice_parameter_search_dist,
3301 (unsigned)partition_order,
3303 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3309 set_partitioned_rice_with_precompute_(
3311 abs_residual_partition_sums+sum,
3312 raw_bits_per_partition+sum,
3316 rice_parameter_search_dist,
3317 (unsigned)partition_order,
3319 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3325 FLAC__ASSERT(best_residual_bits != 0);
3328 sum += 1u << partition_order;
3329 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3330 best_residual_bits = residual_bits;
3331 best_parameters_index = !best_parameters_index;
3332 best_partitioned_rice->order = partition_order;
3337 unsigned partition_order;
3338 for(partition_order = min_partition_order; partition_order <= max_partition_order; partition_order++) {
3339 #ifdef DONT_ESTIMATE_RICE_BITS
3341 set_partitioned_rice_(
3347 rice_parameter_search_dist,
3349 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3355 set_partitioned_rice_(
3360 rice_parameter_search_dist,
3362 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3368 FLAC__ASSERT(best_residual_bits != 0);
3371 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3372 best_residual_bits = residual_bits;
3373 best_parameters_index = !best_parameters_index;
3374 best_partitioned_rice->order = partition_order;
3380 * We are allowed to de-const the pointer based on our special knowledge;
3381 * it is const to the outside world.
3384 FLAC__EntropyCodingMethod_PartitionedRiceContents* best_partitioned_rice_contents = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_partitioned_rice->contents;
3385 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(best_partitioned_rice_contents, max(6, best_partitioned_rice->order));
3386 memcpy(best_partitioned_rice_contents->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
3387 memcpy(best_partitioned_rice_contents->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
3390 return best_residual_bits;
3393 void precompute_partition_info_sums_(
3394 const FLAC__uint32 abs_residual[],
3395 FLAC__uint64 abs_residual_partition_sums[],
3396 unsigned residual_samples,
3397 unsigned predictor_order,
3398 unsigned min_partition_order,
3399 unsigned max_partition_order
3402 int partition_order;
3403 unsigned from_partition, to_partition = 0;
3404 const unsigned blocksize = residual_samples + predictor_order;
3406 /* first do max_partition_order */
3407 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3408 FLAC__uint64 abs_residual_partition_sum;
3410 unsigned partition, partition_sample, partition_samples, residual_sample;
3411 const unsigned partitions = 1u << partition_order;
3412 const unsigned default_partition_samples = blocksize >> partition_order;
3414 FLAC__ASSERT(default_partition_samples > predictor_order);
3416 for(partition = residual_sample = 0; partition < partitions; partition++) {
3417 partition_samples = default_partition_samples;
3419 partition_samples -= predictor_order;
3420 abs_residual_partition_sum = 0;
3421 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
3422 abs_r = abs_residual[residual_sample];
3423 abs_residual_partition_sum += abs_r;
3426 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3428 to_partition = partitions;
3432 /* now merge partitions for lower orders */
3433 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
3436 const unsigned partitions = 1u << partition_order;
3437 for(i = 0; i < partitions; i++) {
3438 s = abs_residual_partition_sums[from_partition];
3440 abs_residual_partition_sums[to_partition] = s + abs_residual_partition_sums[from_partition];
3447 void precompute_partition_info_escapes_(
3448 const FLAC__int32 residual[],
3449 unsigned raw_bits_per_partition[],
3450 unsigned residual_samples,
3451 unsigned predictor_order,
3452 unsigned min_partition_order,
3453 unsigned max_partition_order
3456 int partition_order;
3457 unsigned from_partition, to_partition = 0;
3458 const unsigned blocksize = residual_samples + predictor_order;
3460 /* first do max_partition_order */
3461 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3462 FLAC__int32 r, residual_partition_min, residual_partition_max;
3463 unsigned silog2_min, silog2_max;
3464 unsigned partition, partition_sample, partition_samples, residual_sample;
3465 const unsigned partitions = 1u << partition_order;
3466 const unsigned default_partition_samples = blocksize >> partition_order;
3468 FLAC__ASSERT(default_partition_samples > predictor_order);
3470 for(partition = residual_sample = 0; partition < partitions; partition++) {
3471 partition_samples = default_partition_samples;
3473 partition_samples -= predictor_order;
3474 residual_partition_min = residual_partition_max = 0;
3475 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
3476 r = residual[residual_sample];
3477 if(r < residual_partition_min)
3478 residual_partition_min = r;
3479 else if(r > residual_partition_max)
3480 residual_partition_max = r;
3483 silog2_min = FLAC__bitmath_silog2(residual_partition_min);
3484 silog2_max = FLAC__bitmath_silog2(residual_partition_max);
3485 raw_bits_per_partition[partition] = max(silog2_min, silog2_max);
3487 to_partition = partitions;
3488 break; /*@@@@@@ yuck, should remove the 'for' loop instead */
3491 /* now merge partitions for lower orders */
3492 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
3495 const unsigned partitions = 1u << partition_order;
3496 for(i = 0; i < partitions; i++) {
3497 m = raw_bits_per_partition[from_partition];
3499 raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
3506 #ifdef VARIABLE_RICE_BITS
3507 #undef VARIABLE_RICE_BITS
3509 #ifndef DONT_ESTIMATE_RICE_BITS
3510 #define VARIABLE_RICE_BITS(value, parameter) ((value) >> (parameter))
3513 #ifdef DONT_ESTIMATE_RICE_BITS
3514 FLAC__bool set_partitioned_rice_(
3515 const FLAC__uint32 abs_residual[],
3516 const FLAC__int32 residual[],
3517 const unsigned residual_samples,
3518 const unsigned predictor_order,
3519 const unsigned suggested_rice_parameter,
3520 const unsigned rice_parameter_search_dist,
3521 const unsigned partition_order,
3522 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3526 FLAC__bool set_partitioned_rice_(
3527 const FLAC__uint32 abs_residual[],
3528 const unsigned residual_samples,
3529 const unsigned predictor_order,
3530 const unsigned suggested_rice_parameter,
3531 const unsigned rice_parameter_search_dist,
3532 const unsigned partition_order,
3533 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3538 unsigned rice_parameter, partition_bits;
3539 #ifndef NO_RICE_SEARCH
3540 unsigned best_partition_bits;
3541 unsigned min_rice_parameter, max_rice_parameter, best_rice_parameter = 0;
3543 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
3544 unsigned *parameters;
3546 FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
3548 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
3549 parameters = partitioned_rice_contents->parameters;
3551 if(partition_order == 0) {
3554 #ifndef NO_RICE_SEARCH
3555 if(rice_parameter_search_dist) {
3556 if(suggested_rice_parameter < rice_parameter_search_dist)
3557 min_rice_parameter = 0;
3559 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
3560 max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
3561 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3562 #ifdef DEBUG_VERBOSE
3563 fprintf(stderr, "clipping rice_parameter (%u -> %u) @2\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3565 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3569 min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
3571 best_partition_bits = 0xffffffff;
3572 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3574 #ifdef VARIABLE_RICE_BITS
3575 const unsigned rice_parameter_estimate = rice_parameter-1;
3576 partition_bits = (1+rice_parameter) * residual_samples;
3580 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
3581 for(i = 0; i < residual_samples; i++) {
3582 #ifdef VARIABLE_RICE_BITS
3583 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter_estimate);
3585 partition_bits += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter); /* NOTE: we will need to pass in residual[] in addition to abs_residual[] */
3588 #ifndef NO_RICE_SEARCH
3589 if(partition_bits < best_partition_bits) {
3590 best_rice_parameter = rice_parameter;
3591 best_partition_bits = partition_bits;
3595 parameters[0] = best_rice_parameter;
3596 bits_ += best_partition_bits;
3599 unsigned partition, residual_sample, save_residual_sample, partition_sample;
3600 unsigned partition_samples;
3601 FLAC__uint64 mean, k;
3602 const unsigned partitions = 1u << partition_order;
3603 for(partition = residual_sample = 0; partition < partitions; partition++) {
3604 partition_samples = (residual_samples+predictor_order) >> partition_order;
3605 if(partition == 0) {
3606 if(partition_samples <= predictor_order)
3609 partition_samples -= predictor_order;
3612 save_residual_sample = residual_sample;
3613 for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++)
3614 mean += abs_residual[residual_sample];
3615 residual_sample = save_residual_sample;
3616 /* we are basically calculating the size in bits of the
3617 * average residual magnitude in the partition:
3618 * rice_parameter = floor(log2(mean/partition_samples))
3619 * 'mean' is not a good name for the variable, it is
3620 * actually the sum of magnitudes of all residual values
3621 * in the partition, so the actual mean is
3622 * mean/partition_samples
3624 for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
3626 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3627 #ifdef DEBUG_VERBOSE
3628 fprintf(stderr, "clipping rice_parameter (%u -> %u) @3\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3630 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3633 #ifndef NO_RICE_SEARCH
3634 if(rice_parameter_search_dist) {
3635 if(rice_parameter < rice_parameter_search_dist)
3636 min_rice_parameter = 0;
3638 min_rice_parameter = rice_parameter - rice_parameter_search_dist;
3639 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
3640 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3641 #ifdef DEBUG_VERBOSE
3642 fprintf(stderr, "clipping rice_parameter (%u -> %u) @4\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3644 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3648 min_rice_parameter = max_rice_parameter = rice_parameter;
3650 best_partition_bits = 0xffffffff;
3651 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3653 #ifdef VARIABLE_RICE_BITS
3654 const unsigned rice_parameter_estimate = rice_parameter-1;
3655 partition_bits = (1+rice_parameter) * partition_samples;
3659 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
3660 save_residual_sample = residual_sample;
3661 for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++) {
3662 #ifdef VARIABLE_RICE_BITS
3663 partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter_estimate);
3665 partition_bits += FLAC__bitbuffer_rice_bits(residual[residual_sample], rice_parameter); /* NOTE: we will need to pass in residual[] in addition to abs_residual[] */
3668 #ifndef NO_RICE_SEARCH
3669 if(rice_parameter != max_rice_parameter)
3670 residual_sample = save_residual_sample;
3671 if(partition_bits < best_partition_bits) {
3672 best_rice_parameter = rice_parameter;
3673 best_partition_bits = partition_bits;
3677 parameters[partition] = best_rice_parameter;
3678 bits_ += best_partition_bits;
3686 #ifdef DONT_ESTIMATE_RICE_BITS
3687 FLAC__bool set_partitioned_rice_with_precompute_(
3688 const FLAC__int32 residual[],
3689 const FLAC__uint64 abs_residual_partition_sums[],
3690 const unsigned raw_bits_per_partition[],
3691 const unsigned residual_samples,
3692 const unsigned predictor_order,
3693 const unsigned suggested_rice_parameter,
3694 const unsigned rice_parameter_search_dist,
3695 const unsigned partition_order,
3696 const FLAC__bool search_for_escapes,
3697 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3701 FLAC__bool set_partitioned_rice_with_precompute_(
3702 const FLAC__uint32 abs_residual[],
3703 const FLAC__uint64 abs_residual_partition_sums[],
3704 const unsigned raw_bits_per_partition[],
3705 const unsigned residual_samples,
3706 const unsigned predictor_order,
3707 const unsigned suggested_rice_parameter,
3708 const unsigned rice_parameter_search_dist,
3709 const unsigned partition_order,
3710 const FLAC__bool search_for_escapes,
3711 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3716 unsigned rice_parameter, partition_bits;
3717 #ifndef NO_RICE_SEARCH
3718 unsigned best_partition_bits;
3719 unsigned min_rice_parameter, max_rice_parameter, best_rice_parameter = 0;
3722 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
3723 unsigned *parameters, *raw_bits;
3725 FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
3727 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
3728 parameters = partitioned_rice_contents->parameters;
3729 raw_bits = partitioned_rice_contents->raw_bits;
3731 if(partition_order == 0) {
3734 #ifndef NO_RICE_SEARCH
3735 if(rice_parameter_search_dist) {
3736 if(suggested_rice_parameter < rice_parameter_search_dist)
3737 min_rice_parameter = 0;
3739 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
3740 max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
3741 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3742 #ifdef DEBUG_VERBOSE
3743 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3745 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3749 min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
3751 best_partition_bits = 0xffffffff;
3752 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3754 #ifdef VARIABLE_RICE_BITS
3755 const unsigned rice_parameter_estimate = rice_parameter-1;
3756 partition_bits = (1+rice_parameter) * residual_samples;
3760 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
3761 for(i = 0; i < residual_samples; i++) {
3762 #ifdef VARIABLE_RICE_BITS
3763 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter_estimate);
3765 partition_bits += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
3768 #ifndef NO_RICE_SEARCH
3769 if(partition_bits < best_partition_bits) {
3770 best_rice_parameter = rice_parameter;
3771 best_partition_bits = partition_bits;
3775 if(search_for_escapes) {
3776 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;
3777 if(flat_bits <= best_partition_bits) {
3778 raw_bits[0] = raw_bits_per_partition[0];
3779 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
3780 best_partition_bits = flat_bits;
3783 parameters[0] = best_rice_parameter;
3784 bits_ += best_partition_bits;
3787 unsigned partition, residual_sample, save_residual_sample, partition_sample;
3788 unsigned partition_samples;
3789 FLAC__uint64 mean, k;
3790 const unsigned partitions = 1u << partition_order;
3791 for(partition = residual_sample = 0; partition < partitions; partition++) {
3792 partition_samples = (residual_samples+predictor_order) >> partition_order;
3793 if(partition == 0) {
3794 if(partition_samples <= predictor_order)
3797 partition_samples -= predictor_order;
3799 mean = abs_residual_partition_sums[partition];
3800 /* we are basically calculating the size in bits of the
3801 * average residual magnitude in the partition:
3802 * rice_parameter = floor(log2(mean/partition_samples))
3803 * 'mean' is not a good name for the variable, it is
3804 * actually the sum of magnitudes of all residual values
3805 * in the partition, so the actual mean is
3806 * mean/partition_samples
3808 for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
3810 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3811 #ifdef DEBUG_VERBOSE
3812 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3814 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3817 #ifndef NO_RICE_SEARCH
3818 if(rice_parameter_search_dist) {
3819 if(rice_parameter < rice_parameter_search_dist)
3820 min_rice_parameter = 0;
3822 min_rice_parameter = rice_parameter - rice_parameter_search_dist;
3823 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
3824 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3825 #ifdef DEBUG_VERBOSE
3826 fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3828 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3832 min_rice_parameter = max_rice_parameter = rice_parameter;
3834 best_partition_bits = 0xffffffff;
3835 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3837 #ifdef VARIABLE_RICE_BITS
3838 const unsigned rice_parameter_estimate = rice_parameter-1;
3839 partition_bits = (1+rice_parameter) * partition_samples;
3843 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
3844 save_residual_sample = residual_sample;
3845 for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++) {
3846 #ifdef VARIABLE_RICE_BITS
3847 partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter_estimate);
3849 partition_bits += FLAC__bitbuffer_rice_bits(residual[residual_sample], rice_parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
3852 #ifndef NO_RICE_SEARCH
3853 if(rice_parameter != max_rice_parameter)
3854 residual_sample = save_residual_sample;
3855 if(partition_bits < best_partition_bits) {
3856 best_rice_parameter = rice_parameter;
3857 best_partition_bits = partition_bits;
3861 if(search_for_escapes) {
3862 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;
3863 if(flat_bits <= best_partition_bits) {
3864 raw_bits[partition] = raw_bits_per_partition[partition];
3865 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
3866 best_partition_bits = flat_bits;
3869 parameters[partition] = best_rice_parameter;
3870 bits_ += best_partition_bits;
3878 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
3883 for(i = 0; i < samples && !(x&1); i++)
3890 for(shift = 0; !(x&1); shift++)
3895 for(i = 0; i < samples; i++)
3896 signal[i] >>= shift;
3902 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
3906 for(channel = 0; channel < channels; channel++)
3907 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
3909 fifo->tail += wide_samples;
3911 FLAC__ASSERT(fifo->tail <= fifo->size);
3914 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
3917 unsigned sample, wide_sample;
3918 unsigned tail = fifo->tail;
3920 sample = input_offset * channels;
3921 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
3922 for(channel = 0; channel < channels; channel++)
3923 fifo->data[channel][tail] = input[sample++];
3928 FLAC__ASSERT(fifo->tail <= fifo->size);
3931 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
3933 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
3934 const unsigned encoded_bytes = encoder->private_->verify.output.bytes;
3937 if(encoder->private_->verify.needs_magic_hack) {
3938 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
3939 *bytes = FLAC__STREAM_SYNC_LENGTH;
3940 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
3941 encoder->private_->verify.needs_magic_hack = false;
3944 if(encoded_bytes == 0) {
3946 * If we get here, a FIFO underflow has occurred,
3947 * which means there is a bug somewhere.
3950 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
3952 else if(encoded_bytes < *bytes)
3953 *bytes = encoded_bytes;
3954 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
3955 encoder->private_->verify.output.data += *bytes;
3956 encoder->private_->verify.output.bytes -= *bytes;
3959 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
3962 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
3964 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
3966 const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
3967 const unsigned blocksize = frame->header.blocksize;
3968 const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
3970 for(channel = 0; channel < channels; channel++) {
3971 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
3972 unsigned i, sample = 0;
3973 FLAC__int32 expect = 0, got = 0;
3975 for(i = 0; i < blocksize; i++) {
3976 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
3978 expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
3979 got = (FLAC__int32)buffer[channel][i];
3983 FLAC__ASSERT(i < blocksize);
3984 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
3985 encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
3986 encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
3987 encoder->private_->verify.error_stats.channel = channel;
3988 encoder->private_->verify.error_stats.sample = sample;
3989 encoder->private_->verify.error_stats.expected = expect;
3990 encoder->private_->verify.error_stats.got = got;
3991 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
3992 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
3995 /* dequeue the frame from the fifo */
3996 for(channel = 0; channel < channels; channel++) {
3997 memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail - blocksize);
3999 encoder->private_->verify.input_fifo.tail -= blocksize;
4000 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4003 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4005 (void)decoder, (void)metadata, (void)client_data;
4008 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4010 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4011 (void)decoder, (void)status;
4012 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4015 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4019 if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
4020 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4022 return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4025 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4031 offset = ftello(encoder->private_->file);
4034 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4037 *absolute_byte_offset = (FLAC__uint64)offset;
4038 return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4042 #ifdef FLAC__VALGRIND_TESTING
4043 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4045 size_t ret = fwrite(ptr, size, nmemb, stream);
4051 #define local__fwrite fwrite
4054 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
4056 (void)client_data, (void)samples, (void)current_frame;
4058 if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4059 if(0 != encoder->private_->progress_callback && samples > 0)
4060 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);
4061 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4064 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4068 * This will forcibly set stdout to binary mode (for OSes that require it)
4070 FILE *get_binary_stdout_()
4072 /* if something breaks here it is probably due to the presence or
4073 * absence of an underscore before the identifiers 'setmode',
4074 * 'fileno', and/or 'O_BINARY'; check your system header files.
4076 #if defined _MSC_VER || defined __MINGW32__
4077 _setmode(_fileno(stdout), _O_BINARY);
4078 #elif defined __CYGWIN__
4079 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4080 setmode(_fileno(stdout), _O_BINARY);
4081 #elif defined __EMX__
4082 setmode(fileno(stdout), O_BINARY);