VST3: fetch midi mappings all at once, use it for note/sound-off
[carla.git] / source / modules / juce_audio_formats / codecs / flac / libFLAC / stream_encoder.c
blob795025eb92c6d2384bb74ad1b4ea49ec9c18950e
1 /* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000-2009 Josh Coalson
3 * Copyright (C) 2011-2014 Xiph.Org Foundation
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * - Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * - Neither the name of the Xiph.org Foundation nor the names of its
17 * contributors may be used to endorse or promote products derived from
18 * this software without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
24 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
28 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
30 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #ifdef HAVE_CONFIG_H
34 # include <config.h>
35 #endif
37 #include <limits.h>
38 #include <stdio.h>
39 #include <stdlib.h> /* for malloc() */
40 #include <string.h> /* for memcpy() */
41 #include <sys/types.h> /* for off_t */
42 #include "../assert.h"
43 #include "../stream_decoder.h"
44 #include "include/protected/stream_encoder.h"
45 #include "include/private/bitwriter.h"
46 #include "include/private/bitmath.h"
47 #include "include/private/crc.h"
48 #include "include/private/cpu.h"
49 #include "include/private/fixed.h"
50 #include "include/private/format.h"
51 #include "include/private/lpc.h"
52 #include "include/private/md5.h"
53 #include "include/private/memory.h"
54 #if FLAC__HAS_OGG
55 #include "include/private/ogg_helper.h"
56 #include "include/private/ogg_mapping.h"
57 #endif
58 #include "include/private/stream_encoder.h"
59 #include "include/private/stream_encoder_framing.h"
60 #include "include/private/window.h"
61 #include "../alloc.h"
64 /* Exact Rice codeword length calculation is off by default. The simple
65 * (and fast) estimation (of how many bits a residual value will be
66 * encoded with) in this encoder is very good, almost always yielding
67 * compression within 0.1% of exact calculation.
69 #undef EXACT_RICE_BITS_CALCULATION
70 /* Rice parameter searching is off by default. The simple (and fast)
71 * parameter estimation in this encoder is very good, almost always
72 * yielding compression within 0.1% of the optimal parameters.
74 #undef ENABLE_RICE_PARAMETER_SEARCH
77 typedef struct {
78 FLAC__int32 *data[FLAC__MAX_CHANNELS];
79 unsigned size; /* of each data[] in samples */
80 unsigned tail;
81 } verify_input_fifo;
83 typedef struct {
84 const FLAC__byte *data;
85 unsigned capacity;
86 unsigned bytes;
87 } verify_output;
89 typedef enum {
90 ENCODER_IN_MAGIC = 0,
91 ENCODER_IN_METADATA = 1,
92 ENCODER_IN_AUDIO = 2
93 } EncoderStateHint;
95 static struct CompressionLevels {
96 FLAC__bool do_mid_side_stereo;
97 FLAC__bool loose_mid_side_stereo;
98 unsigned max_lpc_order;
99 unsigned qlp_coeff_precision;
100 FLAC__bool do_qlp_coeff_prec_search;
101 FLAC__bool do_escape_coding;
102 FLAC__bool do_exhaustive_model_search;
103 unsigned min_residual_partition_order;
104 unsigned max_residual_partition_order;
105 unsigned rice_parameter_search_dist;
106 const char *apodization;
107 } compression_levels_[] = {
108 { false, false, 0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
109 { true , true , 0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
110 { true , false, 0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
111 { false, false, 6, 0, false, false, false, 0, 4, 0, "tukey(5e-1)" },
112 { true , true , 8, 0, false, false, false, 0, 4, 0, "tukey(5e-1)" },
113 { true , false, 8, 0, false, false, false, 0, 5, 0, "tukey(5e-1)" },
114 { true , false, 8, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2)" },
115 { true , false, 12, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2)" },
116 { true , false, 12, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2);punchout_tukey(3)" }
117 /* here we use locale-independent 5e-1 instead of 0.5 or 0,5 */
121 /***********************************************************************
123 * Private class method prototypes
125 ***********************************************************************/
127 static void set_defaults_(FLAC__StreamEncoder *encoder);
128 static void free_(FLAC__StreamEncoder *encoder);
129 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
130 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
131 static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
132 static void update_metadata_(const FLAC__StreamEncoder *encoder);
133 #if FLAC__HAS_OGG
134 static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
135 #endif
136 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
137 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
139 static FLAC__bool process_subframe_(
140 FLAC__StreamEncoder *encoder,
141 unsigned min_partition_order,
142 unsigned max_partition_order,
143 const FLAC__FrameHeader *frame_header,
144 unsigned subframe_bps,
145 const FLAC__int32 integer_signal[],
146 FLAC__Subframe *subframe[2],
147 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
148 FLAC__int32 *residual[2],
149 unsigned *best_subframe,
150 unsigned *best_bits
153 static FLAC__bool add_subframe_(
154 FLAC__StreamEncoder *encoder,
155 unsigned blocksize,
156 unsigned subframe_bps,
157 const FLAC__Subframe *subframe,
158 FLAC__BitWriter *frame
161 static unsigned evaluate_constant_subframe_(
162 FLAC__StreamEncoder *encoder,
163 const FLAC__int32 signal,
164 unsigned blocksize,
165 unsigned subframe_bps,
166 FLAC__Subframe *subframe
169 static unsigned evaluate_fixed_subframe_(
170 FLAC__StreamEncoder *encoder,
171 const FLAC__int32 signal[],
172 FLAC__int32 residual[],
173 FLAC__uint64 abs_residual_partition_sums[],
174 unsigned raw_bits_per_partition[],
175 unsigned blocksize,
176 unsigned subframe_bps,
177 unsigned order,
178 unsigned rice_parameter,
179 unsigned rice_parameter_limit,
180 unsigned min_partition_order,
181 unsigned max_partition_order,
182 FLAC__bool do_escape_coding,
183 unsigned rice_parameter_search_dist,
184 FLAC__Subframe *subframe,
185 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
188 #ifndef FLAC__INTEGER_ONLY_LIBRARY
189 static unsigned evaluate_lpc_subframe_(
190 FLAC__StreamEncoder *encoder,
191 const FLAC__int32 signal[],
192 FLAC__int32 residual[],
193 FLAC__uint64 abs_residual_partition_sums[],
194 unsigned raw_bits_per_partition[],
195 const FLAC__real lp_coeff[],
196 unsigned blocksize,
197 unsigned subframe_bps,
198 unsigned order,
199 unsigned qlp_coeff_precision,
200 unsigned rice_parameter,
201 unsigned rice_parameter_limit,
202 unsigned min_partition_order,
203 unsigned max_partition_order,
204 FLAC__bool do_escape_coding,
205 unsigned rice_parameter_search_dist,
206 FLAC__Subframe *subframe,
207 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
209 #endif
211 static unsigned evaluate_verbatim_subframe_(
212 FLAC__StreamEncoder *encoder,
213 const FLAC__int32 signal[],
214 unsigned blocksize,
215 unsigned subframe_bps,
216 FLAC__Subframe *subframe
219 static unsigned find_best_partition_order_(
220 struct FLAC__StreamEncoderPrivate *private_,
221 const FLAC__int32 residual[],
222 FLAC__uint64 abs_residual_partition_sums[],
223 unsigned raw_bits_per_partition[],
224 unsigned residual_samples,
225 unsigned predictor_order,
226 unsigned rice_parameter,
227 unsigned rice_parameter_limit,
228 unsigned min_partition_order,
229 unsigned max_partition_order,
230 unsigned bps,
231 FLAC__bool do_escape_coding,
232 unsigned rice_parameter_search_dist,
233 FLAC__EntropyCodingMethod *best_ecm
236 static void precompute_partition_info_sums_(
237 const FLAC__int32 residual[],
238 FLAC__uint64 abs_residual_partition_sums[],
239 unsigned residual_samples,
240 unsigned predictor_order,
241 unsigned min_partition_order,
242 unsigned max_partition_order,
243 unsigned bps
246 static void precompute_partition_info_escapes_(
247 const FLAC__int32 residual[],
248 unsigned raw_bits_per_partition[],
249 unsigned residual_samples,
250 unsigned predictor_order,
251 unsigned min_partition_order,
252 unsigned max_partition_order
255 static FLAC__bool set_partitioned_rice_(
256 #ifdef EXACT_RICE_BITS_CALCULATION
257 const FLAC__int32 residual[],
258 #endif
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_limit,
265 const unsigned rice_parameter_search_dist,
266 const unsigned partition_order,
267 const FLAC__bool search_for_escapes,
268 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
269 unsigned *bits
272 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
274 /* verify-related routines: */
275 static void append_to_verify_fifo_(
276 verify_input_fifo *fifo,
277 const FLAC__int32 * const input[],
278 unsigned input_offset,
279 unsigned channels,
280 unsigned wide_samples
283 static void append_to_verify_fifo_interleaved_(
284 verify_input_fifo *fifo,
285 const FLAC__int32 input[],
286 unsigned input_offset,
287 unsigned channels,
288 unsigned wide_samples
291 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
292 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
293 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
294 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
296 //static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
297 //static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
298 //static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
299 //static FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
300 //static FILE *get_binary_stdout_(void);
303 /***********************************************************************
305 * Private class data
307 ***********************************************************************/
309 typedef struct FLAC__StreamEncoderPrivate {
310 unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
311 FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
312 FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
313 #ifndef FLAC__INTEGER_ONLY_LIBRARY
314 FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
315 FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
316 FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
317 FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
318 #endif
319 unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
320 unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
321 FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
322 FLAC__int32 *residual_workspace_mid_side[2][2];
323 FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
324 FLAC__Subframe subframe_workspace_mid_side[2][2];
325 FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
326 FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
327 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
328 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
329 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
330 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
331 unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
332 unsigned best_subframe_mid_side[2];
333 unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
334 unsigned best_subframe_bits_mid_side[2];
335 FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
336 unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
337 FLAC__BitWriter *frame; /* the current frame being worked on */
338 unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
339 unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
340 FLAC__ChannelAssignment last_channel_assignment;
341 FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
342 FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
343 unsigned current_sample_number;
344 unsigned current_frame_number;
345 FLAC__MD5Context md5context;
346 FLAC__CPUInfo cpuinfo;
347 void (*local_precompute_partition_info_sums)(const FLAC__int32 residual[], FLAC__uint64 abs_residual_partition_sums[], unsigned residual_samples, unsigned predictor_order, unsigned min_partition_order, unsigned max_partition_order, unsigned bps);
348 #ifndef FLAC__INTEGER_ONLY_LIBRARY
349 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
350 unsigned (*local_fixed_compute_best_predictor_wide)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
351 #else
352 unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
353 unsigned (*local_fixed_compute_best_predictor_wide)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
354 #endif
355 #ifndef FLAC__INTEGER_ONLY_LIBRARY
356 void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
357 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[]);
358 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[]);
359 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[]);
360 #endif
361 FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
362 FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
363 FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
364 FLAC__bool disable_constant_subframes;
365 FLAC__bool disable_fixed_subframes;
366 FLAC__bool disable_verbatim_subframes;
367 #if FLAC__HAS_OGG
368 FLAC__bool is_ogg;
369 #endif
370 FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
371 FLAC__StreamEncoderSeekCallback seek_callback;
372 FLAC__StreamEncoderTellCallback tell_callback;
373 FLAC__StreamEncoderWriteCallback write_callback;
374 FLAC__StreamEncoderMetadataCallback metadata_callback;
375 FLAC__StreamEncoderProgressCallback progress_callback;
376 void *client_data;
377 unsigned first_seekpoint_to_check;
378 FILE *file; /* only used when encoding to a file */
379 FLAC__uint64 bytes_written;
380 FLAC__uint64 samples_written;
381 unsigned frames_written;
382 unsigned total_frames_estimate;
383 /* unaligned (original) pointers to allocated data */
384 FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
385 FLAC__int32 *integer_signal_mid_side_unaligned[2];
386 #ifndef FLAC__INTEGER_ONLY_LIBRARY
387 FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
388 FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
389 FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
390 FLAC__real *windowed_signal_unaligned;
391 #endif
392 FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
393 FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
394 FLAC__uint64 *abs_residual_partition_sums_unaligned;
395 unsigned *raw_bits_per_partition_unaligned;
397 * These fields have been moved here from private function local
398 * declarations merely to save stack space during encoding.
400 #ifndef FLAC__INTEGER_ONLY_LIBRARY
401 FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
402 #endif
403 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
405 * The data for the verify section
407 struct {
408 FLAC__StreamDecoder *decoder;
409 EncoderStateHint state_hint;
410 FLAC__bool needs_magic_hack;
411 verify_input_fifo input_fifo;
412 verify_output output;
413 struct {
414 FLAC__uint64 absolute_sample;
415 unsigned frame_number;
416 unsigned channel;
417 unsigned sample;
418 FLAC__int32 expected;
419 FLAC__int32 got;
420 } error_stats;
421 } verify;
422 FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
423 } FLAC__StreamEncoderPrivate;
425 /***********************************************************************
427 * Public static class data
429 ***********************************************************************/
431 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
432 "FLAC__STREAM_ENCODER_OK",
433 "FLAC__STREAM_ENCODER_UNINITIALIZED",
434 "FLAC__STREAM_ENCODER_OGG_ERROR",
435 "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
436 "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
437 "FLAC__STREAM_ENCODER_CLIENT_ERROR",
438 "FLAC__STREAM_ENCODER_IO_ERROR",
439 "FLAC__STREAM_ENCODER_FRAMING_ERROR",
440 "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
443 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
444 "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
445 "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
446 "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
447 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
448 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
449 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
450 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
451 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
452 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
453 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
454 "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
455 "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
456 "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
457 "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
460 FLAC_API const char * const FLAC__StreamEncoderReadStatusString[] = {
461 "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
462 "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
463 "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
464 "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
467 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
468 "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
469 "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
472 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
473 "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
474 "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
475 "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
478 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
479 "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
480 "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
481 "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
484 /* Number of samples that will be overread to watch for end of stream. By
485 * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
486 * always try to read blocksize+1 samples before encoding a block, so that
487 * even if the stream has a total sample count that is an integral multiple
488 * of the blocksize, we will still notice when we are encoding the last
489 * block. This is needed, for example, to correctly set the end-of-stream
490 * marker in Ogg FLAC.
492 * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
493 * not really any reason to change it.
495 static const unsigned OVERREAD_ = 1;
497 /***********************************************************************
499 * Class constructor/destructor
502 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
504 FLAC__StreamEncoder *encoder;
505 unsigned i;
507 FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
509 encoder = (FLAC__StreamEncoder*) calloc(1, sizeof(FLAC__StreamEncoder));
510 if(encoder == 0) {
511 return 0;
514 encoder->protected_ = (FLAC__StreamEncoderProtected*) calloc(1, sizeof(FLAC__StreamEncoderProtected));
515 if(encoder->protected_ == 0) {
516 free(encoder);
517 return 0;
520 encoder->private_ = (FLAC__StreamEncoderPrivate*) calloc(1, sizeof(FLAC__StreamEncoderPrivate));
521 if(encoder->private_ == 0) {
522 free(encoder->protected_);
523 free(encoder);
524 return 0;
527 encoder->private_->frame = FLAC__bitwriter_new();
528 if(encoder->private_->frame == 0) {
529 free(encoder->private_);
530 free(encoder->protected_);
531 free(encoder);
532 return 0;
535 encoder->private_->file = 0;
537 set_defaults_(encoder);
539 encoder->private_->is_being_deleted = false;
541 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
542 encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
543 encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
545 for(i = 0; i < 2; i++) {
546 encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
547 encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
549 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
550 encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
551 encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
553 for(i = 0; i < 2; i++) {
554 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
555 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
558 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
559 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
560 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
562 for(i = 0; i < 2; i++) {
563 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
564 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
566 for(i = 0; i < 2; i++)
567 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
569 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
571 return encoder;
574 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
576 unsigned i;
578 if (encoder == NULL)
579 return ;
581 FLAC__ASSERT(0 != encoder->protected_);
582 FLAC__ASSERT(0 != encoder->private_);
583 FLAC__ASSERT(0 != encoder->private_->frame);
585 encoder->private_->is_being_deleted = true;
587 (void)FLAC__stream_encoder_finish(encoder);
589 if(0 != encoder->private_->verify.decoder)
590 FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
592 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
593 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
594 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
596 for(i = 0; i < 2; i++) {
597 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
598 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
600 for(i = 0; i < 2; i++)
601 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
603 FLAC__bitwriter_delete(encoder->private_->frame);
604 free(encoder->private_);
605 free(encoder->protected_);
606 free(encoder);
609 /***********************************************************************
611 * Public class methods
613 ***********************************************************************/
615 static FLAC__StreamEncoderInitStatus init_stream_internal_(
616 FLAC__StreamEncoder *encoder,
617 FLAC__StreamEncoderReadCallback read_callback,
618 FLAC__StreamEncoderWriteCallback write_callback,
619 FLAC__StreamEncoderSeekCallback seek_callback,
620 FLAC__StreamEncoderTellCallback tell_callback,
621 FLAC__StreamEncoderMetadataCallback metadata_callback,
622 void *client_data,
623 FLAC__bool is_ogg
626 unsigned i;
627 FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
629 FLAC__ASSERT(0 != encoder);
631 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
632 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
634 #if !FLAC__HAS_OGG
635 if(is_ogg)
636 return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
637 #endif
639 if(0 == write_callback || (seek_callback && 0 == tell_callback))
640 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
642 if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
643 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
645 if(encoder->protected_->channels != 2) {
646 encoder->protected_->do_mid_side_stereo = false;
647 encoder->protected_->loose_mid_side_stereo = false;
649 else if(!encoder->protected_->do_mid_side_stereo)
650 encoder->protected_->loose_mid_side_stereo = false;
652 if(encoder->protected_->bits_per_sample >= 32)
653 encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
655 if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
656 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
658 if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
659 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
661 if(encoder->protected_->blocksize == 0) {
662 if(encoder->protected_->max_lpc_order == 0)
663 encoder->protected_->blocksize = 1152;
664 else
665 encoder->protected_->blocksize = 4096;
668 if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
669 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
671 if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
672 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
674 if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
675 return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
677 if(encoder->protected_->qlp_coeff_precision == 0) {
678 if(encoder->protected_->bits_per_sample < 16) {
679 /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
680 /* @@@ until then we'll make a guess */
681 encoder->protected_->qlp_coeff_precision = flac_max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
683 else if(encoder->protected_->bits_per_sample == 16) {
684 if(encoder->protected_->blocksize <= 192)
685 encoder->protected_->qlp_coeff_precision = 7;
686 else if(encoder->protected_->blocksize <= 384)
687 encoder->protected_->qlp_coeff_precision = 8;
688 else if(encoder->protected_->blocksize <= 576)
689 encoder->protected_->qlp_coeff_precision = 9;
690 else if(encoder->protected_->blocksize <= 1152)
691 encoder->protected_->qlp_coeff_precision = 10;
692 else if(encoder->protected_->blocksize <= 2304)
693 encoder->protected_->qlp_coeff_precision = 11;
694 else if(encoder->protected_->blocksize <= 4608)
695 encoder->protected_->qlp_coeff_precision = 12;
696 else
697 encoder->protected_->qlp_coeff_precision = 13;
699 else {
700 if(encoder->protected_->blocksize <= 384)
701 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
702 else if(encoder->protected_->blocksize <= 1152)
703 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
704 else
705 encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
707 FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
709 else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
710 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
712 if(encoder->protected_->streamable_subset) {
713 if(!FLAC__format_blocksize_is_subset(encoder->protected_->blocksize, encoder->protected_->sample_rate))
714 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
715 if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
716 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
718 encoder->protected_->bits_per_sample != 8 &&
719 encoder->protected_->bits_per_sample != 12 &&
720 encoder->protected_->bits_per_sample != 16 &&
721 encoder->protected_->bits_per_sample != 20 &&
722 encoder->protected_->bits_per_sample != 24
724 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
725 if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
726 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
728 encoder->protected_->sample_rate <= 48000 &&
730 encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
731 encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
734 return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
738 if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
739 encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
740 if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
741 encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
743 #if FLAC__HAS_OGG
744 /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
745 if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
746 unsigned i1;
747 for(i1 = 1; i1 < encoder->protected_->num_metadata_blocks; i1++) {
748 if(0 != encoder->protected_->metadata[i1] && encoder->protected_->metadata[i1]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
749 FLAC__StreamMetadata *vc = encoder->protected_->metadata[i1];
750 for( ; i1 > 0; i1--)
751 encoder->protected_->metadata[i1] = encoder->protected_->metadata[i1-1];
752 encoder->protected_->metadata[0] = vc;
753 break;
757 #endif
758 /* keep track of any SEEKTABLE block */
759 if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
760 unsigned i2;
761 for(i2 = 0; i2 < encoder->protected_->num_metadata_blocks; i2++) {
762 if(0 != encoder->protected_->metadata[i2] && encoder->protected_->metadata[i2]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
763 encoder->private_->seek_table = &encoder->protected_->metadata[i2]->data.seek_table;
764 break; /* take only the first one */
769 /* validate metadata */
770 if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
771 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
772 metadata_has_seektable = false;
773 metadata_has_vorbis_comment = false;
774 metadata_picture_has_type1 = false;
775 metadata_picture_has_type2 = false;
776 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
777 const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
778 if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
779 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
780 else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
781 if(metadata_has_seektable) /* only one is allowed */
782 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
783 metadata_has_seektable = true;
784 if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
785 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
787 else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
788 if(metadata_has_vorbis_comment) /* only one is allowed */
789 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
790 metadata_has_vorbis_comment = true;
792 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
793 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
794 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
796 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
797 if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
798 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
799 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
800 if(metadata_picture_has_type1) /* there should only be 1 per stream */
801 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
802 metadata_picture_has_type1 = true;
803 /* standard icon must be 32x32 pixel PNG */
805 m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
807 (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
808 m->data.picture.width != 32 ||
809 m->data.picture.height != 32
812 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
814 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
815 if(metadata_picture_has_type2) /* there should only be 1 per stream */
816 return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
817 metadata_picture_has_type2 = true;
822 encoder->private_->input_capacity = 0;
823 for(i = 0; i < encoder->protected_->channels; i++) {
824 encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
825 #ifndef FLAC__INTEGER_ONLY_LIBRARY
826 encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
827 #endif
829 for(i = 0; i < 2; i++) {
830 encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
831 #ifndef FLAC__INTEGER_ONLY_LIBRARY
832 encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
833 #endif
835 #ifndef FLAC__INTEGER_ONLY_LIBRARY
836 for(i = 0; i < encoder->protected_->num_apodizations; i++)
837 encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
838 encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
839 #endif
840 for(i = 0; i < encoder->protected_->channels; i++) {
841 encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
842 encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
843 encoder->private_->best_subframe[i] = 0;
845 for(i = 0; i < 2; i++) {
846 encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
847 encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
848 encoder->private_->best_subframe_mid_side[i] = 0;
850 encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
851 encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
852 #ifndef FLAC__INTEGER_ONLY_LIBRARY
853 encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
854 #else
855 /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
856 /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
857 FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
858 FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
859 FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
860 FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
861 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);
862 #endif
863 if(encoder->private_->loose_mid_side_stereo_frames == 0)
864 encoder->private_->loose_mid_side_stereo_frames = 1;
865 encoder->private_->loose_mid_side_stereo_frame_count = 0;
866 encoder->private_->current_sample_number = 0;
867 encoder->private_->current_frame_number = 0;
869 encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
870 encoder->private_->use_wide_by_order = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(flac_max(encoder->protected_->max_lpc_order, FLAC__MAX_FIXED_ORDER))+1 > 30); /*@@@ need to use this? */
871 encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
874 * get the CPU info and set the function pointers
876 FLAC__cpu_info(&encoder->private_->cpuinfo);
877 /* first default to the non-asm routines */
878 #ifndef FLAC__INTEGER_ONLY_LIBRARY
879 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
880 #endif
881 encoder->private_->local_precompute_partition_info_sums = precompute_partition_info_sums_;
882 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
883 encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide;
884 #ifndef FLAC__INTEGER_ONLY_LIBRARY
885 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
886 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
887 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
888 #endif
889 /* now override with asm where appropriate */
890 #ifndef FLAC__INTEGER_ONLY_LIBRARY
891 # ifndef FLAC__NO_ASM
892 if(encoder->private_->cpuinfo.use_asm) {
893 # ifdef FLAC__CPU_IA32
894 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
895 # ifdef FLAC__HAS_NASM
896 if(encoder->private_->cpuinfo.ia32.sse) {
897 if(encoder->protected_->max_lpc_order < 4)
898 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
899 else if(encoder->protected_->max_lpc_order < 8)
900 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
901 else if(encoder->protected_->max_lpc_order < 12)
902 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
903 else if(encoder->protected_->max_lpc_order < 16)
904 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_16;
905 else
906 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
908 else
909 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
911 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_asm_ia32; /* OPT_IA32: was really necessary for GCC < 4.9 */
912 if(encoder->private_->cpuinfo.ia32.mmx) {
913 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
914 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
916 else {
917 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
918 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
921 if(encoder->private_->cpuinfo.ia32.mmx && encoder->private_->cpuinfo.ia32.cmov)
922 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
923 # endif /* FLAC__HAS_NASM */
924 # ifdef FLAC__HAS_X86INTRIN
925 # if defined FLAC__SSE_SUPPORTED
926 if(encoder->private_->cpuinfo.ia32.sse) {
927 if(encoder->protected_->max_lpc_order < 4)
928 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4;
929 else if(encoder->protected_->max_lpc_order < 8)
930 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8;
931 else if(encoder->protected_->max_lpc_order < 12)
932 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12;
933 else if(encoder->protected_->max_lpc_order < 16)
934 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16;
935 else
936 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
938 # endif
940 # ifdef FLAC__SSE2_SUPPORTED
941 if(encoder->private_->cpuinfo.ia32.sse2) {
942 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse2;
943 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_sse2;
945 # endif
946 # ifdef FLAC__SSE4_1_SUPPORTED
947 if(encoder->private_->cpuinfo.ia32.sse41) {
948 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse41;
949 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_sse41;
951 # endif
952 # ifdef FLAC__AVX2_SUPPORTED
953 if(encoder->private_->cpuinfo.ia32.avx2) {
954 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_avx2;
955 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_avx2;
956 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_avx2;
958 # endif
960 # ifdef FLAC__SSE2_SUPPORTED
961 if (encoder->private_->cpuinfo.ia32.sse2) {
962 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_intrin_sse2;
963 encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_sse2;
965 # endif
966 # ifdef FLAC__SSSE3_SUPPORTED
967 if (encoder->private_->cpuinfo.ia32.ssse3) {
968 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_intrin_ssse3;
969 encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_ssse3;
971 # endif
972 # endif /* FLAC__HAS_X86INTRIN */
973 # elif defined FLAC__CPU_X86_64
974 FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_X86_64);
975 # ifdef FLAC__HAS_X86INTRIN
976 # ifdef FLAC__SSE_SUPPORTED
977 if(encoder->protected_->max_lpc_order < 4)
978 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4;
979 else if(encoder->protected_->max_lpc_order < 8)
980 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8;
981 else if(encoder->protected_->max_lpc_order < 12)
982 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12;
983 else if(encoder->protected_->max_lpc_order < 16)
984 encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16;
985 # endif
987 # ifdef FLAC__SSE2_SUPPORTED
988 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_sse2;
989 # endif
990 # ifdef FLAC__SSE4_1_SUPPORTED
991 if(encoder->private_->cpuinfo.x86.sse41) {
992 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse41;
994 # endif
995 # ifdef FLAC__AVX2_SUPPORTED
996 if(encoder->private_->cpuinfo.x86.avx2) {
997 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_avx2;
998 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_avx2;
999 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_avx2;
1001 # endif
1003 # ifdef FLAC__SSE2_SUPPORTED
1004 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_intrin_sse2;
1005 encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_sse2;
1006 # endif
1007 # ifdef FLAC__SSSE3_SUPPORTED
1008 if (encoder->private_->cpuinfo.x86.ssse3) {
1009 encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_intrin_ssse3;
1010 encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_ssse3;
1012 # endif
1013 # endif /* FLAC__HAS_X86INTRIN */
1014 # endif /* FLAC__CPU_... */
1016 # endif /* !FLAC__NO_ASM */
1017 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
1018 #if !defined FLAC__NO_ASM && defined FLAC__HAS_X86INTRIN
1019 if(encoder->private_->cpuinfo.use_asm) {
1020 # if defined FLAC__CPU_IA32
1021 # ifdef FLAC__SSE2_SUPPORTED
1022 if(encoder->private_->cpuinfo.ia32.sse2)
1023 encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_sse2;
1024 # endif
1025 # ifdef FLAC__SSSE3_SUPPORTED
1026 if(encoder->private_->cpuinfo.ia32.ssse3)
1027 encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_ssse3;
1028 # endif
1029 # ifdef FLAC__AVX2_SUPPORTED
1030 if(encoder->private_->cpuinfo.ia32.avx2)
1031 encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_avx2;
1032 # endif
1033 # elif defined FLAC__CPU_X86_64
1034 # ifdef FLAC__SSE2_SUPPORTED
1035 encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_sse2;
1036 # endif
1037 # ifdef FLAC__SSSE3_SUPPORTED
1038 if(encoder->private_->cpuinfo.x86.ssse3)
1039 encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_ssse3;
1040 # endif
1041 # ifdef FLAC__AVX2_SUPPORTED
1042 if(encoder->private_->cpuinfo.x86.avx2)
1043 encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_avx2;
1044 # endif
1045 # endif /* FLAC__CPU_... */
1047 #endif /* !FLAC__NO_ASM && FLAC__HAS_X86INTRIN */
1048 /* finally override based on wide-ness if necessary */
1049 if(encoder->private_->use_wide_by_block) {
1050 encoder->private_->local_fixed_compute_best_predictor = encoder->private_->local_fixed_compute_best_predictor_wide;
1053 /* set state to OK; from here on, errors are fatal and we'll override the state then */
1054 encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
1056 #if FLAC__HAS_OGG
1057 encoder->private_->is_ogg = is_ogg;
1058 if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
1059 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
1060 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1062 #endif
1064 encoder->private_->read_callback = read_callback;
1065 encoder->private_->write_callback = write_callback;
1066 encoder->private_->seek_callback = seek_callback;
1067 encoder->private_->tell_callback = tell_callback;
1068 encoder->private_->metadata_callback = metadata_callback;
1069 encoder->private_->client_data = client_data;
1071 if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
1072 /* the above function sets the state for us in case of an error */
1073 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1076 if(!FLAC__bitwriter_init(encoder->private_->frame)) {
1077 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1078 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1082 * Set up the verify stuff if necessary
1084 if(encoder->protected_->verify) {
1086 * First, set up the fifo which will hold the
1087 * original signal to compare against
1089 encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
1090 for(i = 0; i < encoder->protected_->channels; i++) {
1091 if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*) safe_malloc_mul_2op_p(sizeof(FLAC__int32), /*times*/encoder->private_->verify.input_fifo.size))) {
1092 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1093 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1096 encoder->private_->verify.input_fifo.tail = 0;
1099 * Now set up a stream decoder for verification
1101 if(0 == encoder->private_->verify.decoder) {
1102 encoder->private_->verify.decoder = FLAC__stream_decoder_new();
1103 if(0 == encoder->private_->verify.decoder) {
1104 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1105 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1109 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) {
1110 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1111 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1114 encoder->private_->verify.error_stats.absolute_sample = 0;
1115 encoder->private_->verify.error_stats.frame_number = 0;
1116 encoder->private_->verify.error_stats.channel = 0;
1117 encoder->private_->verify.error_stats.sample = 0;
1118 encoder->private_->verify.error_stats.expected = 0;
1119 encoder->private_->verify.error_stats.got = 0;
1122 * These must be done before we write any metadata, because that
1123 * calls the write_callback, which uses these values.
1125 encoder->private_->first_seekpoint_to_check = 0;
1126 encoder->private_->samples_written = 0;
1127 encoder->protected_->streaminfo_offset = 0;
1128 encoder->protected_->seektable_offset = 0;
1129 encoder->protected_->audio_offset = 0;
1132 * write the stream header
1134 if(encoder->protected_->verify)
1135 encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1136 if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1137 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1138 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1140 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1141 /* the above function sets the state for us in case of an error */
1142 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1146 * write the STREAMINFO metadata block
1148 if(encoder->protected_->verify)
1149 encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1150 encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1151 encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1152 encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1153 encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1154 encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1155 encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1156 encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1157 encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1158 encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1159 encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1160 encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1161 memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1162 if(encoder->protected_->do_md5)
1163 FLAC__MD5Init(&encoder->private_->md5context);
1164 if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1165 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1166 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1168 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1169 /* the above function sets the state for us in case of an error */
1170 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1174 * Now that the STREAMINFO block is written, we can init this to an
1175 * absurdly-high value...
1177 encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1178 /* ... and clear this to 0 */
1179 encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1182 * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1183 * if not, we will write an empty one (FLAC__add_metadata_block()
1184 * automatically supplies the vendor string).
1186 * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1187 * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
1188 * true it will have already insured that the metadata list is properly
1189 * ordered.)
1191 if(!metadata_has_vorbis_comment) {
1192 FLAC__StreamMetadata vorbis_comment;
1193 vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1194 vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1195 vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1196 vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1197 vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1198 vorbis_comment.data.vorbis_comment.num_comments = 0;
1199 vorbis_comment.data.vorbis_comment.comments = 0;
1200 if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1201 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1202 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1204 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1205 /* the above function sets the state for us in case of an error */
1206 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1211 * write the user's metadata blocks
1213 for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1214 encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1215 if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1216 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1217 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1219 if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1220 /* the above function sets the state for us in case of an error */
1221 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1225 /* now that all the metadata is written, we save the stream offset */
1226 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 */
1227 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1228 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1231 if(encoder->protected_->verify)
1232 encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1234 return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1237 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1238 FLAC__StreamEncoder *encoder,
1239 FLAC__StreamEncoderWriteCallback write_callback,
1240 FLAC__StreamEncoderSeekCallback seek_callback,
1241 FLAC__StreamEncoderTellCallback tell_callback,
1242 FLAC__StreamEncoderMetadataCallback metadata_callback,
1243 void *client_data
1246 return init_stream_internal_(
1247 encoder,
1248 /*read_callback=*/0,
1249 write_callback,
1250 seek_callback,
1251 tell_callback,
1252 metadata_callback,
1253 client_data,
1254 /*is_ogg=*/false
1258 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1259 FLAC__StreamEncoder *encoder,
1260 FLAC__StreamEncoderReadCallback read_callback,
1261 FLAC__StreamEncoderWriteCallback write_callback,
1262 FLAC__StreamEncoderSeekCallback seek_callback,
1263 FLAC__StreamEncoderTellCallback tell_callback,
1264 FLAC__StreamEncoderMetadataCallback metadata_callback,
1265 void *client_data
1268 return init_stream_internal_(
1269 encoder,
1270 read_callback,
1271 write_callback,
1272 seek_callback,
1273 tell_callback,
1274 metadata_callback,
1275 client_data,
1276 /*is_ogg=*/true
1280 #if 0
1281 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1282 FLAC__StreamEncoder *encoder,
1283 FILE *file,
1284 FLAC__StreamEncoderProgressCallback progress_callback,
1285 void *client_data,
1286 FLAC__bool is_ogg
1289 FLAC__StreamEncoderInitStatus init_status;
1291 FLAC__ASSERT(0 != encoder);
1292 FLAC__ASSERT(0 != file);
1294 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1295 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1297 /* double protection */
1298 if(file == 0) {
1299 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1300 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1304 * To make sure that our file does not go unclosed after an error, we
1305 * must assign the FILE pointer before any further error can occur in
1306 * this routine.
1308 if(file == stdout)
1309 file = get_binary_stdout_(); /* just to be safe */
1311 #ifdef _WIN32
1313 * Windows can suffer quite badly from disk fragmentation. This can be
1314 * reduced significantly by setting the output buffer size to be 10MB.
1316 setvbuf(file, NULL, _IOFBF, 10*1024*1024);
1317 #endif
1318 encoder->private_->file = file;
1320 encoder->private_->progress_callback = progress_callback;
1321 encoder->private_->bytes_written = 0;
1322 encoder->private_->samples_written = 0;
1323 encoder->private_->frames_written = 0;
1325 init_status = init_stream_internal_(
1326 encoder,
1327 encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1328 file_write_callback_,
1329 encoder->private_->file == stdout? 0 : file_seek_callback_,
1330 encoder->private_->file == stdout? 0 : file_tell_callback_,
1331 /*metadata_callback=*/0,
1332 client_data,
1333 is_ogg
1335 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1336 /* the above function sets the state for us in case of an error */
1337 return init_status;
1341 unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1343 FLAC__ASSERT(blocksize != 0);
1344 encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1347 return init_status;
1350 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1351 FLAC__StreamEncoder *encoder,
1352 FILE *file,
1353 FLAC__StreamEncoderProgressCallback progress_callback,
1354 void *client_data
1357 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1360 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1361 FLAC__StreamEncoder *encoder,
1362 FILE *file,
1363 FLAC__StreamEncoderProgressCallback progress_callback,
1364 void *client_data
1367 return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1370 static FLAC__StreamEncoderInitStatus init_file_internal_(
1371 FLAC__StreamEncoder *encoder,
1372 const char *filename,
1373 FLAC__StreamEncoderProgressCallback progress_callback,
1374 void *client_data,
1375 FLAC__bool is_ogg
1378 FILE *file;
1380 FLAC__ASSERT(0 != encoder);
1383 * To make sure that our file does not go unclosed after an error, we
1384 * have to do the same entrance checks here that are later performed
1385 * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1387 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1388 return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1390 file = filename? flac_fopen(filename, "w+b") : stdout;
1392 if(file == 0) {
1393 encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1394 return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1397 return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1400 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1401 FLAC__StreamEncoder *encoder,
1402 const char *filename,
1403 FLAC__StreamEncoderProgressCallback progress_callback,
1404 void *client_data
1407 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1410 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1411 FLAC__StreamEncoder *encoder,
1412 const char *filename,
1413 FLAC__StreamEncoderProgressCallback progress_callback,
1414 void *client_data
1417 return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1419 #endif
1421 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1423 FLAC__bool error = false;
1425 FLAC__ASSERT(0 != encoder);
1426 FLAC__ASSERT(0 != encoder->private_);
1427 FLAC__ASSERT(0 != encoder->protected_);
1429 if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1430 return true;
1432 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1433 if(encoder->private_->current_sample_number != 0) {
1434 const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1435 encoder->protected_->blocksize = encoder->private_->current_sample_number;
1436 if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1437 error = true;
1441 if(encoder->protected_->do_md5)
1442 FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1444 if(!encoder->private_->is_being_deleted) {
1445 if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1446 if(encoder->private_->seek_callback) {
1447 #if FLAC__HAS_OGG
1448 if(encoder->private_->is_ogg)
1449 update_ogg_metadata_(encoder);
1450 else
1451 #endif
1452 update_metadata_(encoder);
1454 /* check if an error occurred while updating metadata */
1455 if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1456 error = true;
1458 if(encoder->private_->metadata_callback)
1459 encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1462 if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1463 if(!error)
1464 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1465 error = true;
1469 if(0 != encoder->private_->file) {
1470 if(encoder->private_->file != stdout)
1471 fclose(encoder->private_->file);
1472 encoder->private_->file = 0;
1475 #if FLAC__HAS_OGG
1476 if(encoder->private_->is_ogg)
1477 FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1478 #endif
1480 free_(encoder);
1481 set_defaults_(encoder);
1483 if(!error)
1484 encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1486 return !error;
1489 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1491 FLAC__ASSERT(0 != encoder);
1492 FLAC__ASSERT(0 != encoder->private_);
1493 FLAC__ASSERT(0 != encoder->protected_);
1494 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1495 return false;
1496 #if FLAC__HAS_OGG
1497 /* can't check encoder->private_->is_ogg since that's not set until init time */
1498 FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1499 return true;
1500 #else
1501 (void)value;
1502 return false;
1503 #endif
1506 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1508 FLAC__ASSERT(0 != encoder);
1509 FLAC__ASSERT(0 != encoder->private_);
1510 FLAC__ASSERT(0 != encoder->protected_);
1511 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1512 return false;
1513 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1514 encoder->protected_->verify = value;
1515 #endif
1516 return true;
1519 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1521 FLAC__ASSERT(0 != encoder);
1522 FLAC__ASSERT(0 != encoder->private_);
1523 FLAC__ASSERT(0 != encoder->protected_);
1524 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1525 return false;
1526 encoder->protected_->streamable_subset = value;
1527 return true;
1530 inline FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
1532 FLAC__ASSERT(0 != encoder);
1533 FLAC__ASSERT(0 != encoder->private_);
1534 FLAC__ASSERT(0 != encoder->protected_);
1535 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1536 return false;
1537 encoder->protected_->do_md5 = value;
1538 return true;
1541 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1543 FLAC__ASSERT(0 != encoder);
1544 FLAC__ASSERT(0 != encoder->private_);
1545 FLAC__ASSERT(0 != encoder->protected_);
1546 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1547 return false;
1548 encoder->protected_->channels = value;
1549 return true;
1552 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1554 FLAC__ASSERT(0 != encoder);
1555 FLAC__ASSERT(0 != encoder->private_);
1556 FLAC__ASSERT(0 != encoder->protected_);
1557 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1558 return false;
1559 encoder->protected_->bits_per_sample = value;
1560 return true;
1563 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1565 FLAC__ASSERT(0 != encoder);
1566 FLAC__ASSERT(0 != encoder->private_);
1567 FLAC__ASSERT(0 != encoder->protected_);
1568 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1569 return false;
1570 encoder->protected_->sample_rate = value;
1571 return true;
1574 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1576 FLAC__bool ok = true;
1577 FLAC__ASSERT(0 != encoder);
1578 FLAC__ASSERT(0 != encoder->private_);
1579 FLAC__ASSERT(0 != encoder->protected_);
1580 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1581 return false;
1582 if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1583 value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1584 ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
1585 ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
1586 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1587 #if 1
1588 ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
1589 #else
1590 /* equivalent to -A tukey(0.5) */
1591 encoder->protected_->num_apodizations = 1;
1592 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1593 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1594 #endif
1595 #endif
1596 ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
1597 ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
1598 ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1599 ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
1600 ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
1601 ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1602 ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1603 ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
1604 return ok;
1607 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1609 FLAC__ASSERT(0 != encoder);
1610 FLAC__ASSERT(0 != encoder->private_);
1611 FLAC__ASSERT(0 != encoder->protected_);
1612 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1613 return false;
1614 encoder->protected_->blocksize = value;
1615 return true;
1618 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1620 FLAC__ASSERT(0 != encoder);
1621 FLAC__ASSERT(0 != encoder->private_);
1622 FLAC__ASSERT(0 != encoder->protected_);
1623 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1624 return false;
1625 encoder->protected_->do_mid_side_stereo = value;
1626 return true;
1629 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1631 FLAC__ASSERT(0 != encoder);
1632 FLAC__ASSERT(0 != encoder->private_);
1633 FLAC__ASSERT(0 != encoder->protected_);
1634 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1635 return false;
1636 encoder->protected_->loose_mid_side_stereo = value;
1637 return true;
1640 /*@@@@add to tests*/
1641 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1643 FLAC__ASSERT(0 != encoder);
1644 FLAC__ASSERT(0 != encoder->private_);
1645 FLAC__ASSERT(0 != encoder->protected_);
1646 FLAC__ASSERT(0 != specification);
1647 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1648 return false;
1649 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1650 (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1651 #else
1652 encoder->protected_->num_apodizations = 0;
1653 while(1) {
1654 const char *s = strchr(specification, ';');
1655 const size_t n = s? (size_t)(s - specification) : strlen(specification);
1656 if (n==8 && 0 == strncmp("bartlett" , specification, n))
1657 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1658 else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1659 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1660 else if(n==8 && 0 == strncmp("blackman" , specification, n))
1661 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1662 else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1663 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1664 else if(n==6 && 0 == strncmp("connes" , specification, n))
1665 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1666 else if(n==7 && 0 == strncmp("flattop" , specification, n))
1667 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1668 else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
1669 FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1670 if (stddev > 0.0 && stddev <= 0.5) {
1671 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1672 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1675 else if(n==7 && 0 == strncmp("hamming" , specification, n))
1676 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1677 else if(n==4 && 0 == strncmp("hann" , specification, n))
1678 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1679 else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1680 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1681 else if(n==7 && 0 == strncmp("nuttall" , specification, n))
1682 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1683 else if(n==9 && 0 == strncmp("rectangle" , specification, n))
1684 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1685 else if(n==8 && 0 == strncmp("triangle" , specification, n))
1686 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1687 else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
1688 FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1689 if (p >= 0.0 && p <= 1.0) {
1690 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1691 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1694 else if(n>15 && 0 == strncmp("partial_tukey(" , specification, 14)) {
1695 FLAC__int32 tukey_parts = (FLAC__int32)strtod(specification+14, 0);
1696 const char *si_1 = strchr(specification, '/');
1697 FLAC__real overlap = si_1?flac_min((FLAC__real)strtod(si_1+1, 0),0.99f):0.1f;
1698 FLAC__real overlap_units = 1.0f/(1.0f - overlap) - 1.0f;
1699 const char *si_2 = strchr((si_1?(si_1+1):specification), '/');
1700 FLAC__real tukey_p = si_2?(FLAC__real)strtod(si_2+1, 0):0.2f;
1702 if (tukey_parts <= 1) {
1703 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = tukey_p;
1704 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1705 }else if (encoder->protected_->num_apodizations + tukey_parts < 32){
1706 FLAC__int32 m;
1707 for(m = 0; m < tukey_parts; m++){
1708 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.p = tukey_p;
1709 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.start = m/(tukey_parts+overlap_units);
1710 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.end = (m+1+overlap_units)/(tukey_parts+overlap_units);
1711 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_PARTIAL_TUKEY;
1715 else if(n>16 && 0 == strncmp("punchout_tukey(" , specification, 15)) {
1716 FLAC__int32 tukey_parts = (FLAC__int32)strtod(specification+15, 0);
1717 const char *si_1 = strchr(specification, '/');
1718 FLAC__real overlap = si_1?flac_min((FLAC__real)strtod(si_1+1, 0),0.99f):0.2f;
1719 FLAC__real overlap_units = 1.0f/(1.0f - overlap) - 1.0f;
1720 const char *si_2 = strchr((si_1?(si_1+1):specification), '/');
1721 FLAC__real tukey_p = si_2?(FLAC__real)strtod(si_2+1, 0):0.2f;
1723 if (tukey_parts <= 1) {
1724 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = tukey_p;
1725 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1726 }else if (encoder->protected_->num_apodizations + tukey_parts < 32){
1727 FLAC__int32 m;
1728 for(m = 0; m < tukey_parts; m++){
1729 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.p = tukey_p;
1730 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.start = m/(tukey_parts+overlap_units);
1731 encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.end = (m+1+overlap_units)/(tukey_parts+overlap_units);
1732 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_PUNCHOUT_TUKEY;
1736 else if(n==5 && 0 == strncmp("welch" , specification, n))
1737 encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1738 if (encoder->protected_->num_apodizations == 32)
1739 break;
1740 if (s)
1741 specification = s+1;
1742 else
1743 break;
1745 if(encoder->protected_->num_apodizations == 0) {
1746 encoder->protected_->num_apodizations = 1;
1747 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1748 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1750 #endif
1751 return true;
1754 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1756 FLAC__ASSERT(0 != encoder);
1757 FLAC__ASSERT(0 != encoder->private_);
1758 FLAC__ASSERT(0 != encoder->protected_);
1759 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1760 return false;
1761 encoder->protected_->max_lpc_order = value;
1762 return true;
1765 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1767 FLAC__ASSERT(0 != encoder);
1768 FLAC__ASSERT(0 != encoder->private_);
1769 FLAC__ASSERT(0 != encoder->protected_);
1770 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1771 return false;
1772 encoder->protected_->qlp_coeff_precision = value;
1773 return true;
1776 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1778 FLAC__ASSERT(0 != encoder);
1779 FLAC__ASSERT(0 != encoder->private_);
1780 FLAC__ASSERT(0 != encoder->protected_);
1781 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1782 return false;
1783 encoder->protected_->do_qlp_coeff_prec_search = value;
1784 return true;
1787 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1789 FLAC__ASSERT(0 != encoder);
1790 FLAC__ASSERT(0 != encoder->private_);
1791 FLAC__ASSERT(0 != encoder->protected_);
1792 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1793 return false;
1794 #if 0
1795 /*@@@ deprecated: */
1796 encoder->protected_->do_escape_coding = value;
1797 #else
1798 (void)value;
1799 #endif
1800 return true;
1803 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1805 FLAC__ASSERT(0 != encoder);
1806 FLAC__ASSERT(0 != encoder->private_);
1807 FLAC__ASSERT(0 != encoder->protected_);
1808 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1809 return false;
1810 encoder->protected_->do_exhaustive_model_search = value;
1811 return true;
1814 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1816 FLAC__ASSERT(0 != encoder);
1817 FLAC__ASSERT(0 != encoder->private_);
1818 FLAC__ASSERT(0 != encoder->protected_);
1819 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1820 return false;
1821 encoder->protected_->min_residual_partition_order = value;
1822 return true;
1825 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1827 FLAC__ASSERT(0 != encoder);
1828 FLAC__ASSERT(0 != encoder->private_);
1829 FLAC__ASSERT(0 != encoder->protected_);
1830 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1831 return false;
1832 encoder->protected_->max_residual_partition_order = value;
1833 return true;
1836 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1838 FLAC__ASSERT(0 != encoder);
1839 FLAC__ASSERT(0 != encoder->private_);
1840 FLAC__ASSERT(0 != encoder->protected_);
1841 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1842 return false;
1843 #if 0
1844 /*@@@ deprecated: */
1845 encoder->protected_->rice_parameter_search_dist = value;
1846 #else
1847 (void)value;
1848 #endif
1849 return true;
1852 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1854 FLAC__ASSERT(0 != encoder);
1855 FLAC__ASSERT(0 != encoder->private_);
1856 FLAC__ASSERT(0 != encoder->protected_);
1857 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1858 return false;
1859 encoder->protected_->total_samples_estimate = value;
1860 return true;
1863 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1865 FLAC__ASSERT(0 != encoder);
1866 FLAC__ASSERT(0 != encoder->private_);
1867 FLAC__ASSERT(0 != encoder->protected_);
1868 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1869 return false;
1870 if(0 == metadata)
1871 num_blocks = 0;
1872 if(0 == num_blocks)
1873 metadata = 0;
1874 /* realloc() does not do exactly what we want so... */
1875 if(encoder->protected_->metadata) {
1876 free(encoder->protected_->metadata);
1877 encoder->protected_->metadata = 0;
1878 encoder->protected_->num_metadata_blocks = 0;
1880 if(num_blocks) {
1881 FLAC__StreamMetadata **m;
1882 if(0 == (m = (FLAC__StreamMetadata**) safe_malloc_mul_2op_p(sizeof(m[0]), /*times*/num_blocks)))
1883 return false;
1884 memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1885 encoder->protected_->metadata = m;
1886 encoder->protected_->num_metadata_blocks = num_blocks;
1888 #if FLAC__HAS_OGG
1889 if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1890 return false;
1891 #endif
1892 return true;
1896 * These three functions are not static, but not publically exposed in
1897 * include/FLAC/ either. They are used by the test suite.
1899 inline FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1901 FLAC__ASSERT(0 != encoder);
1902 FLAC__ASSERT(0 != encoder->private_);
1903 FLAC__ASSERT(0 != encoder->protected_);
1904 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1905 return false;
1906 encoder->private_->disable_constant_subframes = value;
1907 return true;
1910 inline FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1912 FLAC__ASSERT(0 != encoder);
1913 FLAC__ASSERT(0 != encoder->private_);
1914 FLAC__ASSERT(0 != encoder->protected_);
1915 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1916 return false;
1917 encoder->private_->disable_fixed_subframes = value;
1918 return true;
1921 inline FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1923 FLAC__ASSERT(0 != encoder);
1924 FLAC__ASSERT(0 != encoder->private_);
1925 FLAC__ASSERT(0 != encoder->protected_);
1926 if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1927 return false;
1928 encoder->private_->disable_verbatim_subframes = value;
1929 return true;
1932 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1934 FLAC__ASSERT(0 != encoder);
1935 FLAC__ASSERT(0 != encoder->private_);
1936 FLAC__ASSERT(0 != encoder->protected_);
1937 return encoder->protected_->state;
1940 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1942 FLAC__ASSERT(0 != encoder);
1943 FLAC__ASSERT(0 != encoder->private_);
1944 FLAC__ASSERT(0 != encoder->protected_);
1945 if(encoder->protected_->verify)
1946 return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1947 else
1948 return FLAC__STREAM_DECODER_UNINITIALIZED;
1951 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1953 FLAC__ASSERT(0 != encoder);
1954 FLAC__ASSERT(0 != encoder->private_);
1955 FLAC__ASSERT(0 != encoder->protected_);
1956 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1957 return FLAC__StreamEncoderStateString[encoder->protected_->state];
1958 else
1959 return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1962 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)
1964 FLAC__ASSERT(0 != encoder);
1965 FLAC__ASSERT(0 != encoder->private_);
1966 FLAC__ASSERT(0 != encoder->protected_);
1967 if(0 != absolute_sample)
1968 *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1969 if(0 != frame_number)
1970 *frame_number = encoder->private_->verify.error_stats.frame_number;
1971 if(0 != channel)
1972 *channel = encoder->private_->verify.error_stats.channel;
1973 if(0 != sample)
1974 *sample = encoder->private_->verify.error_stats.sample;
1975 if(0 != expected)
1976 *expected = encoder->private_->verify.error_stats.expected;
1977 if(0 != got)
1978 *got = encoder->private_->verify.error_stats.got;
1981 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1983 FLAC__ASSERT(0 != encoder);
1984 FLAC__ASSERT(0 != encoder->private_);
1985 FLAC__ASSERT(0 != encoder->protected_);
1986 return encoder->protected_->verify;
1989 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1991 FLAC__ASSERT(0 != encoder);
1992 FLAC__ASSERT(0 != encoder->private_);
1993 FLAC__ASSERT(0 != encoder->protected_);
1994 return encoder->protected_->streamable_subset;
1997 inline FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
1999 FLAC__ASSERT(0 != encoder);
2000 FLAC__ASSERT(0 != encoder->private_);
2001 FLAC__ASSERT(0 != encoder->protected_);
2002 return encoder->protected_->do_md5;
2005 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
2007 FLAC__ASSERT(0 != encoder);
2008 FLAC__ASSERT(0 != encoder->private_);
2009 FLAC__ASSERT(0 != encoder->protected_);
2010 return encoder->protected_->channels;
2013 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
2015 FLAC__ASSERT(0 != encoder);
2016 FLAC__ASSERT(0 != encoder->private_);
2017 FLAC__ASSERT(0 != encoder->protected_);
2018 return encoder->protected_->bits_per_sample;
2021 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
2023 FLAC__ASSERT(0 != encoder);
2024 FLAC__ASSERT(0 != encoder->private_);
2025 FLAC__ASSERT(0 != encoder->protected_);
2026 return encoder->protected_->sample_rate;
2029 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
2031 FLAC__ASSERT(0 != encoder);
2032 FLAC__ASSERT(0 != encoder->private_);
2033 FLAC__ASSERT(0 != encoder->protected_);
2034 return encoder->protected_->blocksize;
2037 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
2039 FLAC__ASSERT(0 != encoder);
2040 FLAC__ASSERT(0 != encoder->private_);
2041 FLAC__ASSERT(0 != encoder->protected_);
2042 return encoder->protected_->do_mid_side_stereo;
2045 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
2047 FLAC__ASSERT(0 != encoder);
2048 FLAC__ASSERT(0 != encoder->private_);
2049 FLAC__ASSERT(0 != encoder->protected_);
2050 return encoder->protected_->loose_mid_side_stereo;
2053 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
2055 FLAC__ASSERT(0 != encoder);
2056 FLAC__ASSERT(0 != encoder->private_);
2057 FLAC__ASSERT(0 != encoder->protected_);
2058 return encoder->protected_->max_lpc_order;
2061 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
2063 FLAC__ASSERT(0 != encoder);
2064 FLAC__ASSERT(0 != encoder->private_);
2065 FLAC__ASSERT(0 != encoder->protected_);
2066 return encoder->protected_->qlp_coeff_precision;
2069 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
2071 FLAC__ASSERT(0 != encoder);
2072 FLAC__ASSERT(0 != encoder->private_);
2073 FLAC__ASSERT(0 != encoder->protected_);
2074 return encoder->protected_->do_qlp_coeff_prec_search;
2077 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
2079 FLAC__ASSERT(0 != encoder);
2080 FLAC__ASSERT(0 != encoder->private_);
2081 FLAC__ASSERT(0 != encoder->protected_);
2082 return encoder->protected_->do_escape_coding;
2085 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
2087 FLAC__ASSERT(0 != encoder);
2088 FLAC__ASSERT(0 != encoder->private_);
2089 FLAC__ASSERT(0 != encoder->protected_);
2090 return encoder->protected_->do_exhaustive_model_search;
2093 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
2095 FLAC__ASSERT(0 != encoder);
2096 FLAC__ASSERT(0 != encoder->private_);
2097 FLAC__ASSERT(0 != encoder->protected_);
2098 return encoder->protected_->min_residual_partition_order;
2101 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
2103 FLAC__ASSERT(0 != encoder);
2104 FLAC__ASSERT(0 != encoder->private_);
2105 FLAC__ASSERT(0 != encoder->protected_);
2106 return encoder->protected_->max_residual_partition_order;
2109 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
2111 FLAC__ASSERT(0 != encoder);
2112 FLAC__ASSERT(0 != encoder->private_);
2113 FLAC__ASSERT(0 != encoder->protected_);
2114 return encoder->protected_->rice_parameter_search_dist;
2117 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
2119 FLAC__ASSERT(0 != encoder);
2120 FLAC__ASSERT(0 != encoder->private_);
2121 FLAC__ASSERT(0 != encoder->protected_);
2122 return encoder->protected_->total_samples_estimate;
2125 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
2127 unsigned i, j = 0, channel;
2128 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2130 FLAC__ASSERT(0 != encoder);
2131 FLAC__ASSERT(0 != encoder->private_);
2132 FLAC__ASSERT(0 != encoder->protected_);
2133 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2135 do {
2136 const unsigned n = flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
2138 if(encoder->protected_->verify)
2139 append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
2141 for(channel = 0; channel < channels; channel++)
2142 memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
2144 if(encoder->protected_->do_mid_side_stereo) {
2145 FLAC__ASSERT(channels == 2);
2146 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2147 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2148 encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
2149 encoder->private_->integer_signal_mid_side[0][i] = (buffer[0][j] + buffer[1][j]) >> 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
2152 else
2153 j += n;
2155 encoder->private_->current_sample_number += n;
2157 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2158 if(encoder->private_->current_sample_number > blocksize) {
2159 FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
2160 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2161 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2162 return false;
2163 /* move unprocessed overread samples to beginnings of arrays */
2164 for(channel = 0; channel < channels; channel++)
2165 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2166 if(encoder->protected_->do_mid_side_stereo) {
2167 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2168 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2170 encoder->private_->current_sample_number = 1;
2172 } while(j < samples);
2174 return true;
2177 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2179 unsigned i, j, k, channel;
2180 FLAC__int32 x, mid, side;
2181 const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2183 FLAC__ASSERT(0 != encoder);
2184 FLAC__ASSERT(0 != encoder->private_);
2185 FLAC__ASSERT(0 != encoder->protected_);
2186 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2188 j = k = 0;
2190 * we have several flavors of the same basic loop, optimized for
2191 * different conditions:
2193 if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2195 * stereo coding: unroll channel loop
2197 do {
2198 if(encoder->protected_->verify)
2199 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2201 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2202 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2203 encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2204 x = buffer[k++];
2205 encoder->private_->integer_signal[1][i] = x;
2206 mid += x;
2207 side -= x;
2208 mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2209 encoder->private_->integer_signal_mid_side[1][i] = side;
2210 encoder->private_->integer_signal_mid_side[0][i] = mid;
2212 encoder->private_->current_sample_number = i;
2213 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2214 if(i > blocksize) {
2215 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2216 return false;
2217 /* move unprocessed overread samples to beginnings of arrays */
2218 FLAC__ASSERT(i == blocksize+OVERREAD_);
2219 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2220 encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
2221 encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
2222 encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2223 encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2224 encoder->private_->current_sample_number = 1;
2226 } while(j < samples);
2228 else {
2230 * independent channel coding: buffer each channel in inner loop
2232 do {
2233 if(encoder->protected_->verify)
2234 append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2236 /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2237 for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2238 for(channel = 0; channel < channels; channel++)
2239 encoder->private_->integer_signal[channel][i] = buffer[k++];
2241 encoder->private_->current_sample_number = i;
2242 /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2243 if(i > blocksize) {
2244 if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2245 return false;
2246 /* move unprocessed overread samples to beginnings of arrays */
2247 FLAC__ASSERT(i == blocksize+OVERREAD_);
2248 FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2249 for(channel = 0; channel < channels; channel++)
2250 encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2251 encoder->private_->current_sample_number = 1;
2253 } while(j < samples);
2256 return true;
2259 /***********************************************************************
2261 * Private class methods
2263 ***********************************************************************/
2265 void set_defaults_(FLAC__StreamEncoder *encoder)
2267 FLAC__ASSERT(0 != encoder);
2269 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2270 encoder->protected_->verify = true;
2271 #else
2272 encoder->protected_->verify = false;
2273 #endif
2274 encoder->protected_->streamable_subset = true;
2275 encoder->protected_->do_md5 = true;
2276 encoder->protected_->do_mid_side_stereo = false;
2277 encoder->protected_->loose_mid_side_stereo = false;
2278 encoder->protected_->channels = 2;
2279 encoder->protected_->bits_per_sample = 16;
2280 encoder->protected_->sample_rate = 44100;
2281 encoder->protected_->blocksize = 0;
2282 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2283 encoder->protected_->num_apodizations = 1;
2284 encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2285 encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2286 #endif
2287 encoder->protected_->max_lpc_order = 0;
2288 encoder->protected_->qlp_coeff_precision = 0;
2289 encoder->protected_->do_qlp_coeff_prec_search = false;
2290 encoder->protected_->do_exhaustive_model_search = false;
2291 encoder->protected_->do_escape_coding = false;
2292 encoder->protected_->min_residual_partition_order = 0;
2293 encoder->protected_->max_residual_partition_order = 0;
2294 encoder->protected_->rice_parameter_search_dist = 0;
2295 encoder->protected_->total_samples_estimate = 0;
2296 encoder->protected_->metadata = 0;
2297 encoder->protected_->num_metadata_blocks = 0;
2299 encoder->private_->seek_table = 0;
2300 encoder->private_->disable_constant_subframes = false;
2301 encoder->private_->disable_fixed_subframes = false;
2302 encoder->private_->disable_verbatim_subframes = false;
2303 #if FLAC__HAS_OGG
2304 encoder->private_->is_ogg = false;
2305 #endif
2306 encoder->private_->read_callback = 0;
2307 encoder->private_->write_callback = 0;
2308 encoder->private_->seek_callback = 0;
2309 encoder->private_->tell_callback = 0;
2310 encoder->private_->metadata_callback = 0;
2311 encoder->private_->progress_callback = 0;
2312 encoder->private_->client_data = 0;
2314 #if FLAC__HAS_OGG
2315 FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2316 #endif
2318 FLAC__stream_encoder_set_compression_level(encoder, 5);
2321 void free_(FLAC__StreamEncoder *encoder)
2323 unsigned i, channel;
2325 FLAC__ASSERT(0 != encoder);
2326 if(encoder->protected_->metadata) {
2327 free(encoder->protected_->metadata);
2328 encoder->protected_->metadata = 0;
2329 encoder->protected_->num_metadata_blocks = 0;
2331 for(i = 0; i < encoder->protected_->channels; i++) {
2332 if(0 != encoder->private_->integer_signal_unaligned[i]) {
2333 free(encoder->private_->integer_signal_unaligned[i]);
2334 encoder->private_->integer_signal_unaligned[i] = 0;
2336 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2337 if(0 != encoder->private_->real_signal_unaligned[i]) {
2338 free(encoder->private_->real_signal_unaligned[i]);
2339 encoder->private_->real_signal_unaligned[i] = 0;
2341 #endif
2343 for(i = 0; i < 2; i++) {
2344 if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2345 free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2346 encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2348 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2349 if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2350 free(encoder->private_->real_signal_mid_side_unaligned[i]);
2351 encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2353 #endif
2355 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2356 for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2357 if(0 != encoder->private_->window_unaligned[i]) {
2358 free(encoder->private_->window_unaligned[i]);
2359 encoder->private_->window_unaligned[i] = 0;
2362 if(0 != encoder->private_->windowed_signal_unaligned) {
2363 free(encoder->private_->windowed_signal_unaligned);
2364 encoder->private_->windowed_signal_unaligned = 0;
2366 #endif
2367 for(channel = 0; channel < encoder->protected_->channels; channel++) {
2368 for(i = 0; i < 2; i++) {
2369 if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2370 free(encoder->private_->residual_workspace_unaligned[channel][i]);
2371 encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2375 for(channel = 0; channel < 2; channel++) {
2376 for(i = 0; i < 2; i++) {
2377 if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2378 free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2379 encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2383 if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2384 free(encoder->private_->abs_residual_partition_sums_unaligned);
2385 encoder->private_->abs_residual_partition_sums_unaligned = 0;
2387 if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2388 free(encoder->private_->raw_bits_per_partition_unaligned);
2389 encoder->private_->raw_bits_per_partition_unaligned = 0;
2391 if(encoder->protected_->verify) {
2392 for(i = 0; i < encoder->protected_->channels; i++) {
2393 if(0 != encoder->private_->verify.input_fifo.data[i]) {
2394 free(encoder->private_->verify.input_fifo.data[i]);
2395 encoder->private_->verify.input_fifo.data[i] = 0;
2399 FLAC__bitwriter_free(encoder->private_->frame);
2402 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2404 FLAC__bool ok;
2405 unsigned i, channel;
2407 FLAC__ASSERT(new_blocksize > 0);
2408 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2409 FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2411 /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2412 if(new_blocksize <= encoder->private_->input_capacity)
2413 return true;
2415 ok = true;
2417 /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx() and ..._intrin_sse2()
2418 * require that the input arrays (in our case the integer signals)
2419 * have a buffer of up to 3 zeroes in front (at negative indices) for
2420 * alignment purposes; we use 4 in front to keep the data well-aligned.
2423 for(i = 0; ok && i < encoder->protected_->channels; i++) {
2424 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2425 memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2426 encoder->private_->integer_signal[i] += 4;
2427 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2428 #if 0 /* @@@ currently unused */
2429 if(encoder->protected_->max_lpc_order > 0)
2430 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2431 #endif
2432 #endif
2434 for(i = 0; ok && i < 2; i++) {
2435 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_mid_side_unaligned[i], &encoder->private_->integer_signal_mid_side[i]);
2436 memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2437 encoder->private_->integer_signal_mid_side[i] += 4;
2438 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2439 #if 0 /* @@@ currently unused */
2440 if(encoder->protected_->max_lpc_order > 0)
2441 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_mid_side_unaligned[i], &encoder->private_->real_signal_mid_side[i]);
2442 #endif
2443 #endif
2445 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2446 if(ok && encoder->protected_->max_lpc_order > 0) {
2447 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2448 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2449 ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2451 #endif
2452 for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2453 for(i = 0; ok && i < 2; i++) {
2454 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2457 for(channel = 0; ok && channel < 2; channel++) {
2458 for(i = 0; ok && i < 2; i++) {
2459 ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_mid_side_unaligned[channel][i], &encoder->private_->residual_workspace_mid_side[channel][i]);
2462 /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2463 /*@@@ new_blocksize*2 is too pessimistic, but to fix, we need smarter logic because a smaller new_blocksize can actually increase the # of partitions; would require moving this out into a separate function, then checking its capacity against the need of the current blocksize&min/max_partition_order (and maybe predictor order) */
2464 ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2465 if(encoder->protected_->do_escape_coding)
2466 ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2468 /* now adjust the windows if the blocksize has changed */
2469 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2470 if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2471 for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2472 switch(encoder->protected_->apodizations[i].type) {
2473 case FLAC__APODIZATION_BARTLETT:
2474 FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2475 break;
2476 case FLAC__APODIZATION_BARTLETT_HANN:
2477 FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2478 break;
2479 case FLAC__APODIZATION_BLACKMAN:
2480 FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2481 break;
2482 case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2483 FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2484 break;
2485 case FLAC__APODIZATION_CONNES:
2486 FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2487 break;
2488 case FLAC__APODIZATION_FLATTOP:
2489 FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2490 break;
2491 case FLAC__APODIZATION_GAUSS:
2492 FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2493 break;
2494 case FLAC__APODIZATION_HAMMING:
2495 FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2496 break;
2497 case FLAC__APODIZATION_HANN:
2498 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2499 break;
2500 case FLAC__APODIZATION_KAISER_BESSEL:
2501 FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2502 break;
2503 case FLAC__APODIZATION_NUTTALL:
2504 FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2505 break;
2506 case FLAC__APODIZATION_RECTANGLE:
2507 FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2508 break;
2509 case FLAC__APODIZATION_TRIANGLE:
2510 FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2511 break;
2512 case FLAC__APODIZATION_TUKEY:
2513 FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2514 break;
2515 case FLAC__APODIZATION_PARTIAL_TUKEY:
2516 FLAC__window_partial_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.multiple_tukey.p, encoder->protected_->apodizations[i].parameters.multiple_tukey.start, encoder->protected_->apodizations[i].parameters.multiple_tukey.end);
2517 break;
2518 case FLAC__APODIZATION_PUNCHOUT_TUKEY:
2519 FLAC__window_punchout_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.multiple_tukey.p, encoder->protected_->apodizations[i].parameters.multiple_tukey.start, encoder->protected_->apodizations[i].parameters.multiple_tukey.end);
2520 break;
2521 case FLAC__APODIZATION_WELCH:
2522 FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2523 break;
2524 default:
2525 FLAC__ASSERT(0);
2526 /* double protection */
2527 FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2528 break;
2532 #endif
2534 if(ok)
2535 encoder->private_->input_capacity = new_blocksize;
2536 else
2537 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2539 return ok;
2542 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2544 const FLAC__byte *buffer;
2545 size_t bytes;
2547 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2549 if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2550 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2551 return false;
2554 if(encoder->protected_->verify) {
2555 encoder->private_->verify.output.data = buffer;
2556 encoder->private_->verify.output.bytes = bytes;
2557 if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2558 encoder->private_->verify.needs_magic_hack = true;
2560 else {
2561 if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2562 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2563 FLAC__bitwriter_clear(encoder->private_->frame);
2564 if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2565 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2566 return false;
2571 if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2572 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2573 FLAC__bitwriter_clear(encoder->private_->frame);
2574 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2575 return false;
2578 FLAC__bitwriter_release_buffer(encoder->private_->frame);
2579 FLAC__bitwriter_clear(encoder->private_->frame);
2581 if(samples > 0) {
2582 encoder->private_->streaminfo.data.stream_info.min_framesize = flac_min(bytes, (size_t) encoder->private_->streaminfo.data.stream_info.min_framesize);
2583 encoder->private_->streaminfo.data.stream_info.max_framesize = flac_max(bytes, (size_t) encoder->private_->streaminfo.data.stream_info.max_framesize);
2586 return true;
2589 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2591 FLAC__StreamEncoderWriteStatus status;
2592 FLAC__uint64 output_position = 0;
2594 #if FLAC__HAS_OGG == 0
2595 (void)is_last_block;
2596 #endif
2598 /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2599 if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2600 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2601 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2605 * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2607 if(samples == 0) {
2608 FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
2609 if(type == FLAC__METADATA_TYPE_STREAMINFO)
2610 encoder->protected_->streaminfo_offset = output_position;
2611 else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2612 encoder->protected_->seektable_offset = output_position;
2616 * Mark the current seek point if hit (if audio_offset == 0 that
2617 * means we're still writing metadata and haven't hit the first
2618 * frame yet)
2620 if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2621 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2622 const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2623 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2624 FLAC__uint64 test_sample;
2625 unsigned i;
2626 for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2627 test_sample = encoder->private_->seek_table->points[i].sample_number;
2628 if(test_sample > frame_last_sample) {
2629 break;
2631 else if(test_sample >= frame_first_sample) {
2632 encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2633 encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2634 encoder->private_->seek_table->points[i].frame_samples = blocksize;
2635 encoder->private_->first_seekpoint_to_check++;
2636 /* DO NOT: "break;" and here's why:
2637 * The seektable template may contain more than one target
2638 * sample for any given frame; we will keep looping, generating
2639 * duplicate seekpoints for them, and we'll clean it up later,
2640 * just before writing the seektable back to the metadata.
2643 else {
2644 encoder->private_->first_seekpoint_to_check++;
2649 #if FLAC__HAS_OGG
2650 if(encoder->private_->is_ogg) {
2651 status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2652 &encoder->protected_->ogg_encoder_aspect,
2653 buffer,
2654 bytes,
2655 samples,
2656 encoder->private_->current_frame_number,
2657 is_last_block,
2658 (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2659 encoder,
2660 encoder->private_->client_data
2663 else
2664 #endif
2665 status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2667 if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2668 encoder->private_->bytes_written += bytes;
2669 encoder->private_->samples_written += samples;
2670 /* we keep a high watermark on the number of frames written because
2671 * when the encoder goes back to write metadata, 'current_frame'
2672 * will drop back to 0.
2674 encoder->private_->frames_written = flac_max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2676 else
2677 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2679 return status;
2682 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2683 void update_metadata_(const FLAC__StreamEncoder *encoder)
2685 FLAC__byte b[FLAC__STREAM_METADATA_SEEKPOINT_LENGTH];
2686 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2687 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2688 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2689 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2690 const unsigned bps = metadata->data.stream_info.bits_per_sample;
2691 FLAC__StreamEncoderSeekStatus seek_status;
2693 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2695 /* All this is based on intimate knowledge of the stream header
2696 * layout, but a change to the header format that would break this
2697 * would also break all streams encoded in the previous format.
2701 * Write MD5 signature
2704 const unsigned md5_offset =
2705 FLAC__STREAM_METADATA_HEADER_LENGTH +
2707 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2708 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2709 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2710 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2711 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2712 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2713 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2714 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2715 ) / 8;
2717 if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2718 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2719 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2720 return;
2722 if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2723 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2724 return;
2729 * Write total samples
2732 const unsigned total_samples_byte_offset =
2733 FLAC__STREAM_METADATA_HEADER_LENGTH +
2735 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2736 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2737 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2738 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2739 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2740 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2741 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2743 ) / 8;
2745 b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2746 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2747 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2748 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2749 b[4] = (FLAC__byte)(samples & 0xFF);
2750 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) {
2751 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2752 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2753 return;
2755 if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2756 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2757 return;
2762 * Write min/max framesize
2765 const unsigned min_framesize_offset =
2766 FLAC__STREAM_METADATA_HEADER_LENGTH +
2768 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2769 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2770 ) / 8;
2772 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2773 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2774 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2775 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2776 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2777 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2778 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) {
2779 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2780 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2781 return;
2783 if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2784 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2785 return;
2790 * Write seektable
2792 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2793 unsigned i;
2795 FLAC__format_seektable_sort(encoder->private_->seek_table);
2797 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2799 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) {
2800 if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2801 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2802 return;
2805 for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2806 FLAC__uint64 xx;
2807 unsigned x;
2808 xx = encoder->private_->seek_table->points[i].sample_number;
2809 b[7] = (FLAC__byte)xx; xx >>= 8;
2810 b[6] = (FLAC__byte)xx; xx >>= 8;
2811 b[5] = (FLAC__byte)xx; xx >>= 8;
2812 b[4] = (FLAC__byte)xx; xx >>= 8;
2813 b[3] = (FLAC__byte)xx; xx >>= 8;
2814 b[2] = (FLAC__byte)xx; xx >>= 8;
2815 b[1] = (FLAC__byte)xx; xx >>= 8;
2816 b[0] = (FLAC__byte)xx; //xx >>= 8;
2817 xx = encoder->private_->seek_table->points[i].stream_offset;
2818 b[15] = (FLAC__byte)xx; xx >>= 8;
2819 b[14] = (FLAC__byte)xx; xx >>= 8;
2820 b[13] = (FLAC__byte)xx; xx >>= 8;
2821 b[12] = (FLAC__byte)xx; xx >>= 8;
2822 b[11] = (FLAC__byte)xx; xx >>= 8;
2823 b[10] = (FLAC__byte)xx; xx >>= 8;
2824 b[9] = (FLAC__byte)xx; xx >>= 8;
2825 b[8] = (FLAC__byte)xx; //xx >>= 8;
2826 x = encoder->private_->seek_table->points[i].frame_samples;
2827 b[17] = (FLAC__byte)x; x >>= 8;
2828 b[16] = (FLAC__byte)x; //x >>= 8;
2829 if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2830 encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2831 return;
2837 #if FLAC__HAS_OGG
2838 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
2839 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2841 /* the # of bytes in the 1st packet that precede the STREAMINFO */
2842 static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2843 FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2844 FLAC__OGG_MAPPING_MAGIC_LENGTH +
2845 FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2846 FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2847 FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2848 FLAC__STREAM_SYNC_LENGTH
2850 FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2851 const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2852 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2853 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2854 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2855 ogg_page page;
2857 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2858 FLAC__ASSERT(0 != encoder->private_->seek_callback);
2860 /* Pre-check that client supports seeking, since we don't want the
2861 * ogg_helper code to ever have to deal with this condition.
2863 if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2864 return;
2866 /* All this is based on intimate knowledge of the stream header
2867 * layout, but a change to the header format that would break this
2868 * would also break all streams encoded in the previous format.
2872 ** Write STREAMINFO stats
2874 simple_ogg_page__init(&page);
2875 if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2876 simple_ogg_page__clear(&page);
2877 return; /* state already set */
2881 * Write MD5 signature
2884 const unsigned md5_offset =
2885 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2886 FLAC__STREAM_METADATA_HEADER_LENGTH +
2888 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2889 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2890 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2891 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2892 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2893 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2894 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2895 FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2896 ) / 8;
2898 if(md5_offset + 16 > (unsigned)page.body_len) {
2899 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2900 simple_ogg_page__clear(&page);
2901 return;
2903 memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2907 * Write total samples
2910 const unsigned total_samples_byte_offset =
2911 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2912 FLAC__STREAM_METADATA_HEADER_LENGTH +
2914 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2915 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2916 FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2917 FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2918 FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2919 FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2920 FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2922 ) / 8;
2924 if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2925 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2926 simple_ogg_page__clear(&page);
2927 return;
2929 b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2930 b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2931 b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2932 b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2933 b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2934 b[4] = (FLAC__byte)(samples & 0xFF);
2935 memcpy(page.body + total_samples_byte_offset, b, 5);
2939 * Write min/max framesize
2942 const unsigned min_framesize_offset =
2943 FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2944 FLAC__STREAM_METADATA_HEADER_LENGTH +
2946 FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2947 FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2948 ) / 8;
2950 if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2951 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2952 simple_ogg_page__clear(&page);
2953 return;
2955 b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2956 b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2957 b[2] = (FLAC__byte)(min_framesize & 0xFF);
2958 b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2959 b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2960 b[5] = (FLAC__byte)(max_framesize & 0xFF);
2961 memcpy(page.body + min_framesize_offset, b, 6);
2963 if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2964 simple_ogg_page__clear(&page);
2965 return; /* state already set */
2967 simple_ogg_page__clear(&page);
2970 * Write seektable
2972 if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2973 unsigned i;
2974 FLAC__byte *p;
2976 FLAC__format_seektable_sort(encoder->private_->seek_table);
2978 FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2980 simple_ogg_page__init(&page);
2981 if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2982 simple_ogg_page__clear(&page);
2983 return; /* state already set */
2986 if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
2987 encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2988 simple_ogg_page__clear(&page);
2989 return;
2992 for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
2993 FLAC__uint64 xx;
2994 unsigned x;
2995 xx = encoder->private_->seek_table->points[i].sample_number;
2996 b[7] = (FLAC__byte)xx; xx >>= 8;
2997 b[6] = (FLAC__byte)xx; xx >>= 8;
2998 b[5] = (FLAC__byte)xx; xx >>= 8;
2999 b[4] = (FLAC__byte)xx; xx >>= 8;
3000 b[3] = (FLAC__byte)xx; xx >>= 8;
3001 b[2] = (FLAC__byte)xx; xx >>= 8;
3002 b[1] = (FLAC__byte)xx; xx >>= 8;
3003 b[0] = (FLAC__byte)xx; xx >>= 8;
3004 xx = encoder->private_->seek_table->points[i].stream_offset;
3005 b[15] = (FLAC__byte)xx; xx >>= 8;
3006 b[14] = (FLAC__byte)xx; xx >>= 8;
3007 b[13] = (FLAC__byte)xx; xx >>= 8;
3008 b[12] = (FLAC__byte)xx; xx >>= 8;
3009 b[11] = (FLAC__byte)xx; xx >>= 8;
3010 b[10] = (FLAC__byte)xx; xx >>= 8;
3011 b[9] = (FLAC__byte)xx; xx >>= 8;
3012 b[8] = (FLAC__byte)xx; xx >>= 8;
3013 x = encoder->private_->seek_table->points[i].frame_samples;
3014 b[17] = (FLAC__byte)x; x >>= 8;
3015 b[16] = (FLAC__byte)x; x >>= 8;
3016 memcpy(p, b, 18);
3019 if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
3020 simple_ogg_page__clear(&page);
3021 return; /* state already set */
3023 simple_ogg_page__clear(&page);
3026 #endif
3028 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
3030 FLAC__uint16 crc;
3031 FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
3034 * Accumulate raw signal to the MD5 signature
3036 if(encoder->protected_->do_md5 && !FLAC__MD5Accumulate(&encoder->private_->md5context, (const FLAC__int32 * const *)encoder->private_->integer_signal, encoder->protected_->channels, encoder->protected_->blocksize, (encoder->protected_->bits_per_sample+7) / 8)) {
3037 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3038 return false;
3042 * Process the frame header and subframes into the frame bitbuffer
3044 if(!process_subframes_(encoder, is_fractional_block)) {
3045 /* the above function sets the state for us in case of an error */
3046 return false;
3050 * Zero-pad the frame to a byte_boundary
3052 if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
3053 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3054 return false;
3058 * CRC-16 the whole thing
3060 FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
3062 !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
3063 !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
3065 encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3066 return false;
3070 * Write it
3072 if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
3073 /* the above function sets the state for us in case of an error */
3074 return false;
3078 * Get ready for the next frame
3080 encoder->private_->current_sample_number = 0;
3081 encoder->private_->current_frame_number++;
3082 encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
3084 return true;
3087 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
3089 FLAC__FrameHeader frame_header;
3090 unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
3091 FLAC__bool do_independent, do_mid_side;
3094 * Calculate the min,max Rice partition orders
3096 if(is_fractional_block) {
3097 max_partition_order = 0;
3099 else {
3100 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
3101 max_partition_order = flac_min(max_partition_order, encoder->protected_->max_residual_partition_order);
3103 min_partition_order = flac_min(min_partition_order, max_partition_order);
3106 * Setup the frame
3108 frame_header.blocksize = encoder->protected_->blocksize;
3109 frame_header.sample_rate = encoder->protected_->sample_rate;
3110 frame_header.channels = encoder->protected_->channels;
3111 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
3112 frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
3113 frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
3114 frame_header.number.frame_number = encoder->private_->current_frame_number;
3117 * Figure out what channel assignments to try
3119 if(encoder->protected_->do_mid_side_stereo) {
3120 if(encoder->protected_->loose_mid_side_stereo) {
3121 if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
3122 do_independent = true;
3123 do_mid_side = true;
3125 else {
3126 do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
3127 do_mid_side = !do_independent;
3130 else {
3131 do_independent = true;
3132 do_mid_side = true;
3135 else {
3136 do_independent = true;
3137 do_mid_side = false;
3140 FLAC__ASSERT(do_independent || do_mid_side);
3143 * Check for wasted bits; set effective bps for each subframe
3145 if(do_independent) {
3146 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3147 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
3148 encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
3149 encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
3152 if(do_mid_side) {
3153 FLAC__ASSERT(encoder->protected_->channels == 2);
3154 for(channel = 0; channel < 2; channel++) {
3155 const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
3156 encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
3157 encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
3162 * First do a normal encoding pass of each independent channel
3164 if(do_independent) {
3165 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3166 if(!
3167 process_subframe_(
3168 encoder,
3169 min_partition_order,
3170 max_partition_order,
3171 &frame_header,
3172 encoder->private_->subframe_bps[channel],
3173 encoder->private_->integer_signal[channel],
3174 encoder->private_->subframe_workspace_ptr[channel],
3175 encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3176 encoder->private_->residual_workspace[channel],
3177 encoder->private_->best_subframe+channel,
3178 encoder->private_->best_subframe_bits+channel
3181 return false;
3186 * Now do mid and side channels if requested
3188 if(do_mid_side) {
3189 FLAC__ASSERT(encoder->protected_->channels == 2);
3191 for(channel = 0; channel < 2; channel++) {
3192 if(!
3193 process_subframe_(
3194 encoder,
3195 min_partition_order,
3196 max_partition_order,
3197 &frame_header,
3198 encoder->private_->subframe_bps_mid_side[channel],
3199 encoder->private_->integer_signal_mid_side[channel],
3200 encoder->private_->subframe_workspace_ptr_mid_side[channel],
3201 encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3202 encoder->private_->residual_workspace_mid_side[channel],
3203 encoder->private_->best_subframe_mid_side+channel,
3204 encoder->private_->best_subframe_bits_mid_side+channel
3207 return false;
3212 * Compose the frame bitbuffer
3214 if(do_mid_side) {
3215 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3216 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3217 FLAC__ChannelAssignment channel_assignment;
3219 FLAC__ASSERT(encoder->protected_->channels == 2);
3221 if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3222 channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3224 else {
3225 unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3226 unsigned min_bits;
3227 int ca;
3229 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3230 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
3231 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
3232 FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
3233 FLAC__ASSERT(do_independent && do_mid_side);
3235 /* We have to figure out which channel assignent results in the smallest frame */
3236 bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
3237 bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
3238 bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
3239 bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3241 channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3242 min_bits = bits[channel_assignment];
3243 for(ca = 1; ca <= 3; ca++) {
3244 if(bits[ca] < min_bits) {
3245 min_bits = bits[ca];
3246 channel_assignment = (FLAC__ChannelAssignment)ca;
3251 frame_header.channel_assignment = channel_assignment;
3253 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3254 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3255 return false;
3258 switch(channel_assignment) {
3259 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3260 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3261 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3262 break;
3263 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3264 left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
3265 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3266 break;
3267 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3268 left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3269 right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
3270 break;
3271 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3272 left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3273 right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3274 break;
3275 default:
3276 FLAC__ASSERT(0);
3279 switch(channel_assignment) {
3280 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3281 left_bps = encoder->private_->subframe_bps [0];
3282 right_bps = encoder->private_->subframe_bps [1];
3283 break;
3284 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3285 left_bps = encoder->private_->subframe_bps [0];
3286 right_bps = encoder->private_->subframe_bps_mid_side[1];
3287 break;
3288 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3289 left_bps = encoder->private_->subframe_bps_mid_side[1];
3290 right_bps = encoder->private_->subframe_bps [1];
3291 break;
3292 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3293 left_bps = encoder->private_->subframe_bps_mid_side[0];
3294 right_bps = encoder->private_->subframe_bps_mid_side[1];
3295 break;
3296 default:
3297 FLAC__ASSERT(0);
3300 /* note that encoder_add_subframe_ sets the state for us in case of an error */
3301 if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3302 return false;
3303 if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3304 return false;
3306 else {
3307 if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3308 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3309 return false;
3312 for(channel = 0; channel < encoder->protected_->channels; channel++) {
3313 if(!add_subframe_(encoder, frame_header.blocksize, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame)) {
3314 /* the above function sets the state for us in case of an error */
3315 return false;
3320 if(encoder->protected_->loose_mid_side_stereo) {
3321 encoder->private_->loose_mid_side_stereo_frame_count++;
3322 if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3323 encoder->private_->loose_mid_side_stereo_frame_count = 0;
3326 encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3328 return true;
3331 FLAC__bool process_subframe_(
3332 FLAC__StreamEncoder *encoder,
3333 unsigned min_partition_order,
3334 unsigned max_partition_order,
3335 const FLAC__FrameHeader *frame_header,
3336 unsigned subframe_bps,
3337 const FLAC__int32 integer_signal[],
3338 FLAC__Subframe *subframe[2],
3339 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3340 FLAC__int32 *residual[2],
3341 unsigned *best_subframe,
3342 unsigned *best_bits
3345 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3346 FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3347 #else
3348 FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3349 #endif
3350 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3351 FLAC__double lpc_residual_bits_per_sample;
3352 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 and x86 intrinsic routines need all the space */
3353 FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3354 unsigned min_lpc_order, max_lpc_order, lpc_order;
3355 unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3356 #endif
3357 unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3358 unsigned rice_parameter;
3359 unsigned _candidate_bits, _best_bits;
3360 unsigned _best_subframe;
3361 /* only use RICE2 partitions if stream bps > 16 */
3362 const unsigned rice_parameter_limit = FLAC__stream_encoder_get_bits_per_sample(encoder) > 16? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
3364 FLAC__ASSERT(frame_header->blocksize > 0);
3366 /* verbatim subframe is the baseline against which we measure other compressed subframes */
3367 _best_subframe = 0;
3368 if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3369 _best_bits = UINT_MAX;
3370 else
3371 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3373 if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3374 unsigned signal_is_constant = false;
3375 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);
3376 /* check for constant subframe */
3378 !encoder->private_->disable_constant_subframes &&
3379 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3380 fixed_residual_bits_per_sample[1] == 0.0
3381 #else
3382 fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3383 #endif
3385 /* the above means it's possible all samples are the same value; now double-check it: */
3386 unsigned i;
3387 signal_is_constant = true;
3388 for(i = 1; i < frame_header->blocksize; i++) {
3389 if(integer_signal[0] != integer_signal[i]) {
3390 signal_is_constant = false;
3391 break;
3395 if(signal_is_constant) {
3396 _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3397 if(_candidate_bits < _best_bits) {
3398 _best_subframe = !_best_subframe;
3399 _best_bits = _candidate_bits;
3402 else {
3403 if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3404 /* encode fixed */
3405 if(encoder->protected_->do_exhaustive_model_search) {
3406 min_fixed_order = 0;
3407 max_fixed_order = FLAC__MAX_FIXED_ORDER;
3409 else {
3410 min_fixed_order = max_fixed_order = guess_fixed_order;
3412 if(max_fixed_order >= frame_header->blocksize)
3413 max_fixed_order = frame_header->blocksize - 1;
3414 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3415 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3416 if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3417 continue; /* don't even try */
3418 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 */
3419 #else
3420 if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3421 continue; /* don't even try */
3422 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 */
3423 #endif
3424 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3425 if(rice_parameter >= rice_parameter_limit) {
3426 #ifdef DEBUG_VERBOSE
3427 fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
3428 #endif
3429 rice_parameter = rice_parameter_limit - 1;
3431 _candidate_bits =
3432 evaluate_fixed_subframe_(
3433 encoder,
3434 integer_signal,
3435 residual[!_best_subframe],
3436 encoder->private_->abs_residual_partition_sums,
3437 encoder->private_->raw_bits_per_partition,
3438 frame_header->blocksize,
3439 subframe_bps,
3440 fixed_order,
3441 rice_parameter,
3442 rice_parameter_limit,
3443 min_partition_order,
3444 max_partition_order,
3445 encoder->protected_->do_escape_coding,
3446 encoder->protected_->rice_parameter_search_dist,
3447 subframe[!_best_subframe],
3448 partitioned_rice_contents[!_best_subframe]
3450 if(_candidate_bits < _best_bits) {
3451 _best_subframe = !_best_subframe;
3452 _best_bits = _candidate_bits;
3457 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3458 /* encode lpc */
3459 if(encoder->protected_->max_lpc_order > 0) {
3460 if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3461 max_lpc_order = frame_header->blocksize-1;
3462 else
3463 max_lpc_order = encoder->protected_->max_lpc_order;
3464 if(max_lpc_order > 0) {
3465 unsigned a;
3466 for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3467 FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3468 encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3469 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3470 if(autoc[0] != 0.0) {
3471 FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3472 if(encoder->protected_->do_exhaustive_model_search) {
3473 min_lpc_order = 1;
3475 else {
3476 const unsigned guess_lpc_order =
3477 FLAC__lpc_compute_best_order(
3478 lpc_error,
3479 max_lpc_order,
3480 frame_header->blocksize,
3481 subframe_bps + (
3482 encoder->protected_->do_qlp_coeff_prec_search?
3483 FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
3484 encoder->protected_->qlp_coeff_precision
3487 min_lpc_order = max_lpc_order = guess_lpc_order;
3489 if(max_lpc_order >= frame_header->blocksize)
3490 max_lpc_order = frame_header->blocksize - 1;
3491 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
3492 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
3493 if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
3494 continue; /* don't even try */
3495 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
3496 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3497 if(rice_parameter >= rice_parameter_limit) {
3498 #ifdef DEBUG_VERBOSE
3499 fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
3500 #endif
3501 rice_parameter = rice_parameter_limit - 1;
3503 if(encoder->protected_->do_qlp_coeff_prec_search) {
3504 min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
3505 /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3506 if(subframe_bps <= 16) {
3507 max_qlp_coeff_precision = flac_min(32 - subframe_bps - FLAC__bitmath_ilog2(lpc_order), FLAC__MAX_QLP_COEFF_PRECISION);
3508 max_qlp_coeff_precision = flac_max(max_qlp_coeff_precision, min_qlp_coeff_precision);
3510 else
3511 max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
3513 else {
3514 min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
3516 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
3517 _candidate_bits =
3518 evaluate_lpc_subframe_(
3519 encoder,
3520 integer_signal,
3521 residual[!_best_subframe],
3522 encoder->private_->abs_residual_partition_sums,
3523 encoder->private_->raw_bits_per_partition,
3524 encoder->private_->lp_coeff[lpc_order-1],
3525 frame_header->blocksize,
3526 subframe_bps,
3527 lpc_order,
3528 qlp_coeff_precision,
3529 rice_parameter,
3530 rice_parameter_limit,
3531 min_partition_order,
3532 max_partition_order,
3533 encoder->protected_->do_escape_coding,
3534 encoder->protected_->rice_parameter_search_dist,
3535 subframe[!_best_subframe],
3536 partitioned_rice_contents[!_best_subframe]
3538 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
3539 if(_candidate_bits < _best_bits) {
3540 _best_subframe = !_best_subframe;
3541 _best_bits = _candidate_bits;
3550 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3554 /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3555 if(_best_bits == UINT_MAX) {
3556 FLAC__ASSERT(_best_subframe == 0);
3557 _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3560 *best_subframe = _best_subframe;
3561 *best_bits = _best_bits;
3563 return true;
3566 FLAC__bool add_subframe_(
3567 FLAC__StreamEncoder *encoder,
3568 unsigned blocksize,
3569 unsigned subframe_bps,
3570 const FLAC__Subframe *subframe,
3571 FLAC__BitWriter *frame
3574 switch(subframe->type) {
3575 case FLAC__SUBFRAME_TYPE_CONSTANT:
3576 if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3577 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3578 return false;
3580 break;
3581 case FLAC__SUBFRAME_TYPE_FIXED:
3582 if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3583 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3584 return false;
3586 break;
3587 case FLAC__SUBFRAME_TYPE_LPC:
3588 if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3589 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3590 return false;
3592 break;
3593 case FLAC__SUBFRAME_TYPE_VERBATIM:
3594 if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3595 encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3596 return false;
3598 break;
3599 default:
3600 FLAC__ASSERT(0);
3603 return true;
3606 #define SPOTCHECK_ESTIMATE 0
3607 #if SPOTCHECK_ESTIMATE
3608 static void spotcheck_subframe_estimate_(
3609 FLAC__StreamEncoder *encoder,
3610 unsigned blocksize,
3611 unsigned subframe_bps,
3612 const FLAC__Subframe *subframe,
3613 unsigned estimate
3616 FLAC__bool ret;
3617 FLAC__BitWriter *frame = FLAC__bitwriter_new();
3618 if(frame == 0) {
3619 fprintf(stderr, "EST: can't allocate frame\n");
3620 return;
3622 if(!FLAC__bitwriter_init(frame)) {
3623 fprintf(stderr, "EST: can't init frame\n");
3624 return;
3626 ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
3627 FLAC__ASSERT(ret);
3629 const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
3630 if(estimate != actual)
3631 fprintf(stderr, "EST: bad, frame#%u sub#%%d type=%8s est=%u, actual=%u, delta=%d\n", encoder->private_->current_frame_number, FLAC__SubframeTypeString[subframe->type], estimate, actual, (int)actual-(int)estimate);
3633 FLAC__bitwriter_delete(frame);
3635 #endif
3637 unsigned evaluate_constant_subframe_(
3638 FLAC__StreamEncoder *encoder,
3639 const FLAC__int32 signal,
3640 unsigned blocksize,
3641 unsigned subframe_bps,
3642 FLAC__Subframe *subframe
3645 unsigned estimate;
3646 subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3647 subframe->data.constant.value = signal;
3649 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
3651 #if SPOTCHECK_ESTIMATE
3652 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3653 #else
3654 (void)encoder, (void)blocksize;
3655 #endif
3657 return estimate;
3660 unsigned evaluate_fixed_subframe_(
3661 FLAC__StreamEncoder *encoder,
3662 const FLAC__int32 signal[],
3663 FLAC__int32 residual[],
3664 FLAC__uint64 abs_residual_partition_sums[],
3665 unsigned raw_bits_per_partition[],
3666 unsigned blocksize,
3667 unsigned subframe_bps,
3668 unsigned order,
3669 unsigned rice_parameter,
3670 unsigned rice_parameter_limit,
3671 unsigned min_partition_order,
3672 unsigned max_partition_order,
3673 FLAC__bool do_escape_coding,
3674 unsigned rice_parameter_search_dist,
3675 FLAC__Subframe *subframe,
3676 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3679 unsigned i, residual_bits, estimate;
3680 const unsigned residual_samples = blocksize - order;
3682 FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3684 subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3686 subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3687 subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3688 subframe->data.fixed.residual = residual;
3690 residual_bits =
3691 find_best_partition_order_(
3692 encoder->private_,
3693 residual,
3694 abs_residual_partition_sums,
3695 raw_bits_per_partition,
3696 residual_samples,
3697 order,
3698 rice_parameter,
3699 rice_parameter_limit,
3700 min_partition_order,
3701 max_partition_order,
3702 subframe_bps,
3703 do_escape_coding,
3704 rice_parameter_search_dist,
3705 &subframe->data.fixed.entropy_coding_method
3708 subframe->data.fixed.order = order;
3709 for(i = 0; i < order; i++)
3710 subframe->data.fixed.warmup[i] = signal[i];
3712 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
3714 #if SPOTCHECK_ESTIMATE
3715 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3716 #endif
3718 return estimate;
3721 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3722 unsigned evaluate_lpc_subframe_(
3723 FLAC__StreamEncoder *encoder,
3724 const FLAC__int32 signal[],
3725 FLAC__int32 residual[],
3726 FLAC__uint64 abs_residual_partition_sums[],
3727 unsigned raw_bits_per_partition[],
3728 const FLAC__real lp_coeff[],
3729 unsigned blocksize,
3730 unsigned subframe_bps,
3731 unsigned order,
3732 unsigned qlp_coeff_precision,
3733 unsigned rice_parameter,
3734 unsigned rice_parameter_limit,
3735 unsigned min_partition_order,
3736 unsigned max_partition_order,
3737 FLAC__bool do_escape_coding,
3738 unsigned rice_parameter_search_dist,
3739 FLAC__Subframe *subframe,
3740 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3743 FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER]; /* WATCHOUT: the size is important; some x86 intrinsic routines need more than lpc order elements */
3744 unsigned i, residual_bits, estimate;
3745 int quantization, ret;
3746 const unsigned residual_samples = blocksize - order;
3748 /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3749 if(subframe_bps <= 16) {
3750 FLAC__ASSERT(order > 0);
3751 FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3752 qlp_coeff_precision = flac_min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3755 ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3756 if(ret != 0)
3757 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3759 if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3760 if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3761 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3762 else
3763 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3764 else
3765 encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3767 subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3769 subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3770 subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3771 subframe->data.lpc.residual = residual;
3773 residual_bits =
3774 find_best_partition_order_(
3775 encoder->private_,
3776 residual,
3777 abs_residual_partition_sums,
3778 raw_bits_per_partition,
3779 residual_samples,
3780 order,
3781 rice_parameter,
3782 rice_parameter_limit,
3783 min_partition_order,
3784 max_partition_order,
3785 subframe_bps,
3786 do_escape_coding,
3787 rice_parameter_search_dist,
3788 &subframe->data.lpc.entropy_coding_method
3791 subframe->data.lpc.order = order;
3792 subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3793 subframe->data.lpc.quantization_level = quantization;
3794 memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3795 for(i = 0; i < order; i++)
3796 subframe->data.lpc.warmup[i] = signal[i];
3798 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits;
3800 #if SPOTCHECK_ESTIMATE
3801 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3802 #endif
3804 return estimate;
3806 #endif
3808 unsigned evaluate_verbatim_subframe_(
3809 FLAC__StreamEncoder *encoder,
3810 const FLAC__int32 signal[],
3811 unsigned blocksize,
3812 unsigned subframe_bps,
3813 FLAC__Subframe *subframe
3816 unsigned estimate;
3818 subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3820 subframe->data.verbatim.data = signal;
3822 estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
3824 #if SPOTCHECK_ESTIMATE
3825 spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3826 #else
3827 (void)encoder;
3828 #endif
3830 return estimate;
3833 unsigned find_best_partition_order_(
3834 FLAC__StreamEncoderPrivate *private_,
3835 const FLAC__int32 residual[],
3836 FLAC__uint64 abs_residual_partition_sums[],
3837 unsigned raw_bits_per_partition[],
3838 unsigned residual_samples,
3839 unsigned predictor_order,
3840 unsigned rice_parameter,
3841 unsigned rice_parameter_limit,
3842 unsigned min_partition_order,
3843 unsigned max_partition_order,
3844 unsigned bps,
3845 FLAC__bool do_escape_coding,
3846 unsigned rice_parameter_search_dist,
3847 FLAC__EntropyCodingMethod *best_ecm
3850 unsigned residual_bits, best_residual_bits = 0;
3851 unsigned best_parameters_index = 0;
3852 unsigned best_partition_order = 0;
3853 const unsigned blocksize = residual_samples + predictor_order;
3855 max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3856 min_partition_order = flac_min(min_partition_order, max_partition_order);
3858 private_->local_precompute_partition_info_sums(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
3860 if(do_escape_coding)
3861 precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3864 int partition_order;
3865 unsigned sum;
3867 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3868 if(!
3869 set_partitioned_rice_(
3870 #ifdef EXACT_RICE_BITS_CALCULATION
3871 residual,
3872 #endif
3873 abs_residual_partition_sums+sum,
3874 raw_bits_per_partition+sum,
3875 residual_samples,
3876 predictor_order,
3877 rice_parameter,
3878 rice_parameter_limit,
3879 rice_parameter_search_dist,
3880 (unsigned)partition_order,
3881 do_escape_coding,
3882 &private_->partitioned_rice_contents_extra[!best_parameters_index],
3883 &residual_bits
3887 FLAC__ASSERT(best_residual_bits != 0);
3888 break;
3890 sum += 1u << partition_order;
3891 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3892 best_residual_bits = residual_bits;
3893 best_parameters_index = !best_parameters_index;
3894 best_partition_order = partition_order;
3899 best_ecm->data.partitioned_rice.order = best_partition_order;
3903 * We are allowed to de-const the pointer based on our special
3904 * knowledge; it is const to the outside world.
3906 FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
3907 unsigned partition;
3909 /* save best parameters and raw_bits */
3910 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, flac_max(6u, best_partition_order));
3911 memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
3912 if(do_escape_coding)
3913 memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
3915 * Now need to check if the type should be changed to
3916 * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
3917 * size of the rice parameters.
3919 for(partition = 0; partition < (1u<<best_partition_order); partition++) {
3920 if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3921 best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
3922 break;
3927 return best_residual_bits;
3930 void precompute_partition_info_sums_(
3931 const FLAC__int32 residual[],
3932 FLAC__uint64 abs_residual_partition_sums[],
3933 unsigned residual_samples,
3934 unsigned predictor_order,
3935 unsigned min_partition_order,
3936 unsigned max_partition_order,
3937 unsigned bps
3940 const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
3941 unsigned partitions = 1u << max_partition_order;
3943 FLAC__ASSERT(default_partition_samples > predictor_order);
3945 /* first do max_partition_order */
3947 unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
3948 /* WATCHOUT: "+ bps + FLAC__MAX_EXTRA_RESIDUAL_BPS" is the maximum
3949 * assumed size of the average residual magnitude */
3950 if(FLAC__bitmath_ilog2(default_partition_samples) + bps + FLAC__MAX_EXTRA_RESIDUAL_BPS < 32) {
3951 FLAC__uint32 abs_residual_partition_sum;
3953 for(partition = residual_sample = 0; partition < partitions; partition++) {
3954 end += default_partition_samples;
3955 abs_residual_partition_sum = 0;
3956 for( ; residual_sample < end; residual_sample++)
3957 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3958 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3961 else { /* have to pessimistically use 64 bits for accumulator */
3962 FLAC__uint64 abs_residual_partition_sum;
3964 for(partition = residual_sample = 0; partition < partitions; partition++) {
3965 end += default_partition_samples;
3966 abs_residual_partition_sum = 0;
3967 for( ; residual_sample < end; residual_sample++)
3968 abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3969 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3974 /* now merge partitions for lower orders */
3976 unsigned from_partition = 0, to_partition = partitions;
3977 int partition_order;
3978 for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
3979 unsigned i;
3980 partitions >>= 1;
3981 for(i = 0; i < partitions; i++) {
3982 abs_residual_partition_sums[to_partition++] =
3983 abs_residual_partition_sums[from_partition ] +
3984 abs_residual_partition_sums[from_partition+1];
3985 from_partition += 2;
3991 void precompute_partition_info_escapes_(
3992 const FLAC__int32 residual[],
3993 unsigned raw_bits_per_partition[],
3994 unsigned residual_samples,
3995 unsigned predictor_order,
3996 unsigned min_partition_order,
3997 unsigned max_partition_order
4000 int partition_order;
4001 unsigned from_partition, to_partition = 0;
4002 const unsigned blocksize = residual_samples + predictor_order;
4004 /* first do max_partition_order */
4005 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
4006 FLAC__int32 r;
4007 FLAC__uint32 rmax;
4008 unsigned partition, partition_sample, partition_samples, residual_sample;
4009 const unsigned partitions = 1u << partition_order;
4010 const unsigned default_partition_samples = blocksize >> partition_order;
4012 FLAC__ASSERT(default_partition_samples > predictor_order);
4014 for(partition = residual_sample = 0; partition < partitions; partition++) {
4015 partition_samples = default_partition_samples;
4016 if(partition == 0)
4017 partition_samples -= predictor_order;
4018 rmax = 0;
4019 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
4020 r = residual[residual_sample++];
4021 /* OPT: maybe faster: rmax |= r ^ (r>>31) */
4022 if(r < 0)
4023 rmax |= ~r;
4024 else
4025 rmax |= r;
4027 /* now we know all residual values are in the range [-rmax-1,rmax] */
4028 raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
4030 to_partition = partitions;
4031 break; /*@@@ yuck, should remove the 'for' loop instead */
4034 /* now merge partitions for lower orders */
4035 for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
4036 unsigned m;
4037 unsigned i;
4038 const unsigned partitions = 1u << partition_order;
4039 for(i = 0; i < partitions; i++) {
4040 m = raw_bits_per_partition[from_partition];
4041 from_partition++;
4042 raw_bits_per_partition[to_partition] = flac_max(m, raw_bits_per_partition[from_partition]);
4043 from_partition++;
4044 to_partition++;
4049 #ifdef EXACT_RICE_BITS_CALCULATION
4050 static inline unsigned count_rice_bits_in_partition_(
4051 const unsigned rice_parameter,
4052 const unsigned partition_samples,
4053 const FLAC__int32 *residual
4056 unsigned i, partition_bits =
4057 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
4058 (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
4060 for(i = 0; i < partition_samples; i++)
4061 partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
4062 return partition_bits;
4064 #else
4065 static inline unsigned count_rice_bits_in_partition_(
4066 const unsigned rice_parameter,
4067 const unsigned partition_samples,
4068 const FLAC__uint64 abs_residual_partition_sum
4071 return
4072 FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
4073 (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
4075 rice_parameter?
4076 (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
4077 : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
4079 - (partition_samples >> 1)
4080 /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
4081 * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
4082 * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
4083 * So the subtraction term tries to guess how many extra bits were contributed.
4084 * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
4088 #endif
4090 FLAC__bool set_partitioned_rice_(
4091 #ifdef EXACT_RICE_BITS_CALCULATION
4092 const FLAC__int32 residual[],
4093 #endif
4094 const FLAC__uint64 abs_residual_partition_sums[],
4095 const unsigned raw_bits_per_partition[],
4096 const unsigned residual_samples,
4097 const unsigned predictor_order,
4098 const unsigned suggested_rice_parameter,
4099 const unsigned rice_parameter_limit,
4100 const unsigned rice_parameter_search_dist,
4101 const unsigned partition_order,
4102 const FLAC__bool search_for_escapes,
4103 FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
4104 unsigned *bits
4107 unsigned rice_parameter, partition_bits;
4108 unsigned best_partition_bits, best_rice_parameter = 0;
4109 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
4110 unsigned *parameters, *raw_bits;
4111 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4112 unsigned min_rice_parameter, max_rice_parameter;
4113 #else
4114 (void)rice_parameter_search_dist;
4115 #endif
4117 FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
4118 FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
4120 FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, flac_max(6u, partition_order));
4121 parameters = partitioned_rice_contents->parameters;
4122 raw_bits = partitioned_rice_contents->raw_bits;
4124 if(partition_order == 0) {
4125 best_partition_bits = (unsigned)(-1);
4126 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4127 if(rice_parameter_search_dist) {
4128 if(suggested_rice_parameter < rice_parameter_search_dist)
4129 min_rice_parameter = 0;
4130 else
4131 min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
4132 max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
4133 if(max_rice_parameter >= rice_parameter_limit) {
4134 #ifdef DEBUG_VERBOSE
4135 fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
4136 #endif
4137 max_rice_parameter = rice_parameter_limit - 1;
4140 else
4141 min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
4143 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4144 #else
4145 rice_parameter = suggested_rice_parameter;
4146 #endif
4147 #ifdef EXACT_RICE_BITS_CALCULATION
4148 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
4149 #else
4150 partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
4151 #endif
4152 if(partition_bits < best_partition_bits) {
4153 best_rice_parameter = rice_parameter;
4154 best_partition_bits = partition_bits;
4156 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4158 #endif
4159 if(search_for_escapes) {
4160 partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[0] * residual_samples;
4161 if(partition_bits <= best_partition_bits) {
4162 raw_bits[0] = raw_bits_per_partition[0];
4163 best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4164 best_partition_bits = partition_bits;
4166 else
4167 raw_bits[0] = 0;
4169 parameters[0] = best_rice_parameter;
4170 bits_ += best_partition_bits;
4172 else {
4173 unsigned partition, residual_sample;
4174 unsigned partition_samples;
4175 FLAC__uint64 mean, k;
4176 const unsigned partitions = 1u << partition_order;
4177 for(partition = residual_sample = 0; partition < partitions; partition++) {
4178 partition_samples = (residual_samples+predictor_order) >> partition_order;
4179 if(partition == 0) {
4180 if(partition_samples <= predictor_order)
4181 return false;
4182 else
4183 partition_samples -= predictor_order;
4185 mean = abs_residual_partition_sums[partition];
4186 /* we are basically calculating the size in bits of the
4187 * average residual magnitude in the partition:
4188 * rice_parameter = floor(log2(mean/partition_samples))
4189 * 'mean' is not a good name for the variable, it is
4190 * actually the sum of magnitudes of all residual values
4191 * in the partition, so the actual mean is
4192 * mean/partition_samples
4194 #if 0 /* old simple code */
4195 for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
4197 #else
4198 #if defined FLAC__CPU_X86_64 /* and other 64-bit arch, too */
4199 if(mean <= 0x80000000/512) { /* 512: more or less optimal for both 16- and 24-bit input */
4200 #else
4201 if(mean <= 0x80000000/8) { /* 32-bit arch: use 32-bit math if possible */
4202 #endif
4203 FLAC__uint32 k2, mean2 = (FLAC__uint32) mean;
4204 rice_parameter = 0; k2 = partition_samples;
4205 while(k2*8 < mean2) { /* requires: mean <= (2^31)/8 */
4206 rice_parameter += 4; k2 <<= 4; /* tuned for 16-bit input */
4208 while(k2 < mean2) { /* requires: mean <= 2^31 */
4209 rice_parameter++; k2 <<= 1;
4212 else {
4213 rice_parameter = 0; k = partition_samples;
4214 if(mean <= FLAC__U64L(0x8000000000000000)/128) /* usually mean is _much_ smaller than this value */
4215 while(k*128 < mean) { /* requires: mean <= (2^63)/128 */
4216 rice_parameter += 8; k <<= 8; /* tuned for 24-bit input */
4218 while(k < mean) { /* requires: mean <= 2^63 */
4219 rice_parameter++; k <<= 1;
4222 #endif
4223 if(rice_parameter >= rice_parameter_limit) {
4224 #ifdef DEBUG_VERBOSE
4225 fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
4226 #endif
4227 rice_parameter = rice_parameter_limit - 1;
4230 best_partition_bits = (unsigned)(-1);
4231 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4232 if(rice_parameter_search_dist) {
4233 if(rice_parameter < rice_parameter_search_dist)
4234 min_rice_parameter = 0;
4235 else
4236 min_rice_parameter = rice_parameter - rice_parameter_search_dist;
4237 max_rice_parameter = rice_parameter + rice_parameter_search_dist;
4238 if(max_rice_parameter >= rice_parameter_limit) {
4239 #ifdef DEBUG_VERBOSE
4240 fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
4241 #endif
4242 max_rice_parameter = rice_parameter_limit - 1;
4245 else
4246 min_rice_parameter = max_rice_parameter = rice_parameter;
4248 for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4249 #endif
4250 #ifdef EXACT_RICE_BITS_CALCULATION
4251 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
4252 #else
4253 partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
4254 #endif
4255 if(partition_bits < best_partition_bits) {
4256 best_rice_parameter = rice_parameter;
4257 best_partition_bits = partition_bits;
4259 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4261 #endif
4262 if(search_for_escapes) {
4263 partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[partition] * partition_samples;
4264 if(partition_bits <= best_partition_bits) {
4265 raw_bits[partition] = raw_bits_per_partition[partition];
4266 best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4267 best_partition_bits = partition_bits;
4269 else
4270 raw_bits[partition] = 0;
4272 parameters[partition] = best_rice_parameter;
4273 bits_ += best_partition_bits;
4274 residual_sample += partition_samples;
4278 *bits = bits_;
4279 return true;
4282 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
4284 unsigned i, shift;
4285 FLAC__int32 x = 0;
4287 for(i = 0; i < samples && !(x&1); i++)
4288 x |= signal[i];
4290 if(x == 0) {
4291 shift = 0;
4293 else {
4294 for(shift = 0; !(x&1); shift++)
4295 x >>= 1;
4298 if(shift > 0) {
4299 for(i = 0; i < samples; i++)
4300 signal[i] >>= shift;
4303 return shift;
4306 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4308 unsigned channel;
4310 for(channel = 0; channel < channels; channel++)
4311 memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
4313 fifo->tail += wide_samples;
4315 FLAC__ASSERT(fifo->tail <= fifo->size);
4318 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4320 unsigned channel;
4321 unsigned sample, wide_sample;
4322 unsigned tail = fifo->tail;
4324 sample = input_offset * channels;
4325 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
4326 for(channel = 0; channel < channels; channel++)
4327 fifo->data[channel][tail] = input[sample++];
4328 tail++;
4330 fifo->tail = tail;
4332 FLAC__ASSERT(fifo->tail <= fifo->size);
4335 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4337 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4338 const size_t encoded_bytes = encoder->private_->verify.output.bytes;
4339 (void)decoder;
4341 if(encoder->private_->verify.needs_magic_hack) {
4342 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
4343 *bytes = FLAC__STREAM_SYNC_LENGTH;
4344 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
4345 encoder->private_->verify.needs_magic_hack = false;
4347 else {
4348 if(encoded_bytes == 0) {
4350 * If we get here, a FIFO underflow has occurred,
4351 * which means there is a bug somewhere.
4353 FLAC__ASSERT(0);
4354 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
4356 else if(encoded_bytes < *bytes)
4357 *bytes = encoded_bytes;
4358 memcpy(buffer, encoder->private_->verify.output.data, *bytes);
4359 encoder->private_->verify.output.data += *bytes;
4360 encoder->private_->verify.output.bytes -= *bytes;
4363 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
4366 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
4368 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
4369 unsigned channel;
4370 const unsigned channels = frame->header.channels;
4371 const unsigned blocksize = frame->header.blocksize;
4372 const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
4374 (void)decoder;
4376 for(channel = 0; channel < channels; channel++) {
4377 if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
4378 unsigned i, sample = 0;
4379 FLAC__int32 expect = 0, got = 0;
4381 for(i = 0; i < blocksize; i++) {
4382 if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
4383 sample = i;
4384 expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
4385 got = (FLAC__int32)buffer[channel][i];
4386 break;
4389 FLAC__ASSERT(i < blocksize);
4390 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
4391 encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
4392 encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
4393 encoder->private_->verify.error_stats.channel = channel;
4394 encoder->private_->verify.error_stats.sample = sample;
4395 encoder->private_->verify.error_stats.expected = expect;
4396 encoder->private_->verify.error_stats.got = got;
4397 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
4398 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
4401 /* dequeue the frame from the fifo */
4402 encoder->private_->verify.input_fifo.tail -= blocksize;
4403 FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
4404 for(channel = 0; channel < channels; channel++)
4405 memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail * sizeof(encoder->private_->verify.input_fifo.data[0][0]));
4406 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4409 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4411 (void)decoder, (void)metadata, (void)client_data;
4414 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4416 FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4417 (void)decoder, (void)status;
4418 encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4421 #if 0
4422 FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4424 (void)client_data;
4426 *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
4427 if (*bytes == 0) {
4428 if (feof(encoder->private_->file))
4429 return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
4430 else if (ferror(encoder->private_->file))
4431 return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
4433 return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
4436 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4438 (void)client_data;
4440 if(fseeko(encoder->private_->file, (FLAC__off_t)absolute_byte_offset, SEEK_SET) < 0)
4441 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4442 else
4443 return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4446 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4448 FLAC__off_t offset;
4450 (void)client_data;
4452 offset = ftello(encoder->private_->file);
4454 if(offset < 0) {
4455 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4457 else {
4458 *absolute_byte_offset = (FLAC__uint64)offset;
4459 return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4463 #ifdef FLAC__VALGRIND_TESTING
4464 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4466 size_t ret = fwrite(ptr, size, nmemb, stream);
4467 if(!ferror(stream))
4468 fflush(stream);
4469 return ret;
4471 #else
4472 #define local__fwrite fwrite
4473 #endif
4475 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
4477 (void)client_data, (void)current_frame;
4479 if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4480 FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
4481 #if FLAC__HAS_OGG
4482 /* We would like to be able to use 'samples > 0' in the
4483 * clause here but currently because of the nature of our
4484 * Ogg writing implementation, 'samples' is always 0 (see
4485 * ogg_encoder_aspect.c). The downside is extra progress
4486 * callbacks.
4488 encoder->private_->is_ogg? true :
4489 #endif
4490 samples > 0
4492 if(call_it) {
4493 /* NOTE: We have to add +bytes, +samples, and +1 to the stats
4494 * because at this point in the callback chain, the stats
4495 * have not been updated. Only after we return and control
4496 * gets back to write_frame_() are the stats updated
4498 encoder->private_->progress_callback(encoder, encoder->private_->bytes_written+bytes, encoder->private_->samples_written+samples, encoder->private_->frames_written+(samples?1:0), encoder->private_->total_frames_estimate, encoder->private_->client_data);
4500 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4502 else
4503 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4507 * This will forcibly set stdout to binary mode (for OSes that require it)
4509 FILE *get_binary_stdout_(void)
4511 /* if something breaks here it is probably due to the presence or
4512 * absence of an underscore before the identifiers 'setmode',
4513 * 'fileno', and/or 'O_BINARY'; check your system header files.
4515 #if defined _MSC_VER || defined __MINGW32__
4516 _setmode(_fileno(stdout), _O_BINARY);
4517 #elif defined __CYGWIN__
4518 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4519 setmode(_fileno(stdout), _O_BINARY);
4520 #elif defined __EMX__
4521 setmode(fileno(stdout), O_BINARY);
4522 #endif
4524 return stdout;
4527 #endif