1 /* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006 Josh Coalson
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #undef WINDOW_DEBUG_OUTPUT
39 #if defined _MSC_VER || defined __MINGW32__
40 #include <io.h> /* for _setmode() */
41 #include <fcntl.h> /* for _O_BINARY */
43 #if defined __CYGWIN__ || defined __EMX__
44 #include <io.h> /* for setmode(), O_BINARY */
45 #include <fcntl.h> /* for _O_BINARY */
49 #include <stdlib.h> /* for malloc() */
50 #include <string.h> /* for memcpy() */
51 #include <sys/types.h> /* for off_t */
52 #if defined _MSC_VER || defined __MINGW32__
53 /*@@@ [2G limit] hacks for MSVC6 */
57 #include "FLAC/assert.h"
58 #include "FLAC/stream_decoder.h"
59 #include "protected/stream_encoder.h"
60 #include "private/bitbuffer.h"
61 #include "private/bitmath.h"
62 #include "private/crc.h"
63 #include "private/cpu.h"
64 #include "private/fixed.h"
65 #include "private/format.h"
66 #include "private/lpc.h"
67 #include "private/md5.h"
68 #include "private/memory.h"
69 #include "private/stream_encoder_framing.h"
70 #include "private/window.h"
75 #define min(x,y) ((x)<(y)?(x):(y))
80 #define max(x,y) ((x)>(y)?(x):(y))
83 FLAC__int32 *data[FLAC__MAX_CHANNELS];
84 unsigned size; /* of each data[] in samples */
89 const FLAC__byte *data;
96 ENCODER_IN_METADATA = 1,
100 /***********************************************************************
102 * Private class method prototypes
104 ***********************************************************************/
106 static void set_defaults_(FLAC__StreamEncoder *encoder);
107 static void free_(FLAC__StreamEncoder *encoder);
108 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_size);
109 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples);
110 static FLAC__StreamEncoderWriteStatus write_frame_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples);
111 static void update_metadata_(const FLAC__StreamEncoder *encoder);
112 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame);
113 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame);
115 static FLAC__bool process_subframe_(
116 FLAC__StreamEncoder *encoder,
117 unsigned min_partition_order,
118 unsigned max_partition_order,
119 FLAC__bool precompute_partition_sums,
120 const FLAC__FrameHeader *frame_header,
121 unsigned subframe_bps,
122 const FLAC__int32 integer_signal[],
123 #ifndef FLAC__INTEGER_ONLY_LIBRARY
124 const FLAC__real real_signal[],
126 FLAC__Subframe *subframe[2],
127 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
128 FLAC__int32 *residual[2],
129 unsigned *best_subframe,
131 #ifdef WINDOW_DEBUG_OUTPUT
132 ,unsigned subframe_number
136 static FLAC__bool add_subframe_(
137 FLAC__StreamEncoder *encoder,
138 const FLAC__FrameHeader *frame_header,
139 unsigned subframe_bps,
140 const FLAC__Subframe *subframe,
141 FLAC__BitBuffer *frame
142 #ifdef WINDOW_DEBUG_OUTPUT
143 ,unsigned subframe_bits
147 static unsigned evaluate_constant_subframe_(
148 const FLAC__int32 signal,
149 unsigned subframe_bps,
150 FLAC__Subframe *subframe
153 static unsigned evaluate_fixed_subframe_(
154 FLAC__StreamEncoder *encoder,
155 const FLAC__int32 signal[],
156 FLAC__int32 residual[],
157 FLAC__uint32 abs_residual[],
158 FLAC__uint64 abs_residual_partition_sums[],
159 unsigned raw_bits_per_partition[],
161 unsigned subframe_bps,
163 unsigned rice_parameter,
164 unsigned min_partition_order,
165 unsigned max_partition_order,
166 FLAC__bool precompute_partition_sums,
167 FLAC__bool do_escape_coding,
168 unsigned rice_parameter_search_dist,
169 FLAC__Subframe *subframe,
170 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
173 #ifndef FLAC__INTEGER_ONLY_LIBRARY
174 static unsigned evaluate_lpc_subframe_(
175 FLAC__StreamEncoder *encoder,
176 const FLAC__int32 signal[],
177 FLAC__int32 residual[],
178 FLAC__uint32 abs_residual[],
179 FLAC__uint64 abs_residual_partition_sums[],
180 unsigned raw_bits_per_partition[],
181 const FLAC__real lp_coeff[],
183 unsigned subframe_bps,
185 unsigned qlp_coeff_precision,
186 unsigned rice_parameter,
187 unsigned min_partition_order,
188 unsigned max_partition_order,
189 FLAC__bool precompute_partition_sums,
190 FLAC__bool do_escape_coding,
191 unsigned rice_parameter_search_dist,
192 FLAC__Subframe *subframe,
193 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
194 #ifdef WINDOW_DEBUG_OUTPUT
195 ,unsigned frame_number
196 ,unsigned subframe_number
197 ,FLAC__ApodizationSpecification aspec
202 static unsigned evaluate_verbatim_subframe_(
203 const FLAC__int32 signal[],
205 unsigned subframe_bps,
206 FLAC__Subframe *subframe
209 static unsigned find_best_partition_order_(
210 struct FLAC__StreamEncoderPrivate *private_,
211 const FLAC__int32 residual[],
212 FLAC__uint32 abs_residual[],
213 FLAC__uint64 abs_residual_partition_sums[],
214 unsigned raw_bits_per_partition[],
215 unsigned residual_samples,
216 unsigned predictor_order,
217 unsigned rice_parameter,
218 unsigned min_partition_order,
219 unsigned max_partition_order,
220 FLAC__bool precompute_partition_sums,
221 FLAC__bool do_escape_coding,
222 unsigned rice_parameter_search_dist,
223 FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
226 static void precompute_partition_info_sums_(
227 const FLAC__uint32 abs_residual[],
228 FLAC__uint64 abs_residual_partition_sums[],
229 unsigned residual_samples,
230 unsigned predictor_order,
231 unsigned min_partition_order,
232 unsigned max_partition_order
235 static void precompute_partition_info_escapes_(
236 const FLAC__int32 residual[],
237 unsigned raw_bits_per_partition[],
238 unsigned residual_samples,
239 unsigned predictor_order,
240 unsigned min_partition_order,
241 unsigned max_partition_order
244 #ifdef DONT_ESTIMATE_RICE_BITS
245 static FLAC__bool set_partitioned_rice_(
246 const FLAC__uint32 abs_residual[],
247 const FLAC__int32 residual[],
248 const unsigned residual_samples,
249 const unsigned predictor_order,
250 const unsigned suggested_rice_parameter,
251 const unsigned rice_parameter_search_dist,
252 const unsigned partition_order,
253 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
257 static FLAC__bool set_partitioned_rice_with_precompute_(
258 const FLAC__int32 residual[],
259 const FLAC__uint64 abs_residual_partition_sums[],
260 const unsigned raw_bits_per_partition[],
261 const unsigned residual_samples,
262 const unsigned predictor_order,
263 const unsigned suggested_rice_parameter,
264 const unsigned rice_parameter_search_dist,
265 const unsigned partition_order,
266 const FLAC__bool search_for_escapes,
267 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
271 static FLAC__bool set_partitioned_rice_(
272 const FLAC__uint32 abs_residual[],
273 const unsigned residual_samples,
274 const unsigned predictor_order,
275 const unsigned suggested_rice_parameter,
276 const unsigned rice_parameter_search_dist,
277 const unsigned partition_order,
278 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
282 static FLAC__bool set_partitioned_rice_with_precompute_(
283 const FLAC__uint32 abs_residual[],
284 const FLAC__uint64 abs_residual_partition_sums[],
285 const unsigned raw_bits_per_partition[],
286 const unsigned residual_samples,
287 const unsigned predictor_order,
288 const unsigned suggested_rice_parameter,
289 const unsigned rice_parameter_search_dist,
290 const unsigned partition_order,
291 const FLAC__bool search_for_escapes,
292 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
297 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
299 /* verify-related routines: */
300 static void append_to_verify_fifo_(
301 verify_input_fifo *fifo,
302 const FLAC__int32 * const input[],
303 unsigned input_offset,
305 unsigned wide_samples
308 static void append_to_verify_fifo_interleaved_(
309 verify_input_fifo *fifo,
310 const FLAC__int32 input[],
311 unsigned input_offset,
313 unsigned wide_samples
316 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
317 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
318 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
319 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
321 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
322 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
323 static FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
324 static FILE *get_binary_stdout_();
326 #ifdef WINDOW_DEBUG_OUTPUT
327 static const char * const winstr[] = {
331 "blackman_harris_4term_92db_sidelobe",
346 /***********************************************************************
350 ***********************************************************************/
352 typedef struct FLAC__StreamEncoderPrivate {
353 unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
354 FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
355 FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
356 #ifndef FLAC__INTEGER_ONLY_LIBRARY
357 FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* the floating-point version of the input signal */
358 FLAC__real *real_signal_mid_side[2]; /* the floating-point version of the mid-side input signal (stereo only) */
359 FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
360 FLAC__real *windowed_signal; /* the real_signal[] * current window[] */
362 unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
363 unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
364 FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
365 FLAC__int32 *residual_workspace_mid_side[2][2];
366 FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
367 FLAC__Subframe subframe_workspace_mid_side[2][2];
368 FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
369 FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
370 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
371 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
372 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
373 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
374 unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index into the above workspaces */
375 unsigned best_subframe_mid_side[2];
376 unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
377 unsigned best_subframe_bits_mid_side[2];
378 FLAC__uint32 *abs_residual; /* workspace where abs(candidate residual) is stored */
379 FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
380 unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
381 FLAC__BitBuffer *frame; /* the current frame being worked on */
382 unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
383 unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
384 FLAC__ChannelAssignment last_channel_assignment;
385 FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
386 FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
387 unsigned current_sample_number;
388 unsigned current_frame_number;
389 struct FLAC__MD5Context md5context;
390 FLAC__CPUInfo cpuinfo;
391 #ifndef FLAC__INTEGER_ONLY_LIBRARY
392 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
394 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
396 #ifndef FLAC__INTEGER_ONLY_LIBRARY
397 void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
398 void (*local_lpc_compute_residual_from_qlp_coefficients)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
399 void (*local_lpc_compute_residual_from_qlp_coefficients_64bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
400 void (*local_lpc_compute_residual_from_qlp_coefficients_16bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
402 FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
403 FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
404 FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
405 FLAC__bool precompute_partition_sums; /* our initial guess as to whether precomputing the partitions sums will be a speed improvement */
406 FLAC__bool disable_constant_subframes;
407 FLAC__bool disable_fixed_subframes;
408 FLAC__bool disable_verbatim_subframes;
409 FLAC__StreamEncoderSeekCallback seek_callback;
410 FLAC__StreamEncoderTellCallback tell_callback;
411 FLAC__StreamEncoderWriteCallback write_callback;
412 FLAC__StreamEncoderMetadataCallback metadata_callback;
413 FLAC__StreamEncoderProgressCallback progress_callback;
415 unsigned first_seekpoint_to_check;
416 FILE *file; /* only used when encoding to a file */
417 FLAC__uint64 bytes_written;
418 FLAC__uint64 samples_written;
419 unsigned frames_written;
420 unsigned total_frames_estimate;
421 /* unaligned (original) pointers to allocated data */
422 FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
423 FLAC__int32 *integer_signal_mid_side_unaligned[2];
424 #ifndef FLAC__INTEGER_ONLY_LIBRARY
425 FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS];
426 FLAC__real *real_signal_mid_side_unaligned[2];
427 FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
428 FLAC__real *windowed_signal_unaligned;
430 FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
431 FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
432 FLAC__uint32 *abs_residual_unaligned;
433 FLAC__uint64 *abs_residual_partition_sums_unaligned;
434 unsigned *raw_bits_per_partition_unaligned;
436 * These fields have been moved here from private function local
437 * declarations merely to save stack space during encoding.
439 #ifndef FLAC__INTEGER_ONLY_LIBRARY
440 FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
442 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
444 * The data for the verify section
447 FLAC__StreamDecoder *decoder;
448 EncoderStateHint state_hint;
449 FLAC__bool needs_magic_hack;
450 verify_input_fifo input_fifo;
451 verify_output output;
453 FLAC__uint64 absolute_sample;
454 unsigned frame_number;
457 FLAC__int32 expected;
461 FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
462 } FLAC__StreamEncoderPrivate;
464 /***********************************************************************
466 * Public static class data
468 ***********************************************************************/
470 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
471 "FLAC__STREAM_ENCODER_OK",
472 "FLAC__STREAM_ENCODER_UNINITIALIZED",
473 "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
474 "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
475 "FLAC__STREAM_ENCODER_CLIENT_ERROR",
476 "FLAC__STREAM_ENCODER_IO_ERROR",
477 "FLAC__STREAM_ENCODER_FRAMING_ERROR",
478 "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
481 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
482 "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
483 "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
484 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
485 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
486 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
487 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
488 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
489 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
490 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
491 "FLAC__STREAM_ENCODER_INIT_STATUS_MID_SIDE_CHANNELS_MISMATCH",
492 "FLAC__STREAM_ENCODER_INIT_STATUS_MID_SIDE_SAMPLE_SIZE_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;
747 if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
748 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
749 if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
750 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
752 /* validate metadata */
753 if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
754 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
755 metadata_has_seektable = false;
756 metadata_has_vorbis_comment = false;
757 metadata_picture_has_type1 = false;
758 metadata_picture_has_type2 = false;
759 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
760 const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
761 if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
762 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
763 else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
764 if(metadata_has_seektable) /* only one is allowed */
765 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
766 metadata_has_seektable = true;
767 if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
768 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
770 else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
771 if(metadata_has_vorbis_comment) /* only one is allowed */
772 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
773 metadata_has_vorbis_comment = true;
775 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
776 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
777 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
779 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
780 if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
781 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
782 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
783 if(metadata_picture_has_type1) /* there should only be 1 per stream */
784 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
785 metadata_picture_has_type1 = true;
786 /* standard icon must be 32x32 pixel PNG */
788 m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
790 (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
791 m->data.picture.width != 32 ||
792 m->data.picture.height != 32
795 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
797 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
798 if(metadata_picture_has_type2) /* there should only be 1 per stream */
799 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
800 metadata_picture_has_type2 = true;
805 encoder->private_->input_capacity = 0;
806 for(i = 0; i < encoder->protected_->channels; i++) {
807 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
808 #ifndef FLAC__INTEGER_ONLY_LIBRARY
809 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
812 for(i = 0; i < 2; i++) {
813 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
814 #ifndef FLAC__INTEGER_ONLY_LIBRARY
815 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
818 #ifndef FLAC__INTEGER_ONLY_LIBRARY
819 for(i = 0; i < encoder->protected_->num_apodizations; i++)
820 encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
821 encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
823 for(i = 0; i < encoder->protected_->channels; i++) {
824 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
825 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
826 encoder->private_->best_subframe[i] = 0;
828 for(i = 0; i < 2; i++) {
829 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
830 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
831 encoder->private_->best_subframe_mid_side[i] = 0;
833 encoder->private_->abs_residual_unaligned = encoder->private_->abs_residual = 0;
834 encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
835 encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
836 #ifndef FLAC__INTEGER_ONLY_LIBRARY
837 encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
839 /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
840 /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply÷ by hand */
841 FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
842 FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
843 FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
844 FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
845 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);
847 if(encoder->private_->loose_mid_side_stereo_frames == 0)
848 encoder->private_->loose_mid_side_stereo_frames = 1;
849 encoder->private_->loose_mid_side_stereo_frame_count = 0;
850 encoder->private_->current_sample_number = 0;
851 encoder->private_->current_frame_number = 0;
853 encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
854 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? */
855 encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
858 * get the CPU info and set the function pointers
860 FLAC__cpu_info(&encoder->private_->cpuinfo);
861 /* first default to the non-asm routines */
862 #ifndef FLAC__INTEGER_ONLY_LIBRARY
863 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
865 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
866 #ifndef FLAC__INTEGER_ONLY_LIBRARY
867 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
868 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
869 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
871 /* now override with asm where appropriate */
872 #ifndef FLAC__INTEGER_ONLY_LIBRARY
873 # ifndef FLAC__NO_ASM
874 if(encoder->private_->cpuinfo.use_asm) {
875 # ifdef FLAC__CPU_IA32
876 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
877 # ifdef FLAC__HAS_NASM
879 if(encoder->private_->cpuinfo.data.ia32.sse) {
880 if(encoder->protected_->max_lpc_order < 4)
881 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
882 else if(encoder->protected_->max_lpc_order < 8)
883 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
884 else if(encoder->protected_->max_lpc_order < 12)
885 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
887 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
890 # endif /* FLAC__SSE_OS */
891 if(encoder->private_->cpuinfo.data.ia32._3dnow)
892 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
894 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
895 if(encoder->private_->cpuinfo.data.ia32.mmx) {
896 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
897 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
900 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
901 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
903 if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
904 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
905 # endif /* FLAC__HAS_NASM */
906 # endif /* FLAC__CPU_IA32 */
908 # endif /* !FLAC__NO_ASM */
909 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
910 /* finally override based on wide-ness if necessary */
911 if(encoder->private_->use_wide_by_block) {
912 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
915 /* we require precompute_partition_sums if do_escape_coding because of their intertwined nature */
916 encoder->private_->precompute_partition_sums = (encoder->protected_->max_residual_partition_order > encoder->protected_->min_residual_partition_order) || encoder->protected_->do_escape_coding;
918 /* set state to OK; from here on, errors are fatal and we'll override the state then */
919 encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
921 encoder->private_->write_callback = write_callback;
922 encoder->private_->seek_callback = seek_callback;
923 encoder->private_->tell_callback = tell_callback;
924 encoder->private_->metadata_callback = metadata_callback;
925 encoder->private_->client_data = client_data;
927 if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
928 /* the above function sets the state for us in case of an error */
929 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
932 if(!FLAC__bitbuffer_init(encoder->private_->frame)) {
933 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
934 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
938 * Set up the verify stuff if necessary
940 if(encoder->protected_->verify) {
942 * First, set up the fifo which will hold the
943 * original signal to compare against
945 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize;
946 for(i = 0; i < encoder->protected_->channels; i++) {
947 if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder->private_->verify.input_fifo.size))) {
948 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
949 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
952 encoder->private_->verify.input_fifo.tail = 0;
955 * Now set up a stream decoder for verification
957 encoder->private_->verify.decoder = FLAC__stream_decoder_new();
958 if(0 == encoder->private_->verify.decoder) {
959 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
960 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
963 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) {
964 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
965 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
968 encoder->private_->verify.error_stats.absolute_sample = 0;
969 encoder->private_->verify.error_stats.frame_number = 0;
970 encoder->private_->verify.error_stats.channel = 0;
971 encoder->private_->verify.error_stats.sample = 0;
972 encoder->private_->verify.error_stats.expected = 0;
973 encoder->private_->verify.error_stats.got = 0;
976 * These must be done before we write any metadata, because that
977 * calls the write_callback, which uses these values.
979 encoder->private_->first_seekpoint_to_check = 0;
980 encoder->private_->samples_written = 0;
981 encoder->protected_->streaminfo_offset = 0;
982 encoder->protected_->seektable_offset = 0;
983 encoder->protected_->audio_offset = 0;
986 * write the stream header
988 if(encoder->protected_->verify)
989 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
990 if(!FLAC__bitbuffer_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
991 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
992 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
994 if(!write_bitbuffer_(encoder, 0)) {
995 /* the above function sets the state for us in case of an error */
996 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1000 * write the STREAMINFO metadata block
1002 if(encoder->protected_->verify)
1003 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1004 encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1005 encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1006 encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1007 encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1008 encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1009 encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1010 encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1011 encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1012 encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1013 encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1014 encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1015 memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1016 FLAC__MD5Init(&encoder->private_->md5context);
1017 if(!FLAC__bitbuffer_clear(encoder->private_->frame)) {
1018 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1019 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1021 if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1022 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1023 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1025 if(!write_bitbuffer_(encoder, 0)) {
1026 /* the above function sets the state for us in case of an error */
1027 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1031 * Now that the STREAMINFO block is written, we can init this to an
1032 * absurdly-high value...
1034 encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1035 /* ... and clear this to 0 */
1036 encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1039 * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1040 * if not, we will write an empty one (FLAC__add_metadata_block()
1041 * automatically supplies the vendor string).
1043 * WATCHOUT: libOggFLAC depends on us to write this block after the
1044 * STREAMINFO since that's what the mapping requires. (In the case
1045 * that metadata_has_vorbis_comment is true it will have already
1046 * insured that the metadata list is properly ordered.)
1048 if(!metadata_has_vorbis_comment) {
1049 FLAC__StreamMetadata vorbis_comment;
1050 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1051 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1052 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1053 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1054 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1055 vorbis_comment.data.vorbis_comment.num_comments = 0;
1056 vorbis_comment.data.vorbis_comment.comments = 0;
1057 if(!FLAC__bitbuffer_clear(encoder->private_->frame)) {
1058 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1059 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1061 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1062 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1063 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1065 if(!write_bitbuffer_(encoder, 0)) {
1066 /* the above function sets the state for us in case of an error */
1067 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1072 * write the user's metadata blocks
1074 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1075 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1076 if(!FLAC__bitbuffer_clear(encoder->private_->frame)) {
1077 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1078 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1080 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1081 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1082 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1084 if(!write_bitbuffer_(encoder, 0)) {
1085 /* the above function sets the state for us in case of an error */
1086 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1090 /* now that all the metadata is written, we save the stream offset */
1091 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 */
1092 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1093 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1096 if(encoder->protected_->verify)
1097 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1099 return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1102 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data)
1104 FLAC__StreamEncoderInitStatus init_status;
1106 FLAC__ASSERT(0 != encoder);
1107 FLAC__ASSERT(0 != file);
1110 * To make sure that our file does not go unclosed after an error, we
1111 * must assign the FILE pointer before any further error can occur in
1114 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1115 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1117 /* double protection */
1119 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1120 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1124 file = get_binary_stdout_(); /* just to be safe */
1126 encoder->private_->file = file;
1128 encoder->private_->progress_callback = progress_callback;
1129 encoder->private_->bytes_written = 0;
1130 encoder->private_->samples_written = 0;
1131 encoder->private_->frames_written = 0;
1133 init_status = FLAC__stream_encoder_init_stream(encoder, file_write_callback_, file_seek_callback_, file_tell_callback_, /*metadata_callback=*/0, client_data);
1134 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1135 /* the above function sets the state for us in case of an error */
1140 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1142 FLAC__ASSERT(blocksize != 0);
1143 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1149 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data)
1153 FLAC__ASSERT(0 != encoder);
1156 * To make sure that our file does not go unclosed after an error, we
1157 * have to do the same entrance checks here that are later performed
1158 * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1160 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1161 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1163 file = filename? fopen(filename, "w+b") : stdout;
1166 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1167 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1170 return FLAC__stream_encoder_init_FILE(encoder, file, progress_callback, client_data);
1173 FLAC_API void FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1175 FLAC__ASSERT(0 != encoder);
1176 FLAC__ASSERT(0 != encoder->private_);
1177 FLAC__ASSERT(0 != encoder->protected_);
1179 if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1182 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1183 if(encoder->private_->current_sample_number != 0) {
1184 encoder->protected_->blocksize = encoder->private_->current_sample_number;
1185 process_frame_(encoder, true); /* true => is last frame */
1189 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1191 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1192 if(encoder->private_->seek_callback)
1193 update_metadata_(encoder);
1194 if(encoder->private_->metadata_callback)
1195 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1198 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder)
1199 FLAC__stream_decoder_finish(encoder->private_->verify.decoder);
1201 if(0 != encoder->private_->file) {
1202 if(encoder->private_->file != stdout)
1203 fclose(encoder->private_->file);
1204 encoder->private_->file = 0;
1208 set_defaults_(encoder);
1210 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1213 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1215 FLAC__ASSERT(0 != encoder);
1216 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1218 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1219 encoder->protected_->verify = value;
1224 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1226 FLAC__ASSERT(0 != encoder);
1227 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1229 encoder->protected_->streamable_subset = value;
1233 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1235 FLAC__ASSERT(0 != encoder);
1236 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1238 encoder->protected_->do_mid_side_stereo = value;
1242 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_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_->loose_mid_side_stereo = value;
1251 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1253 FLAC__ASSERT(0 != encoder);
1254 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1256 encoder->protected_->channels = value;
1260 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1262 FLAC__ASSERT(0 != encoder);
1263 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1265 encoder->protected_->bits_per_sample = value;
1269 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1271 FLAC__ASSERT(0 != encoder);
1272 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1274 encoder->protected_->sample_rate = value;
1278 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1280 FLAC__ASSERT(0 != encoder);
1281 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1283 encoder->protected_->blocksize = value;
1287 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1289 FLAC__ASSERT(0 != encoder);
1290 FLAC__ASSERT(0 != specification);
1291 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1293 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1294 (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1296 encoder->protected_->num_apodizations = 0;
1298 const char *s = strchr(specification, ';');
1299 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1300 if (n==8 && 0 == strncmp("bartlett" , specification, n))
1301 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1302 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1303 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1304 else if(n==8 && 0 == strncmp("blackman" , specification, n))
1305 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1306 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1307 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1308 else if(n==6 && 0 == strncmp("connes" , specification, n))
1309 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1310 else if(n==7 && 0 == strncmp("flattop" , specification, n))
1311 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1312 else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
1313 FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1314 if (stddev > 0.0 && stddev <= 0.5) {
1315 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1316 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1319 else if(n==7 && 0 == strncmp("hamming" , specification, n))
1320 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1321 else if(n==4 && 0 == strncmp("hann" , specification, n))
1322 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1323 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1324 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1325 else if(n==7 && 0 == strncmp("nuttall" , specification, n))
1326 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1327 else if(n==9 && 0 == strncmp("rectangle" , specification, n))
1328 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1329 else if(n==8 && 0 == strncmp("triangle" , specification, n))
1330 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1331 else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
1332 FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1333 if (p >= 0.0 && p <= 1.0) {
1334 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1335 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1338 else if(n==5 && 0 == strncmp("welch" , specification, n))
1339 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1340 if (encoder->protected_->num_apodizations == 32)
1343 specification = s+1;
1347 if(encoder->protected_->num_apodizations == 0) {
1348 encoder->protected_->num_apodizations = 1;
1349 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1350 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1352 #ifdef WINDOW_DEBUG_OUTPUT
1353 {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]);}
1359 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1361 FLAC__ASSERT(0 != encoder);
1362 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1364 encoder->protected_->max_lpc_order = value;
1368 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1370 FLAC__ASSERT(0 != encoder);
1371 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1373 encoder->protected_->qlp_coeff_precision = value;
1377 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1379 FLAC__ASSERT(0 != encoder);
1380 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1382 encoder->protected_->do_qlp_coeff_prec_search = value;
1386 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1388 FLAC__ASSERT(0 != encoder);
1389 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1392 /*@@@ deprecated: */
1393 encoder->protected_->do_escape_coding = value;
1400 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1402 FLAC__ASSERT(0 != encoder);
1403 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1405 encoder->protected_->do_exhaustive_model_search = value;
1409 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1411 FLAC__ASSERT(0 != encoder);
1412 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1414 encoder->protected_->min_residual_partition_order = value;
1418 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_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_->max_residual_partition_order = value;
1427 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1429 FLAC__ASSERT(0 != encoder);
1430 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1433 /*@@@ deprecated: */
1434 encoder->protected_->rice_parameter_search_dist = value;
1441 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1443 FLAC__ASSERT(0 != encoder);
1444 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1446 encoder->protected_->total_samples_estimate = value;
1450 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1452 FLAC__ASSERT(0 != encoder);
1453 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1455 encoder->protected_->metadata = metadata;
1456 encoder->protected_->num_metadata_blocks = num_blocks;
1457 if(0 != metadata && num_blocks > 0) {
1459 for(i = 0; i < num_blocks; i++) {
1460 if(0 != metadata[i] && metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
1461 encoder->private_->seek_table = &metadata[i]->data.seek_table;
1462 break; /* take only the first one */
1470 * These three functions are not static, but not publically exposed in
1471 * include/FLAC/ either. They are used by the test suite.
1473 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1475 FLAC__ASSERT(0 != encoder);
1476 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1478 encoder->private_->disable_constant_subframes = value;
1482 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_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_fixed_subframes = value;
1491 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_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_verbatim_subframes = value;
1500 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1502 FLAC__ASSERT(0 != encoder);
1503 return encoder->protected_->state;
1506 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1508 FLAC__ASSERT(0 != encoder);
1509 if(encoder->protected_->verify)
1510 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1512 return FLAC__STREAM_DECODER_UNINITIALIZED;
1515 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1517 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1518 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1520 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1523 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)
1525 FLAC__ASSERT(0 != encoder);
1526 if(0 != absolute_sample)
1527 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1528 if(0 != frame_number)
1529 *frame_number = encoder->private_->verify.error_stats.frame_number;
1531 *channel = encoder->private_->verify.error_stats.channel;
1533 *sample = encoder->private_->verify.error_stats.sample;
1535 *expected = encoder->private_->verify.error_stats.expected;
1537 *got = encoder->private_->verify.error_stats.got;
1540 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1542 FLAC__ASSERT(0 != encoder);
1543 return encoder->protected_->verify;
1546 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1548 FLAC__ASSERT(0 != encoder);
1549 return encoder->protected_->streamable_subset;
1552 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1554 FLAC__ASSERT(0 != encoder);
1555 return encoder->protected_->do_mid_side_stereo;
1558 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1560 FLAC__ASSERT(0 != encoder);
1561 return encoder->protected_->loose_mid_side_stereo;
1564 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1566 FLAC__ASSERT(0 != encoder);
1567 return encoder->protected_->channels;
1570 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1572 FLAC__ASSERT(0 != encoder);
1573 return encoder->protected_->bits_per_sample;
1576 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1578 FLAC__ASSERT(0 != encoder);
1579 return encoder->protected_->sample_rate;
1582 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1584 FLAC__ASSERT(0 != encoder);
1585 return encoder->protected_->blocksize;
1588 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1590 FLAC__ASSERT(0 != encoder);
1591 return encoder->protected_->max_lpc_order;
1594 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1596 FLAC__ASSERT(0 != encoder);
1597 return encoder->protected_->qlp_coeff_precision;
1600 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1602 FLAC__ASSERT(0 != encoder);
1603 return encoder->protected_->do_qlp_coeff_prec_search;
1606 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1608 FLAC__ASSERT(0 != encoder);
1609 return encoder->protected_->do_escape_coding;
1612 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1614 FLAC__ASSERT(0 != encoder);
1615 return encoder->protected_->do_exhaustive_model_search;
1618 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1620 FLAC__ASSERT(0 != encoder);
1621 return encoder->protected_->min_residual_partition_order;
1624 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1626 FLAC__ASSERT(0 != encoder);
1627 return encoder->protected_->max_residual_partition_order;
1630 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1632 FLAC__ASSERT(0 != encoder);
1633 return encoder->protected_->rice_parameter_search_dist;
1636 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1638 FLAC__ASSERT(0 != encoder);
1639 return encoder->protected_->total_samples_estimate;
1642 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1644 unsigned i, j, channel;
1645 FLAC__int32 x, mid, side;
1646 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1648 FLAC__ASSERT(0 != encoder);
1649 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1653 * we have several flavors of the same basic loop, optimized for
1654 * different conditions:
1656 if(encoder->protected_->max_lpc_order > 0) {
1657 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1659 * stereo coding: unroll channel loop
1660 * with LPC: calculate floating point version of signal
1663 if(encoder->protected_->verify)
1664 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1666 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1667 x = mid = side = buffer[0][j];
1668 encoder->private_->integer_signal[0][i] = x;
1669 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1670 encoder->private_->real_signal[0][i] = (FLAC__real)x;
1673 encoder->private_->integer_signal[1][i] = x;
1674 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1675 encoder->private_->real_signal[1][i] = (FLAC__real)x;
1679 mid >>= 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
1680 encoder->private_->integer_signal_mid_side[1][i] = side;
1681 encoder->private_->integer_signal_mid_side[0][i] = mid;
1682 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1683 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
1684 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
1686 encoder->private_->current_sample_number++;
1688 if(i == blocksize) {
1689 if(!process_frame_(encoder, false)) /* false => not last frame */
1692 } while(j < samples);
1696 * independent channel coding: buffer each channel in inner loop
1697 * with LPC: calculate floating point version of signal
1700 if(encoder->protected_->verify)
1701 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1703 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1704 for(channel = 0; channel < channels; channel++) {
1705 x = buffer[channel][j];
1706 encoder->private_->integer_signal[channel][i] = x;
1707 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1708 encoder->private_->real_signal[channel][i] = (FLAC__real)x;
1711 encoder->private_->current_sample_number++;
1713 if(i == blocksize) {
1714 if(!process_frame_(encoder, false)) /* false => not last frame */
1717 } while(j < samples);
1721 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1723 * stereo coding: unroll channel loop
1724 * without LPC: no need to calculate floating point version of signal
1727 if(encoder->protected_->verify)
1728 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1730 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1731 encoder->private_->integer_signal[0][i] = mid = side = buffer[0][j];
1733 encoder->private_->integer_signal[1][i] = x;
1736 mid >>= 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
1737 encoder->private_->integer_signal_mid_side[1][i] = side;
1738 encoder->private_->integer_signal_mid_side[0][i] = mid;
1739 encoder->private_->current_sample_number++;
1741 if(i == blocksize) {
1742 if(!process_frame_(encoder, false)) /* false => not last frame */
1745 } while(j < samples);
1749 * independent channel coding: buffer each channel in inner loop
1750 * without LPC: no need to calculate floating point version of signal
1753 if(encoder->protected_->verify)
1754 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1756 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1757 for(channel = 0; channel < channels; channel++)
1758 encoder->private_->integer_signal[channel][i] = buffer[channel][j];
1759 encoder->private_->current_sample_number++;
1761 if(i == blocksize) {
1762 if(!process_frame_(encoder, false)) /* false => not last frame */
1765 } while(j < samples);
1772 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
1774 unsigned i, j, k, channel;
1775 FLAC__int32 x, mid, side;
1776 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1778 FLAC__ASSERT(0 != encoder);
1779 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1783 * we have several flavors of the same basic loop, optimized for
1784 * different conditions:
1786 if(encoder->protected_->max_lpc_order > 0) {
1787 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1789 * stereo coding: unroll channel loop
1790 * with LPC: calculate floating point version of signal
1793 if(encoder->protected_->verify)
1794 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1796 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1797 x = mid = side = buffer[k++];
1798 encoder->private_->integer_signal[0][i] = x;
1799 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1800 encoder->private_->real_signal[0][i] = (FLAC__real)x;
1803 encoder->private_->integer_signal[1][i] = x;
1804 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1805 encoder->private_->real_signal[1][i] = (FLAC__real)x;
1809 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
1810 encoder->private_->integer_signal_mid_side[1][i] = side;
1811 encoder->private_->integer_signal_mid_side[0][i] = mid;
1812 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1813 encoder->private_->real_signal_mid_side[1][i] = (FLAC__real)side;
1814 encoder->private_->real_signal_mid_side[0][i] = (FLAC__real)mid;
1816 encoder->private_->current_sample_number++;
1818 if(i == blocksize) {
1819 if(!process_frame_(encoder, false)) /* false => not last frame */
1822 } while(j < samples);
1826 * independent channel coding: buffer each channel in inner loop
1827 * with LPC: calculate floating point version of signal
1830 if(encoder->protected_->verify)
1831 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1833 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1834 for(channel = 0; channel < channels; channel++) {
1836 encoder->private_->integer_signal[channel][i] = x;
1837 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1838 encoder->private_->real_signal[channel][i] = (FLAC__real)x;
1841 encoder->private_->current_sample_number++;
1843 if(i == blocksize) {
1844 if(!process_frame_(encoder, false)) /* false => not last frame */
1847 } while(j < samples);
1851 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
1853 * stereo coding: unroll channel loop
1854 * without LPC: no need to calculate floating point version of signal
1857 if(encoder->protected_->verify)
1858 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1860 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1861 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
1863 encoder->private_->integer_signal[1][i] = x;
1866 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
1867 encoder->private_->integer_signal_mid_side[1][i] = side;
1868 encoder->private_->integer_signal_mid_side[0][i] = mid;
1869 encoder->private_->current_sample_number++;
1871 if(i == blocksize) {
1872 if(!process_frame_(encoder, false)) /* false => not last frame */
1875 } while(j < samples);
1879 * independent channel coding: buffer each channel in inner loop
1880 * without LPC: no need to calculate floating point version of signal
1883 if(encoder->protected_->verify)
1884 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
1886 for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
1887 for(channel = 0; channel < channels; channel++)
1888 encoder->private_->integer_signal[channel][i] = buffer[k++];
1889 encoder->private_->current_sample_number++;
1891 if(i == blocksize) {
1892 if(!process_frame_(encoder, false)) /* false => not last frame */
1895 } while(j < samples);
1902 /***********************************************************************
1904 * Private class methods
1906 ***********************************************************************/
1908 void set_defaults_(FLAC__StreamEncoder *encoder)
1910 FLAC__ASSERT(0 != encoder);
1912 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1913 encoder->protected_->verify = true;
1915 encoder->protected_->verify = false;
1917 encoder->protected_->streamable_subset = true;
1918 encoder->protected_->do_mid_side_stereo = false;
1919 encoder->protected_->loose_mid_side_stereo = false;
1920 encoder->protected_->channels = 2;
1921 encoder->protected_->bits_per_sample = 16;
1922 encoder->protected_->sample_rate = 44100;
1923 encoder->protected_->blocksize = 1152;
1924 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1925 encoder->protected_->num_apodizations = 1;
1926 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1927 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1929 encoder->protected_->max_lpc_order = 0;
1930 encoder->protected_->qlp_coeff_precision = 0;
1931 encoder->protected_->do_qlp_coeff_prec_search = false;
1932 encoder->protected_->do_exhaustive_model_search = false;
1933 encoder->protected_->do_escape_coding = false;
1934 encoder->protected_->min_residual_partition_order = 0;
1935 encoder->protected_->max_residual_partition_order = 0;
1936 encoder->protected_->rice_parameter_search_dist = 0;
1937 encoder->protected_->total_samples_estimate = 0;
1938 encoder->protected_->metadata = 0;
1939 encoder->protected_->num_metadata_blocks = 0;
1941 encoder->private_->seek_table = 0;
1942 encoder->private_->disable_constant_subframes = false;
1943 encoder->private_->disable_fixed_subframes = false;
1944 encoder->private_->disable_verbatim_subframes = false;
1945 encoder->private_->write_callback = 0;
1946 encoder->private_->seek_callback = 0;
1947 encoder->private_->tell_callback = 0;
1948 encoder->private_->metadata_callback = 0;
1949 encoder->private_->progress_callback = 0;
1950 encoder->private_->client_data = 0;
1953 void free_(FLAC__StreamEncoder *encoder)
1955 unsigned i, channel;
1957 FLAC__ASSERT(0 != encoder);
1958 for(i = 0; i < encoder->protected_->channels; i++) {
1959 if(0 != encoder->private_->integer_signal_unaligned[i]) {
1960 free(encoder->private_->integer_signal_unaligned[i]);
1961 encoder->private_->integer_signal_unaligned[i] = 0;
1963 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1964 if(0 != encoder->private_->real_signal_unaligned[i]) {
1965 free(encoder->private_->real_signal_unaligned[i]);
1966 encoder->private_->real_signal_unaligned[i] = 0;
1970 for(i = 0; i < 2; i++) {
1971 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
1972 free(encoder->private_->integer_signal_mid_side_unaligned[i]);
1973 encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
1975 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1976 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
1977 free(encoder->private_->real_signal_mid_side_unaligned[i]);
1978 encoder->private_->real_signal_mid_side_unaligned[i] = 0;
1982 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1983 for(i = 0; i < encoder->protected_->num_apodizations; i++) {
1984 if(0 != encoder->private_->window_unaligned[i]) {
1985 free(encoder->private_->window_unaligned[i]);
1986 encoder->private_->window_unaligned[i] = 0;
1989 if(0 != encoder->private_->windowed_signal_unaligned) {
1990 free(encoder->private_->windowed_signal_unaligned);
1991 encoder->private_->windowed_signal_unaligned = 0;
1994 for(channel = 0; channel < encoder->protected_->channels; channel++) {
1995 for(i = 0; i < 2; i++) {
1996 if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
1997 free(encoder->private_->residual_workspace_unaligned[channel][i]);
1998 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2002 for(channel = 0; channel < 2; channel++) {
2003 for(i = 0; i < 2; i++) {
2004 if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2005 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2006 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2010 if(0 != encoder->private_->abs_residual_unaligned) {
2011 free(encoder->private_->abs_residual_unaligned);
2012 encoder->private_->abs_residual_unaligned = 0;
2014 if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2015 free(encoder->private_->abs_residual_partition_sums_unaligned);
2016 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2018 if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2019 free(encoder->private_->raw_bits_per_partition_unaligned);
2020 encoder->private_->raw_bits_per_partition_unaligned = 0;
2022 if(encoder->protected_->verify) {
2023 for(i = 0; i < encoder->protected_->channels; i++) {
2024 if(0 != encoder->private_->verify.input_fifo.data[i]) {
2025 free(encoder->private_->verify.input_fifo.data[i]);
2026 encoder->private_->verify.input_fifo.data[i] = 0;
2030 FLAC__bitbuffer_free(encoder->private_->frame);
2033 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_size)
2036 unsigned i, channel;
2038 FLAC__ASSERT(new_size > 0);
2039 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2040 FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2042 /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2043 if(new_size <= encoder->private_->input_capacity)
2048 /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
2049 * requires that the input arrays (in our case the integer signals)
2050 * have a buffer of up to 3 zeroes in front (at negative indices) for
2051 * alignment purposes; we use 4 to keep the data well-aligned.
2054 for(i = 0; ok && i < encoder->protected_->channels; i++) {
2055 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size+4, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2056 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2057 if(encoder->protected_->max_lpc_order > 0)
2058 ok = ok && FLAC__memory_alloc_aligned_real_array(new_size, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2060 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2061 encoder->private_->integer_signal[i] += 4;
2063 for(i = 0; ok && i < 2; i++) {
2064 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]);
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_mid_side_unaligned[i], &encoder->private_->real_signal_mid_side[i]);
2069 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2070 encoder->private_->integer_signal_mid_side[i] += 4;
2072 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2073 if(ok && encoder->protected_->max_lpc_order > 0) {
2074 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2075 ok = ok && FLAC__memory_alloc_aligned_real_array(new_size, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2076 ok = ok && FLAC__memory_alloc_aligned_real_array(new_size, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2079 for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2080 for(i = 0; ok && i < 2; i++) {
2081 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2084 for(channel = 0; ok && channel < 2; channel++) {
2085 for(i = 0; ok && i < 2; i++) {
2086 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]);
2089 ok = ok && FLAC__memory_alloc_aligned_uint32_array(new_size, &encoder->private_->abs_residual_unaligned, &encoder->private_->abs_residual);
2090 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 */
2091 ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_size * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2092 if(encoder->protected_->do_escape_coding)
2093 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_size * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2096 encoder->private_->input_capacity = new_size;
2098 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2100 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2101 if(ok && encoder->protected_->max_lpc_order > 0) {
2102 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2103 switch(encoder->protected_->apodizations[i].type) {
2104 case FLAC__APODIZATION_BARTLETT:
2105 FLAC__window_bartlett(encoder->private_->window[i], new_size);
2107 case FLAC__APODIZATION_BARTLETT_HANN:
2108 FLAC__window_bartlett_hann(encoder->private_->window[i], new_size);
2110 case FLAC__APODIZATION_BLACKMAN:
2111 FLAC__window_blackman(encoder->private_->window[i], new_size);
2113 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2114 FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_size);
2116 case FLAC__APODIZATION_CONNES:
2117 FLAC__window_connes(encoder->private_->window[i], new_size);
2119 case FLAC__APODIZATION_FLATTOP:
2120 FLAC__window_flattop(encoder->private_->window[i], new_size);
2122 case FLAC__APODIZATION_GAUSS:
2123 FLAC__window_gauss(encoder->private_->window[i], new_size, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2125 case FLAC__APODIZATION_HAMMING:
2126 FLAC__window_hamming(encoder->private_->window[i], new_size);
2128 case FLAC__APODIZATION_HANN:
2129 FLAC__window_hann(encoder->private_->window[i], new_size);
2131 case FLAC__APODIZATION_KAISER_BESSEL:
2132 FLAC__window_kaiser_bessel(encoder->private_->window[i], new_size);
2134 case FLAC__APODIZATION_NUTTALL:
2135 FLAC__window_nuttall(encoder->private_->window[i], new_size);
2137 case FLAC__APODIZATION_RECTANGLE:
2138 FLAC__window_rectangle(encoder->private_->window[i], new_size);
2140 case FLAC__APODIZATION_TRIANGLE:
2141 FLAC__window_triangle(encoder->private_->window[i], new_size);
2143 case FLAC__APODIZATION_TUKEY:
2144 FLAC__window_tukey(encoder->private_->window[i], new_size, encoder->protected_->apodizations[i].parameters.tukey.p);
2146 case FLAC__APODIZATION_WELCH:
2147 FLAC__window_welch(encoder->private_->window[i], new_size);
2151 /* double protection */
2152 FLAC__window_hann(encoder->private_->window[i], new_size);
2162 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples)
2164 const FLAC__byte *buffer;
2167 FLAC__ASSERT(FLAC__bitbuffer_is_byte_aligned(encoder->private_->frame));
2169 FLAC__bitbuffer_get_buffer(encoder->private_->frame, &buffer, &bytes);
2171 if(encoder->protected_->verify) {
2172 encoder->private_->verify.output.data = buffer;
2173 encoder->private_->verify.output.bytes = bytes;
2174 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2175 encoder->private_->verify.needs_magic_hack = true;
2178 if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2179 FLAC__bitbuffer_release_buffer(encoder->private_->frame);
2180 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2181 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2187 if(write_frame_(encoder, buffer, bytes, samples) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2188 FLAC__bitbuffer_release_buffer(encoder->private_->frame);
2189 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2193 FLAC__bitbuffer_release_buffer(encoder->private_->frame);
2196 encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2197 encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2203 FLAC__StreamEncoderWriteStatus write_frame_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples)
2205 FLAC__StreamEncoderWriteStatus status;
2206 FLAC__uint64 output_position = 0;
2208 /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2209 if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2210 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2211 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2215 * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2218 FLAC__MetadataType type = (buffer[0] & 0x7f);
2219 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2220 encoder->protected_->streaminfo_offset = output_position;
2221 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2222 encoder->protected_->seektable_offset = output_position;
2226 * Mark the current seek point if hit (if audio_offset == 0 that
2227 * means we're still writing metadata and haven't hit the first
2230 if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2231 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2232 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2233 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2234 FLAC__uint64 test_sample;
2236 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2237 test_sample = encoder->private_->seek_table->points[i].sample_number;
2238 if(test_sample > frame_last_sample) {
2241 else if(test_sample >= frame_first_sample) {
2242 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2243 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2244 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2245 encoder->private_->first_seekpoint_to_check++;
2246 /* DO NOT: "break;" and here's why:
2247 * The seektable template may contain more than one target
2248 * sample for any given frame; we will keep looping, generating
2249 * duplicate seekpoints for them, and we'll clean it up later,
2250 * just before writing the seektable back to the metadata.
2254 encoder->private_->first_seekpoint_to_check++;
2259 status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2261 if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2262 encoder->private_->bytes_written += bytes;
2263 encoder->private_->samples_written += samples;
2264 /* we keep a high watermark on the number of frames written because
2265 * when the encoder goes back to write metadata, 'current_frame'
2266 * will drop back to 0.
2268 encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2271 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2276 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2277 void update_metadata_(const FLAC__StreamEncoder *encoder)
2279 FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2280 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2281 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2282 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2283 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2284 const unsigned bps = metadata->data.stream_info.bits_per_sample;
2285 FLAC__StreamEncoderSeekStatus seek_status;
2287 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2289 /* All this is based on intimate knowledge of the stream header
2290 * layout, but a change to the header format that would break this
2291 * would also break all streams encoded in the previous format.
2295 * Write MD5 signature
2298 const unsigned md5_offset =
2299 FLAC__STREAM_METADATA_HEADER_LENGTH +
2301 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2302 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2303 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2304 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2305 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2306 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2307 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2308 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2311 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2312 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2313 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2316 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2317 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2323 * Write total samples
2326 const unsigned total_samples_byte_offset =
2327 FLAC__STREAM_METADATA_HEADER_LENGTH +
2329 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2330 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2331 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2332 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2333 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2334 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2335 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2339 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2340 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2341 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2342 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2343 b[4] = (FLAC__byte)(samples & 0xFF);
2344 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) {
2345 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2346 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2349 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2350 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2356 * Write min/max framesize
2359 const unsigned min_framesize_offset =
2360 FLAC__STREAM_METADATA_HEADER_LENGTH +
2362 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2363 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2366 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2367 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2368 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2369 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2370 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2371 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2372 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) {
2373 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2374 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2377 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2378 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2386 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2389 FLAC__format_seektable_sort(encoder->private_->seek_table);
2391 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2393 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) {
2394 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2395 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2399 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2402 xx = encoder->private_->seek_table->points[i].sample_number;
2403 b[7] = (FLAC__byte)xx; xx >>= 8;
2404 b[6] = (FLAC__byte)xx; xx >>= 8;
2405 b[5] = (FLAC__byte)xx; xx >>= 8;
2406 b[4] = (FLAC__byte)xx; xx >>= 8;
2407 b[3] = (FLAC__byte)xx; xx >>= 8;
2408 b[2] = (FLAC__byte)xx; xx >>= 8;
2409 b[1] = (FLAC__byte)xx; xx >>= 8;
2410 b[0] = (FLAC__byte)xx; xx >>= 8;
2411 xx = encoder->private_->seek_table->points[i].stream_offset;
2412 b[15] = (FLAC__byte)xx; xx >>= 8;
2413 b[14] = (FLAC__byte)xx; xx >>= 8;
2414 b[13] = (FLAC__byte)xx; xx >>= 8;
2415 b[12] = (FLAC__byte)xx; xx >>= 8;
2416 b[11] = (FLAC__byte)xx; xx >>= 8;
2417 b[10] = (FLAC__byte)xx; xx >>= 8;
2418 b[9] = (FLAC__byte)xx; xx >>= 8;
2419 b[8] = (FLAC__byte)xx; xx >>= 8;
2420 x = encoder->private_->seek_table->points[i].frame_samples;
2421 b[17] = (FLAC__byte)x; x >>= 8;
2422 b[16] = (FLAC__byte)x; x >>= 8;
2423 if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2424 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2431 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame)
2433 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2436 * Accumulate raw signal to the MD5 signature
2438 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)) {
2439 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2444 * Process the frame header and subframes into the frame bitbuffer
2446 if(!process_subframes_(encoder, is_last_frame)) {
2447 /* the above function sets the state for us in case of an error */
2452 * Zero-pad the frame to a byte_boundary
2454 if(!FLAC__bitbuffer_zero_pad_to_byte_boundary(encoder->private_->frame)) {
2455 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2460 * CRC-16 the whole thing
2462 FLAC__ASSERT(FLAC__bitbuffer_is_byte_aligned(encoder->private_->frame));
2463 FLAC__bitbuffer_write_raw_uint32(encoder->private_->frame, FLAC__bitbuffer_get_write_crc16(encoder->private_->frame), FLAC__FRAME_FOOTER_CRC_LEN);
2468 if(!write_bitbuffer_(encoder, encoder->protected_->blocksize)) {
2469 /* the above function sets the state for us in case of an error */
2474 * Get ready for the next frame
2476 encoder->private_->current_sample_number = 0;
2477 encoder->private_->current_frame_number++;
2478 encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
2483 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame)
2485 FLAC__FrameHeader frame_header;
2486 unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
2487 FLAC__bool do_independent, do_mid_side, precompute_partition_sums;
2490 * Calculate the min,max Rice partition orders
2493 max_partition_order = 0;
2496 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
2497 max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
2499 min_partition_order = min(min_partition_order, max_partition_order);
2501 precompute_partition_sums = encoder->private_->precompute_partition_sums && ((max_partition_order > min_partition_order) || encoder->protected_->do_escape_coding);
2506 if(!FLAC__bitbuffer_clear(encoder->private_->frame)) {
2507 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2510 frame_header.blocksize = encoder->protected_->blocksize;
2511 frame_header.sample_rate = encoder->protected_->sample_rate;
2512 frame_header.channels = encoder->protected_->channels;
2513 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
2514 frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
2515 frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2516 frame_header.number.frame_number = encoder->private_->current_frame_number;
2519 * Figure out what channel assignments to try
2521 if(encoder->protected_->do_mid_side_stereo) {
2522 if(encoder->protected_->loose_mid_side_stereo) {
2523 if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
2524 do_independent = true;
2528 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
2529 do_mid_side = !do_independent;
2533 do_independent = true;
2538 do_independent = true;
2539 do_mid_side = false;
2542 FLAC__ASSERT(do_independent || do_mid_side);
2545 * Check for wasted bits; set effective bps for each subframe
2547 if(do_independent) {
2548 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2549 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
2550 encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
2551 encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
2555 FLAC__ASSERT(encoder->protected_->channels == 2);
2556 for(channel = 0; channel < 2; channel++) {
2557 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
2558 encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
2559 encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
2564 * First do a normal encoding pass of each independent channel
2566 if(do_independent) {
2567 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2571 min_partition_order,
2572 max_partition_order,
2573 precompute_partition_sums,
2575 encoder->private_->subframe_bps[channel],
2576 encoder->private_->integer_signal[channel],
2577 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2578 encoder->private_->real_signal[channel],
2580 encoder->private_->subframe_workspace_ptr[channel],
2581 encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
2582 encoder->private_->residual_workspace[channel],
2583 encoder->private_->best_subframe+channel,
2584 encoder->private_->best_subframe_bits+channel
2585 #ifdef WINDOW_DEBUG_OUTPUT
2595 * Now do mid and side channels if requested
2598 FLAC__ASSERT(encoder->protected_->channels == 2);
2600 for(channel = 0; channel < 2; channel++) {
2604 min_partition_order,
2605 max_partition_order,
2606 precompute_partition_sums,
2608 encoder->private_->subframe_bps_mid_side[channel],
2609 encoder->private_->integer_signal_mid_side[channel],
2610 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2611 encoder->private_->real_signal_mid_side[channel],
2613 encoder->private_->subframe_workspace_ptr_mid_side[channel],
2614 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
2615 encoder->private_->residual_workspace_mid_side[channel],
2616 encoder->private_->best_subframe_mid_side+channel,
2617 encoder->private_->best_subframe_bits_mid_side+channel
2618 #ifdef WINDOW_DEBUG_OUTPUT
2628 * Compose the frame bitbuffer
2631 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
2632 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
2633 FLAC__ChannelAssignment channel_assignment;
2634 #ifdef WINDOW_DEBUG_OUTPUT
2635 unsigned left_bits = 0, right_bits = 0;
2638 FLAC__ASSERT(encoder->protected_->channels == 2);
2640 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
2641 channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
2644 unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
2646 FLAC__ChannelAssignment ca;
2648 FLAC__ASSERT(do_independent && do_mid_side);
2650 /* We have to figure out which channel assignent results in the smallest frame */
2651 bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
2652 bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
2653 bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
2654 bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
2656 for(channel_assignment = (FLAC__ChannelAssignment)0, min_bits = bits[0], ca = (FLAC__ChannelAssignment)1; (int)ca <= 3; ca = (FLAC__ChannelAssignment)((int)ca + 1)) {
2657 if(bits[ca] < min_bits) {
2658 min_bits = bits[ca];
2659 channel_assignment = ca;
2664 frame_header.channel_assignment = channel_assignment;
2666 if(!FLAC__frame_add_header(&frame_header, encoder->protected_->streamable_subset, encoder->private_->frame)) {
2667 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
2671 switch(channel_assignment) {
2672 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2673 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
2674 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
2675 #ifdef WINDOW_DEBUG_OUTPUT
2676 left_bits = encoder->private_->best_subframe_bits [0];
2677 right_bits = encoder->private_->best_subframe_bits [1];
2680 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2681 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
2682 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
2683 #ifdef WINDOW_DEBUG_OUTPUT
2684 left_bits = encoder->private_->best_subframe_bits [0];
2685 right_bits = encoder->private_->best_subframe_bits_mid_side [1];
2688 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2689 left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
2690 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
2691 #ifdef WINDOW_DEBUG_OUTPUT
2692 left_bits = encoder->private_->best_subframe_bits_mid_side [1];
2693 right_bits = encoder->private_->best_subframe_bits [1];
2696 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2697 left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
2698 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
2699 #ifdef WINDOW_DEBUG_OUTPUT
2700 left_bits = encoder->private_->best_subframe_bits_mid_side [0];
2701 right_bits = encoder->private_->best_subframe_bits_mid_side [1];
2708 switch(channel_assignment) {
2709 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2710 left_bps = encoder->private_->subframe_bps [0];
2711 right_bps = encoder->private_->subframe_bps [1];
2713 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2714 left_bps = encoder->private_->subframe_bps [0];
2715 right_bps = encoder->private_->subframe_bps_mid_side[1];
2717 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2718 left_bps = encoder->private_->subframe_bps_mid_side[1];
2719 right_bps = encoder->private_->subframe_bps [1];
2721 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2722 left_bps = encoder->private_->subframe_bps_mid_side[0];
2723 right_bps = encoder->private_->subframe_bps_mid_side[1];
2729 /* note that encoder_add_subframe_ sets the state for us in case of an error */
2730 #ifdef WINDOW_DEBUG_OUTPUT
2731 if(!add_subframe_(encoder, &frame_header, left_bps , left_subframe , encoder->private_->frame, left_bits))
2733 if(!add_subframe_(encoder, &frame_header, right_bps, right_subframe, encoder->private_->frame, right_bits))
2736 if(!add_subframe_(encoder, &frame_header, left_bps , left_subframe , encoder->private_->frame))
2738 if(!add_subframe_(encoder, &frame_header, right_bps, right_subframe, encoder->private_->frame))
2743 if(!FLAC__frame_add_header(&frame_header, encoder->protected_->streamable_subset, encoder->private_->frame)) {
2744 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
2748 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2749 #ifdef WINDOW_DEBUG_OUTPUT
2750 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]))
2752 if(!add_subframe_(encoder, &frame_header, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame))
2755 /* the above function sets the state for us in case of an error */
2761 if(encoder->protected_->loose_mid_side_stereo) {
2762 encoder->private_->loose_mid_side_stereo_frame_count++;
2763 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
2764 encoder->private_->loose_mid_side_stereo_frame_count = 0;
2767 encoder->private_->last_channel_assignment = frame_header.channel_assignment;
2772 FLAC__bool process_subframe_(
2773 FLAC__StreamEncoder *encoder,
2774 unsigned min_partition_order,
2775 unsigned max_partition_order,
2776 FLAC__bool precompute_partition_sums,
2777 const FLAC__FrameHeader *frame_header,
2778 unsigned subframe_bps,
2779 const FLAC__int32 integer_signal[],
2780 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2781 const FLAC__real real_signal[],
2783 FLAC__Subframe *subframe[2],
2784 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
2785 FLAC__int32 *residual[2],
2786 unsigned *best_subframe,
2788 #ifdef WINDOW_DEBUG_OUTPUT
2789 ,unsigned subframe_number
2793 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2794 FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
2796 FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
2798 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2799 FLAC__double lpc_residual_bits_per_sample;
2800 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 */
2801 FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
2802 unsigned min_lpc_order, max_lpc_order, lpc_order;
2803 unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
2805 unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
2806 unsigned rice_parameter;
2807 unsigned _candidate_bits, _best_bits;
2808 unsigned _best_subframe;
2810 /* verbatim subframe is the baseline against which we measure other compressed subframes */
2812 if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
2813 _best_bits = UINT_MAX;
2815 _best_bits = evaluate_verbatim_subframe_(integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
2817 if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
2818 unsigned signal_is_constant = false;
2819 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);
2820 /* check for constant subframe */
2822 !encoder->private_->disable_constant_subframes &&
2823 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2824 fixed_residual_bits_per_sample[1] == 0.0
2826 fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
2829 /* the above means it's possible all samples are the same value; now double-check it: */
2831 signal_is_constant = true;
2832 for(i = 1; i < frame_header->blocksize; i++) {
2833 if(integer_signal[0] != integer_signal[i]) {
2834 signal_is_constant = false;
2839 if(signal_is_constant) {
2840 _candidate_bits = evaluate_constant_subframe_(integer_signal[0], subframe_bps, subframe[!_best_subframe]);
2841 if(_candidate_bits < _best_bits) {
2842 _best_subframe = !_best_subframe;
2843 _best_bits = _candidate_bits;
2847 if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
2849 if(encoder->protected_->do_exhaustive_model_search) {
2850 min_fixed_order = 0;
2851 max_fixed_order = FLAC__MAX_FIXED_ORDER;
2854 min_fixed_order = max_fixed_order = guess_fixed_order;
2856 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
2857 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2858 if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
2859 continue; /* don't even try */
2860 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 */
2862 if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
2863 continue; /* don't even try */
2864 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 */
2866 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
2867 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2868 #ifdef DEBUG_VERBOSE
2869 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2871 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2874 evaluate_fixed_subframe_(
2877 residual[!_best_subframe],
2878 encoder->private_->abs_residual,
2879 encoder->private_->abs_residual_partition_sums,
2880 encoder->private_->raw_bits_per_partition,
2881 frame_header->blocksize,
2885 min_partition_order,
2886 max_partition_order,
2887 precompute_partition_sums,
2888 encoder->protected_->do_escape_coding,
2889 encoder->protected_->rice_parameter_search_dist,
2890 subframe[!_best_subframe],
2891 partitioned_rice_contents[!_best_subframe]
2893 if(_candidate_bits < _best_bits) {
2894 _best_subframe = !_best_subframe;
2895 _best_bits = _candidate_bits;
2900 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2902 if(encoder->protected_->max_lpc_order > 0) {
2903 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
2904 max_lpc_order = frame_header->blocksize-1;
2906 max_lpc_order = encoder->protected_->max_lpc_order;
2907 if(max_lpc_order > 0) {
2909 for (a = 0; a < encoder->protected_->num_apodizations; a++) {
2910 FLAC__lpc_window_data(real_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
2911 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
2912 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
2913 if(autoc[0] != 0.0) {
2914 FLAC__lpc_compute_lp_coefficients(autoc, max_lpc_order, encoder->private_->lp_coeff, lpc_error);
2915 if(encoder->protected_->do_exhaustive_model_search) {
2919 const unsigned guess_lpc_order =
2920 FLAC__lpc_compute_best_order(
2923 frame_header->blocksize,
2925 encoder->protected_->do_qlp_coeff_prec_search?
2926 FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
2927 encoder->protected_->qlp_coeff_precision
2930 min_lpc_order = max_lpc_order = guess_lpc_order;
2932 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
2933 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
2934 if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
2935 continue; /* don't even try */
2936 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
2937 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
2938 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2939 #ifdef DEBUG_VERBOSE
2940 fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2942 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2944 if(encoder->protected_->do_qlp_coeff_prec_search) {
2945 min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
2946 /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
2947 if(subframe_bps <= 17) {
2948 max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
2949 max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
2952 max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
2955 min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
2957 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
2959 evaluate_lpc_subframe_(
2962 residual[!_best_subframe],
2963 encoder->private_->abs_residual,
2964 encoder->private_->abs_residual_partition_sums,
2965 encoder->private_->raw_bits_per_partition,
2966 encoder->private_->lp_coeff[lpc_order-1],
2967 frame_header->blocksize,
2970 qlp_coeff_precision,
2972 min_partition_order,
2973 max_partition_order,
2974 precompute_partition_sums,
2975 encoder->protected_->do_escape_coding,
2976 encoder->protected_->rice_parameter_search_dist,
2977 subframe[!_best_subframe],
2978 partitioned_rice_contents[!_best_subframe]
2979 #ifdef WINDOW_DEBUG_OUTPUT
2980 ,frame_header->number.frame_number
2982 ,encoder->protected_->apodizations[a]
2985 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
2986 if(_candidate_bits < _best_bits) {
2987 _best_subframe = !_best_subframe;
2988 _best_bits = _candidate_bits;
2997 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3001 /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3002 if(_best_bits == UINT_MAX) {
3003 FLAC__ASSERT(_best_subframe == 0);
3004 _best_bits = evaluate_verbatim_subframe_(integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3007 *best_subframe = _best_subframe;
3008 *best_bits = _best_bits;
3013 FLAC__bool add_subframe_(
3014 FLAC__StreamEncoder *encoder,
3015 const FLAC__FrameHeader *frame_header,
3016 unsigned subframe_bps,
3017 const FLAC__Subframe *subframe,
3018 FLAC__BitBuffer *frame
3019 #ifdef WINDOW_DEBUG_OUTPUT
3020 ,unsigned subframe_bits
3024 switch(subframe->type) {
3025 case FLAC__SUBFRAME_TYPE_CONSTANT:
3026 if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3027 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3031 case FLAC__SUBFRAME_TYPE_FIXED:
3032 if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), frame_header->blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3033 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3037 case FLAC__SUBFRAME_TYPE_LPC:
3038 #ifdef WINDOW_DEBUG_OUTPUT
3039 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);
3041 if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), frame_header->blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3042 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3046 case FLAC__SUBFRAME_TYPE_VERBATIM:
3047 if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), frame_header->blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3048 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3059 unsigned evaluate_constant_subframe_(
3060 const FLAC__int32 signal,
3061 unsigned subframe_bps,
3062 FLAC__Subframe *subframe
3065 subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3066 subframe->data.constant.value = signal;
3068 return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe_bps;
3071 unsigned evaluate_fixed_subframe_(
3072 FLAC__StreamEncoder *encoder,
3073 const FLAC__int32 signal[],
3074 FLAC__int32 residual[],
3075 FLAC__uint32 abs_residual[],
3076 FLAC__uint64 abs_residual_partition_sums[],
3077 unsigned raw_bits_per_partition[],
3079 unsigned subframe_bps,
3081 unsigned rice_parameter,
3082 unsigned min_partition_order,
3083 unsigned max_partition_order,
3084 FLAC__bool precompute_partition_sums,
3085 FLAC__bool do_escape_coding,
3086 unsigned rice_parameter_search_dist,
3087 FLAC__Subframe *subframe,
3088 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3091 unsigned i, residual_bits;
3092 const unsigned residual_samples = blocksize - order;
3094 FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3096 subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3098 subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3099 subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3100 subframe->data.fixed.residual = residual;
3103 find_best_partition_order_(
3107 abs_residual_partition_sums,
3108 raw_bits_per_partition,
3112 min_partition_order,
3113 max_partition_order,
3114 precompute_partition_sums,
3116 rice_parameter_search_dist,
3117 &subframe->data.fixed.entropy_coding_method.data.partitioned_rice
3120 subframe->data.fixed.order = order;
3121 for(i = 0; i < order; i++)
3122 subframe->data.fixed.warmup[i] = signal[i];
3124 return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (order * subframe_bps) + residual_bits;
3127 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3128 unsigned evaluate_lpc_subframe_(
3129 FLAC__StreamEncoder *encoder,
3130 const FLAC__int32 signal[],
3131 FLAC__int32 residual[],
3132 FLAC__uint32 abs_residual[],
3133 FLAC__uint64 abs_residual_partition_sums[],
3134 unsigned raw_bits_per_partition[],
3135 const FLAC__real lp_coeff[],
3137 unsigned subframe_bps,
3139 unsigned qlp_coeff_precision,
3140 unsigned rice_parameter,
3141 unsigned min_partition_order,
3142 unsigned max_partition_order,
3143 FLAC__bool precompute_partition_sums,
3144 FLAC__bool do_escape_coding,
3145 unsigned rice_parameter_search_dist,
3146 FLAC__Subframe *subframe,
3147 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3148 #ifdef WINDOW_DEBUG_OUTPUT
3149 ,unsigned frame_number
3150 ,unsigned subframe_number
3151 ,FLAC__ApodizationSpecification aspec
3155 FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
3156 unsigned i, residual_bits;
3157 int quantization, ret;
3158 const unsigned residual_samples = blocksize - order;
3160 /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3161 if(subframe_bps <= 16) {
3162 FLAC__ASSERT(order > 0);
3163 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3164 qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3167 #ifdef WINDOW_DEBUG_OUTPUT
3168 if (aspec.type == FLAC__APODIZATION_GAUSS)
3169 snprintf(subframe->data.lpc.window_type, sizeof subframe->data.lpc.window_type, "%s(%0.5f)", winstr[aspec.type], aspec.parameters.gauss.stddev);
3170 else if (aspec.type == FLAC__APODIZATION_TUKEY)
3171 snprintf(subframe->data.lpc.window_type, sizeof subframe->data.lpc.window_type, "%s(%0.5f)", winstr[aspec.type], aspec.parameters.tukey.p);
3173 strncpy(subframe->data.lpc.window_type, winstr[aspec.type], sizeof subframe->data.lpc.window_type);
3176 ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3178 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3180 if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3181 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3182 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3184 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3186 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3188 subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3190 subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3191 subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3192 subframe->data.lpc.residual = residual;
3195 find_best_partition_order_(
3199 abs_residual_partition_sums,
3200 raw_bits_per_partition,
3204 min_partition_order,
3205 max_partition_order,
3206 precompute_partition_sums,
3208 rice_parameter_search_dist,
3209 &subframe->data.fixed.entropy_coding_method.data.partitioned_rice
3212 subframe->data.lpc.order = order;
3213 subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3214 subframe->data.lpc.quantization_level = quantization;
3215 memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3216 for(i = 0; i < order; i++)
3217 subframe->data.lpc.warmup[i] = signal[i];
3219 #ifdef WINDOW_DEBUG_OUTPUT
3220 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);
3222 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;
3226 unsigned evaluate_verbatim_subframe_(
3227 const FLAC__int32 signal[],
3229 unsigned subframe_bps,
3230 FLAC__Subframe *subframe
3233 subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3235 subframe->data.verbatim.data = signal;
3237 return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (blocksize * subframe_bps);
3240 unsigned find_best_partition_order_(
3241 FLAC__StreamEncoderPrivate *private_,
3242 const FLAC__int32 residual[],
3243 FLAC__uint32 abs_residual[],
3244 FLAC__uint64 abs_residual_partition_sums[],
3245 unsigned raw_bits_per_partition[],
3246 unsigned residual_samples,
3247 unsigned predictor_order,
3248 unsigned rice_parameter,
3249 unsigned min_partition_order,
3250 unsigned max_partition_order,
3251 FLAC__bool precompute_partition_sums,
3252 FLAC__bool do_escape_coding,
3253 unsigned rice_parameter_search_dist,
3254 FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
3258 unsigned residual_bits, best_residual_bits = 0;
3259 unsigned residual_sample;
3260 unsigned best_parameters_index = 0;
3261 const unsigned blocksize = residual_samples + predictor_order;
3263 /* compute abs(residual) for use later */
3264 for(residual_sample = 0; residual_sample < residual_samples; residual_sample++) {
3265 r = residual[residual_sample];
3266 abs_residual[residual_sample] = (FLAC__uint32)(r<0? -r : r);
3269 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3270 min_partition_order = min(min_partition_order, max_partition_order);
3272 if(precompute_partition_sums) {
3273 int partition_order;
3276 precompute_partition_info_sums_(abs_residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order);
3278 if(do_escape_coding)
3279 precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3281 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3282 #ifdef DONT_ESTIMATE_RICE_BITS
3284 set_partitioned_rice_with_precompute_(
3286 abs_residual_partition_sums+sum,
3287 raw_bits_per_partition+sum,
3291 rice_parameter_search_dist,
3292 (unsigned)partition_order,
3294 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3300 set_partitioned_rice_with_precompute_(
3302 abs_residual_partition_sums+sum,
3303 raw_bits_per_partition+sum,
3307 rice_parameter_search_dist,
3308 (unsigned)partition_order,
3310 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3316 FLAC__ASSERT(best_residual_bits != 0);
3319 sum += 1u << partition_order;
3320 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3321 best_residual_bits = residual_bits;
3322 best_parameters_index = !best_parameters_index;
3323 best_partitioned_rice->order = partition_order;
3328 unsigned partition_order;
3329 for(partition_order = min_partition_order; partition_order <= max_partition_order; partition_order++) {
3330 #ifdef DONT_ESTIMATE_RICE_BITS
3332 set_partitioned_rice_(
3338 rice_parameter_search_dist,
3340 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3346 set_partitioned_rice_(
3351 rice_parameter_search_dist,
3353 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3359 FLAC__ASSERT(best_residual_bits != 0);
3362 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3363 best_residual_bits = residual_bits;
3364 best_parameters_index = !best_parameters_index;
3365 best_partitioned_rice->order = partition_order;
3371 * We are allowed to de-const the pointer based on our special knowledge;
3372 * it is const to the outside world.
3375 FLAC__EntropyCodingMethod_PartitionedRiceContents* best_partitioned_rice_contents = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_partitioned_rice->contents;
3376 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(best_partitioned_rice_contents, max(6, best_partitioned_rice->order));
3377 memcpy(best_partitioned_rice_contents->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
3378 memcpy(best_partitioned_rice_contents->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partitioned_rice->order)));
3381 return best_residual_bits;
3384 void precompute_partition_info_sums_(
3385 const FLAC__uint32 abs_residual[],
3386 FLAC__uint64 abs_residual_partition_sums[],
3387 unsigned residual_samples,
3388 unsigned predictor_order,
3389 unsigned min_partition_order,
3390 unsigned max_partition_order
3393 int partition_order;
3394 unsigned from_partition, to_partition = 0;
3395 const unsigned blocksize = residual_samples + predictor_order;
3397 /* first do max_partition_order */
3398 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3399 FLAC__uint64 abs_residual_partition_sum;
3401 unsigned partition, partition_sample, partition_samples, residual_sample;
3402 const unsigned partitions = 1u << partition_order;
3403 const unsigned default_partition_samples = blocksize >> partition_order;
3405 FLAC__ASSERT(default_partition_samples > predictor_order);
3407 for(partition = residual_sample = 0; partition < partitions; partition++) {
3408 partition_samples = default_partition_samples;
3410 partition_samples -= predictor_order;
3411 abs_residual_partition_sum = 0;
3412 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
3413 abs_r = abs_residual[residual_sample];
3414 abs_residual_partition_sum += abs_r;
3417 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3419 to_partition = partitions;
3423 /* now merge partitions for lower orders */
3424 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
3427 const unsigned partitions = 1u << partition_order;
3428 for(i = 0; i < partitions; i++) {
3429 s = abs_residual_partition_sums[from_partition];
3431 abs_residual_partition_sums[to_partition] = s + abs_residual_partition_sums[from_partition];
3438 void precompute_partition_info_escapes_(
3439 const FLAC__int32 residual[],
3440 unsigned raw_bits_per_partition[],
3441 unsigned residual_samples,
3442 unsigned predictor_order,
3443 unsigned min_partition_order,
3444 unsigned max_partition_order
3447 int partition_order;
3448 unsigned from_partition, to_partition = 0;
3449 const unsigned blocksize = residual_samples + predictor_order;
3451 /* first do max_partition_order */
3452 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3453 FLAC__int32 r, residual_partition_min, residual_partition_max;
3454 unsigned silog2_min, silog2_max;
3455 unsigned partition, partition_sample, partition_samples, residual_sample;
3456 const unsigned partitions = 1u << partition_order;
3457 const unsigned default_partition_samples = blocksize >> partition_order;
3459 FLAC__ASSERT(default_partition_samples > predictor_order);
3461 for(partition = residual_sample = 0; partition < partitions; partition++) {
3462 partition_samples = default_partition_samples;
3464 partition_samples -= predictor_order;
3465 residual_partition_min = residual_partition_max = 0;
3466 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
3467 r = residual[residual_sample];
3468 if(r < residual_partition_min)
3469 residual_partition_min = r;
3470 else if(r > residual_partition_max)
3471 residual_partition_max = r;
3474 silog2_min = FLAC__bitmath_silog2(residual_partition_min);
3475 silog2_max = FLAC__bitmath_silog2(residual_partition_max);
3476 raw_bits_per_partition[partition] = max(silog2_min, silog2_max);
3478 to_partition = partitions;
3479 break; /*@@@@@@ yuck, should remove the 'for' loop instead */
3482 /* now merge partitions for lower orders */
3483 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
3486 const unsigned partitions = 1u << partition_order;
3487 for(i = 0; i < partitions; i++) {
3488 m = raw_bits_per_partition[from_partition];
3490 raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
3497 #ifdef VARIABLE_RICE_BITS
3498 #undef VARIABLE_RICE_BITS
3500 #ifndef DONT_ESTIMATE_RICE_BITS
3501 #define VARIABLE_RICE_BITS(value, parameter) ((value) >> (parameter))
3504 #ifdef DONT_ESTIMATE_RICE_BITS
3505 FLAC__bool set_partitioned_rice_(
3506 const FLAC__uint32 abs_residual[],
3507 const FLAC__int32 residual[],
3508 const unsigned residual_samples,
3509 const unsigned predictor_order,
3510 const unsigned suggested_rice_parameter,
3511 const unsigned rice_parameter_search_dist,
3512 const unsigned partition_order,
3513 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3517 FLAC__bool set_partitioned_rice_(
3518 const FLAC__uint32 abs_residual[],
3519 const unsigned residual_samples,
3520 const unsigned predictor_order,
3521 const unsigned suggested_rice_parameter,
3522 const unsigned rice_parameter_search_dist,
3523 const unsigned partition_order,
3524 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3529 unsigned rice_parameter, partition_bits;
3530 #ifndef NO_RICE_SEARCH
3531 unsigned best_partition_bits;
3532 unsigned min_rice_parameter, max_rice_parameter, best_rice_parameter = 0;
3534 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
3535 unsigned *parameters;
3537 FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
3539 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
3540 parameters = partitioned_rice_contents->parameters;
3542 if(partition_order == 0) {
3545 #ifndef NO_RICE_SEARCH
3546 if(rice_parameter_search_dist) {
3547 if(suggested_rice_parameter < rice_parameter_search_dist)
3548 min_rice_parameter = 0;
3550 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
3551 max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
3552 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3553 #ifdef DEBUG_VERBOSE
3554 fprintf(stderr, "clipping rice_parameter (%u -> %u) @2\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3556 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3560 min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
3562 best_partition_bits = 0xffffffff;
3563 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3565 #ifdef VARIABLE_RICE_BITS
3566 const unsigned rice_parameter_estimate = rice_parameter-1;
3567 partition_bits = (1+rice_parameter) * residual_samples;
3571 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
3572 for(i = 0; i < residual_samples; i++) {
3573 #ifdef VARIABLE_RICE_BITS
3574 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter_estimate);
3576 partition_bits += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter); /* NOTE: we will need to pass in residual[] in addition to abs_residual[] */
3579 #ifndef NO_RICE_SEARCH
3580 if(partition_bits < best_partition_bits) {
3581 best_rice_parameter = rice_parameter;
3582 best_partition_bits = partition_bits;
3586 parameters[0] = best_rice_parameter;
3587 bits_ += best_partition_bits;
3590 unsigned partition, residual_sample, save_residual_sample, partition_sample;
3591 unsigned partition_samples;
3592 FLAC__uint64 mean, k;
3593 const unsigned partitions = 1u << partition_order;
3594 for(partition = residual_sample = 0; partition < partitions; partition++) {
3595 partition_samples = (residual_samples+predictor_order) >> partition_order;
3596 if(partition == 0) {
3597 if(partition_samples <= predictor_order)
3600 partition_samples -= predictor_order;
3603 save_residual_sample = residual_sample;
3604 for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++)
3605 mean += abs_residual[residual_sample];
3606 residual_sample = save_residual_sample;
3607 /* we are basically calculating the size in bits of the
3608 * average residual magnitude in the partition:
3609 * rice_parameter = floor(log2(mean/partition_samples))
3610 * 'mean' is not a good name for the variable, it is
3611 * actually the sum of magnitudes of all residual values
3612 * in the partition, so the actual mean is
3613 * mean/partition_samples
3615 for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
3617 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3618 #ifdef DEBUG_VERBOSE
3619 fprintf(stderr, "clipping rice_parameter (%u -> %u) @3\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3621 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3624 #ifndef NO_RICE_SEARCH
3625 if(rice_parameter_search_dist) {
3626 if(rice_parameter < rice_parameter_search_dist)
3627 min_rice_parameter = 0;
3629 min_rice_parameter = rice_parameter - rice_parameter_search_dist;
3630 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
3631 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3632 #ifdef DEBUG_VERBOSE
3633 fprintf(stderr, "clipping rice_parameter (%u -> %u) @4\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3635 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3639 min_rice_parameter = max_rice_parameter = rice_parameter;
3641 best_partition_bits = 0xffffffff;
3642 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3644 #ifdef VARIABLE_RICE_BITS
3645 const unsigned rice_parameter_estimate = rice_parameter-1;
3646 partition_bits = (1+rice_parameter) * partition_samples;
3650 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
3651 save_residual_sample = residual_sample;
3652 for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++) {
3653 #ifdef VARIABLE_RICE_BITS
3654 partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter_estimate);
3656 partition_bits += FLAC__bitbuffer_rice_bits(residual[residual_sample], rice_parameter); /* NOTE: we will need to pass in residual[] in addition to abs_residual[] */
3659 #ifndef NO_RICE_SEARCH
3660 if(rice_parameter != max_rice_parameter)
3661 residual_sample = save_residual_sample;
3662 if(partition_bits < best_partition_bits) {
3663 best_rice_parameter = rice_parameter;
3664 best_partition_bits = partition_bits;
3668 parameters[partition] = best_rice_parameter;
3669 bits_ += best_partition_bits;
3677 #ifdef DONT_ESTIMATE_RICE_BITS
3678 FLAC__bool set_partitioned_rice_with_precompute_(
3679 const FLAC__int32 residual[],
3680 const FLAC__uint64 abs_residual_partition_sums[],
3681 const unsigned raw_bits_per_partition[],
3682 const unsigned residual_samples,
3683 const unsigned predictor_order,
3684 const unsigned suggested_rice_parameter,
3685 const unsigned rice_parameter_search_dist,
3686 const unsigned partition_order,
3687 const FLAC__bool search_for_escapes,
3688 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3692 FLAC__bool set_partitioned_rice_with_precompute_(
3693 const FLAC__uint32 abs_residual[],
3694 const FLAC__uint64 abs_residual_partition_sums[],
3695 const unsigned raw_bits_per_partition[],
3696 const unsigned residual_samples,
3697 const unsigned predictor_order,
3698 const unsigned suggested_rice_parameter,
3699 const unsigned rice_parameter_search_dist,
3700 const unsigned partition_order,
3701 const FLAC__bool search_for_escapes,
3702 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3707 unsigned rice_parameter, partition_bits;
3708 #ifndef NO_RICE_SEARCH
3709 unsigned best_partition_bits;
3710 unsigned min_rice_parameter, max_rice_parameter, best_rice_parameter = 0;
3713 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
3714 unsigned *parameters, *raw_bits;
3716 FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
3718 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
3719 parameters = partitioned_rice_contents->parameters;
3720 raw_bits = partitioned_rice_contents->raw_bits;
3722 if(partition_order == 0) {
3725 #ifndef NO_RICE_SEARCH
3726 if(rice_parameter_search_dist) {
3727 if(suggested_rice_parameter < rice_parameter_search_dist)
3728 min_rice_parameter = 0;
3730 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
3731 max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
3732 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3733 #ifdef DEBUG_VERBOSE
3734 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3736 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3740 min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
3742 best_partition_bits = 0xffffffff;
3743 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3745 #ifdef VARIABLE_RICE_BITS
3746 const unsigned rice_parameter_estimate = rice_parameter-1;
3747 partition_bits = (1+rice_parameter) * residual_samples;
3751 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
3752 for(i = 0; i < residual_samples; i++) {
3753 #ifdef VARIABLE_RICE_BITS
3754 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter_estimate);
3756 partition_bits += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
3759 #ifndef NO_RICE_SEARCH
3760 if(partition_bits < best_partition_bits) {
3761 best_rice_parameter = rice_parameter;
3762 best_partition_bits = partition_bits;
3766 if(search_for_escapes) {
3767 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;
3768 if(flat_bits <= best_partition_bits) {
3769 raw_bits[0] = raw_bits_per_partition[0];
3770 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
3771 best_partition_bits = flat_bits;
3774 parameters[0] = best_rice_parameter;
3775 bits_ += best_partition_bits;
3778 unsigned partition, residual_sample, save_residual_sample, partition_sample;
3779 unsigned partition_samples;
3780 FLAC__uint64 mean, k;
3781 const unsigned partitions = 1u << partition_order;
3782 for(partition = residual_sample = 0; partition < partitions; partition++) {
3783 partition_samples = (residual_samples+predictor_order) >> partition_order;
3784 if(partition == 0) {
3785 if(partition_samples <= predictor_order)
3788 partition_samples -= predictor_order;
3790 mean = abs_residual_partition_sums[partition];
3791 /* we are basically calculating the size in bits of the
3792 * average residual magnitude in the partition:
3793 * rice_parameter = floor(log2(mean/partition_samples))
3794 * 'mean' is not a good name for the variable, it is
3795 * actually the sum of magnitudes of all residual values
3796 * in the partition, so the actual mean is
3797 * mean/partition_samples
3799 for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
3801 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3802 #ifdef DEBUG_VERBOSE
3803 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3805 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3808 #ifndef NO_RICE_SEARCH
3809 if(rice_parameter_search_dist) {
3810 if(rice_parameter < rice_parameter_search_dist)
3811 min_rice_parameter = 0;
3813 min_rice_parameter = rice_parameter - rice_parameter_search_dist;
3814 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
3815 if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3816 #ifdef DEBUG_VERBOSE
3817 fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3819 max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3823 min_rice_parameter = max_rice_parameter = rice_parameter;
3825 best_partition_bits = 0xffffffff;
3826 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3828 #ifdef VARIABLE_RICE_BITS
3829 const unsigned rice_parameter_estimate = rice_parameter-1;
3830 partition_bits = (1+rice_parameter) * partition_samples;
3834 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
3835 save_residual_sample = residual_sample;
3836 for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++) {
3837 #ifdef VARIABLE_RICE_BITS
3838 partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter_estimate);
3840 partition_bits += FLAC__bitbuffer_rice_bits(residual[residual_sample], rice_parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
3843 #ifndef NO_RICE_SEARCH
3844 if(rice_parameter != max_rice_parameter)
3845 residual_sample = save_residual_sample;
3846 if(partition_bits < best_partition_bits) {
3847 best_rice_parameter = rice_parameter;
3848 best_partition_bits = partition_bits;
3852 if(search_for_escapes) {
3853 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;
3854 if(flat_bits <= best_partition_bits) {
3855 raw_bits[partition] = raw_bits_per_partition[partition];
3856 best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
3857 best_partition_bits = flat_bits;
3860 parameters[partition] = best_rice_parameter;
3861 bits_ += best_partition_bits;
3869 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
3874 for(i = 0; i < samples && !(x&1); i++)
3881 for(shift = 0; !(x&1); shift++)
3886 for(i = 0; i < samples; i++)
3887 signal[i] >>= shift;
3893 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
3897 for(channel = 0; channel < channels; channel++)
3898 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
3900 fifo->tail += wide_samples;
3902 FLAC__ASSERT(fifo->tail <= fifo->size);
3905 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
3908 unsigned sample, wide_sample;
3909 unsigned tail = fifo->tail;
3911 sample = input_offset * channels;
3912 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
3913 for(channel = 0; channel < channels; channel++)
3914 fifo->data[channel][tail] = input[sample++];
3919 FLAC__ASSERT(fifo->tail <= fifo->size);
3922 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
3924 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
3925 const unsigned encoded_bytes = encoder->private_->verify.output.bytes;
3928 if(encoder->private_->verify.needs_magic_hack) {
3929 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
3930 *bytes = FLAC__STREAM_SYNC_LENGTH;
3931 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
3932 encoder->private_->verify.needs_magic_hack = false;
3935 if(encoded_bytes == 0) {
3937 * If we get here, a FIFO underflow has occurred,
3938 * which means there is a bug somewhere.
3941 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
3943 else if(encoded_bytes < *bytes)
3944 *bytes = encoded_bytes;
3945 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
3946 encoder->private_->verify.output.data += *bytes;
3947 encoder->private_->verify.output.bytes -= *bytes;
3950 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
3953 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
3955 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
3957 const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
3958 const unsigned blocksize = frame->header.blocksize;
3959 const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
3961 for(channel = 0; channel < channels; channel++) {
3962 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
3963 unsigned i, sample = 0;
3964 FLAC__int32 expect = 0, got = 0;
3966 for(i = 0; i < blocksize; i++) {
3967 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
3969 expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
3970 got = (FLAC__int32)buffer[channel][i];
3974 FLAC__ASSERT(i < blocksize);
3975 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
3976 encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
3977 encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
3978 encoder->private_->verify.error_stats.channel = channel;
3979 encoder->private_->verify.error_stats.sample = sample;
3980 encoder->private_->verify.error_stats.expected = expect;
3981 encoder->private_->verify.error_stats.got = got;
3982 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
3983 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
3986 /* dequeue the frame from the fifo */
3987 for(channel = 0; channel < channels; channel++) {
3988 memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail - blocksize);
3990 encoder->private_->verify.input_fifo.tail -= blocksize;
3991 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
3994 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
3996 (void)decoder, (void)metadata, (void)client_data;
3999 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4001 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4002 (void)decoder, (void)status;
4003 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4006 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4010 if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
4011 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4013 return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4016 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4022 offset = ftello(encoder->private_->file);
4025 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4028 *absolute_byte_offset = (FLAC__uint64)offset;
4029 return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4033 #ifdef FLAC__VALGRIND_TESTING
4034 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4036 size_t ret = fwrite(ptr, size, nmemb, stream);
4042 #define local__fwrite fwrite
4045 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
4047 (void)client_data, (void)samples, (void)current_frame;
4049 if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4050 if(0 != encoder->private_->progress_callback && samples > 0)
4051 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);
4052 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4055 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4059 * This will forcibly set stdout to binary mode (for OSes that require it)
4061 FILE *get_binary_stdout_()
4063 /* if something breaks here it is probably due to the presence or
4064 * absence of an underscore before the identifiers 'setmode',
4065 * 'fileno', and/or 'O_BINARY'; check your system header files.
4067 #if defined _MSC_VER || defined __MINGW32__
4068 _setmode(_fileno(stdout), _O_BINARY);
4069 #elif defined __CYGWIN__
4070 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4071 setmode(_fileno(stdout), _O_BINARY);
4072 #elif defined __EMX__
4073 setmode(fileno(stdout), O_BINARY);