1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000-2009  Josh Coalson
3  * Copyright (C) 2011-2014  Xiph.Org Foundation
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * - Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *
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.
15  *
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.
19  *
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.
31  */
32 
33 #ifdef HAVE_CONFIG_H
34 #  include <config.h>
35 #endif
36 
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 "share/compat.h"
43 #include "FLAC/assert.h"
44 #include "FLAC/stream_decoder.h"
45 #include "protected/stream_encoder.h"
46 #include "private/bitwriter.h"
47 #include "private/bitmath.h"
48 #include "private/crc.h"
49 #include "private/cpu.h"
50 #include "private/fixed.h"
51 #include "private/format.h"
52 #include "private/lpc.h"
53 #include "private/md5.h"
54 #include "private/memory.h"
55 #include "private/macros.h"
56 #if FLAC__HAS_OGG
57 #include "private/ogg_helper.h"
58 #include "private/ogg_mapping.h"
59 #endif
60 #include "private/stream_encoder.h"
61 #include "private/stream_encoder_framing.h"
62 #include "private/window.h"
63 #include "share/alloc.h"
64 #include "share/private.h"
65 
66 
67 /* Exact Rice codeword length calculation is off by default.  The simple
68  * (and fast) estimation (of how many bits a residual value will be
69  * encoded with) in this encoder is very good, almost always yielding
70  * compression within 0.1% of exact calculation.
71  */
72 #undef EXACT_RICE_BITS_CALCULATION
73 /* Rice parameter searching is off by default.  The simple (and fast)
74  * parameter estimation in this encoder is very good, almost always
75  * yielding compression within 0.1% of the optimal parameters.
76  */
77 #undef ENABLE_RICE_PARAMETER_SEARCH
78 
79 
80 typedef struct {
81 	FLAC__int32 *data[FLAC__MAX_CHANNELS];
82 	unsigned size; /* of each data[] in samples */
83 	unsigned tail;
84 } verify_input_fifo;
85 
86 typedef struct {
87 	const FLAC__byte *data;
88 	unsigned capacity;
89 	unsigned bytes;
90 } verify_output;
91 
92 typedef enum {
93 	ENCODER_IN_MAGIC = 0,
94 	ENCODER_IN_METADATA = 1,
95 	ENCODER_IN_AUDIO = 2
96 } EncoderStateHint;
97 
98 static struct CompressionLevels {
99 	FLAC__bool do_mid_side_stereo;
100 	FLAC__bool loose_mid_side_stereo;
101 	unsigned max_lpc_order;
102 	unsigned qlp_coeff_precision;
103 	FLAC__bool do_qlp_coeff_prec_search;
104 	FLAC__bool do_escape_coding;
105 	FLAC__bool do_exhaustive_model_search;
106 	unsigned min_residual_partition_order;
107 	unsigned max_residual_partition_order;
108 	unsigned rice_parameter_search_dist;
109 	const char *apodization;
110 } compression_levels_[] = {
111 	{ false, false,  0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
112 	{ true , true ,  0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
113 	{ true , false,  0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
114 	{ false, false,  6, 0, false, false, false, 0, 4, 0, "tukey(5e-1)" },
115 	{ true , true ,  8, 0, false, false, false, 0, 4, 0, "tukey(5e-1)" },
116 	{ true , false,  8, 0, false, false, false, 0, 5, 0, "tukey(5e-1)" },
117 	{ true , false,  8, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2)" },
118 	{ true , false, 12, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2)" },
119 	{ true , false, 12, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2);punchout_tukey(3)" }
120 	/* here we use locale-independent 5e-1 instead of 0.5 or 0,5 */
121 };
122 
123 
124 /***********************************************************************
125  *
126  * Private class method prototypes
127  *
128  ***********************************************************************/
129 
130 static void set_defaults_(FLAC__StreamEncoder *encoder);
131 static void free_(FLAC__StreamEncoder *encoder);
132 static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
133 static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
134 static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
135 static void update_metadata_(const FLAC__StreamEncoder *encoder);
136 #if FLAC__HAS_OGG
137 static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
138 #endif
139 static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
140 static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
141 
142 static FLAC__bool process_subframe_(
143 	FLAC__StreamEncoder *encoder,
144 	unsigned min_partition_order,
145 	unsigned max_partition_order,
146 	const FLAC__FrameHeader *frame_header,
147 	unsigned subframe_bps,
148 	const FLAC__int32 integer_signal[],
149 	FLAC__Subframe *subframe[2],
150 	FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
151 	FLAC__int32 *residual[2],
152 	unsigned *best_subframe,
153 	unsigned *best_bits
154 );
155 
156 static FLAC__bool add_subframe_(
157 	FLAC__StreamEncoder *encoder,
158 	unsigned blocksize,
159 	unsigned subframe_bps,
160 	const FLAC__Subframe *subframe,
161 	FLAC__BitWriter *frame
162 );
163 
164 static unsigned evaluate_constant_subframe_(
165 	FLAC__StreamEncoder *encoder,
166 	const FLAC__int32 signal,
167 	unsigned blocksize,
168 	unsigned subframe_bps,
169 	FLAC__Subframe *subframe
170 );
171 
172 static unsigned evaluate_fixed_subframe_(
173 	FLAC__StreamEncoder *encoder,
174 	const FLAC__int32 signal[],
175 	FLAC__int32 residual[],
176 	FLAC__uint64 abs_residual_partition_sums[],
177 	unsigned raw_bits_per_partition[],
178 	unsigned blocksize,
179 	unsigned subframe_bps,
180 	unsigned order,
181 	unsigned rice_parameter,
182 	unsigned rice_parameter_limit,
183 	unsigned min_partition_order,
184 	unsigned max_partition_order,
185 	FLAC__bool do_escape_coding,
186 	unsigned rice_parameter_search_dist,
187 	FLAC__Subframe *subframe,
188 	FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
189 );
190 
191 #ifndef FLAC__INTEGER_ONLY_LIBRARY
192 static unsigned evaluate_lpc_subframe_(
193 	FLAC__StreamEncoder *encoder,
194 	const FLAC__int32 signal[],
195 	FLAC__int32 residual[],
196 	FLAC__uint64 abs_residual_partition_sums[],
197 	unsigned raw_bits_per_partition[],
198 	const FLAC__real lp_coeff[],
199 	unsigned blocksize,
200 	unsigned subframe_bps,
201 	unsigned order,
202 	unsigned qlp_coeff_precision,
203 	unsigned rice_parameter,
204 	unsigned rice_parameter_limit,
205 	unsigned min_partition_order,
206 	unsigned max_partition_order,
207 	FLAC__bool do_escape_coding,
208 	unsigned rice_parameter_search_dist,
209 	FLAC__Subframe *subframe,
210 	FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
211 );
212 #endif
213 
214 static unsigned evaluate_verbatim_subframe_(
215 	FLAC__StreamEncoder *encoder,
216 	const FLAC__int32 signal[],
217 	unsigned blocksize,
218 	unsigned subframe_bps,
219 	FLAC__Subframe *subframe
220 );
221 
222 static unsigned find_best_partition_order_(
223 	struct FLAC__StreamEncoderPrivate *private_,
224 	const FLAC__int32 residual[],
225 	FLAC__uint64 abs_residual_partition_sums[],
226 	unsigned raw_bits_per_partition[],
227 	unsigned residual_samples,
228 	unsigned predictor_order,
229 	unsigned rice_parameter,
230 	unsigned rice_parameter_limit,
231 	unsigned min_partition_order,
232 	unsigned max_partition_order,
233 	unsigned bps,
234 	FLAC__bool do_escape_coding,
235 	unsigned rice_parameter_search_dist,
236 	FLAC__EntropyCodingMethod *best_ecm
237 );
238 
239 static void precompute_partition_info_sums_(
240 	const FLAC__int32 residual[],
241 	FLAC__uint64 abs_residual_partition_sums[],
242 	unsigned residual_samples,
243 	unsigned predictor_order,
244 	unsigned min_partition_order,
245 	unsigned max_partition_order,
246 	unsigned bps
247 );
248 
249 static void precompute_partition_info_escapes_(
250 	const FLAC__int32 residual[],
251 	unsigned raw_bits_per_partition[],
252 	unsigned residual_samples,
253 	unsigned predictor_order,
254 	unsigned min_partition_order,
255 	unsigned max_partition_order
256 );
257 
258 static FLAC__bool set_partitioned_rice_(
259 #ifdef EXACT_RICE_BITS_CALCULATION
260 	const FLAC__int32 residual[],
261 #endif
262 	const FLAC__uint64 abs_residual_partition_sums[],
263 	const unsigned raw_bits_per_partition[],
264 	const unsigned residual_samples,
265 	const unsigned predictor_order,
266 	const unsigned suggested_rice_parameter,
267 	const unsigned rice_parameter_limit,
268 	const unsigned rice_parameter_search_dist,
269 	const unsigned partition_order,
270 	const FLAC__bool search_for_escapes,
271 	FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
272 	unsigned *bits
273 );
274 
275 static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
276 
277 /* verify-related routines: */
278 static void append_to_verify_fifo_(
279 	verify_input_fifo *fifo,
280 	const FLAC__int32 * const input[],
281 	unsigned input_offset,
282 	unsigned channels,
283 	unsigned wide_samples
284 );
285 
286 static void append_to_verify_fifo_interleaved_(
287 	verify_input_fifo *fifo,
288 	const FLAC__int32 input[],
289 	unsigned input_offset,
290 	unsigned channels,
291 	unsigned wide_samples
292 );
293 
294 static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
295 static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
296 static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
297 static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
298 
299 static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
300 static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
301 static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
302 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);
303 static FILE *get_binary_stdout_(void);
304 
305 
306 /***********************************************************************
307  *
308  * Private class data
309  *
310  ***********************************************************************/
311 
312 typedef struct FLAC__StreamEncoderPrivate {
313 	unsigned input_capacity;                          /* current size (in samples) of the signal and residual buffers */
314 	FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS];  /* the integer version of the input signal */
315 	FLAC__int32 *integer_signal_mid_side[2];          /* the integer version of the mid-side input signal (stereo only) */
316 #ifndef FLAC__INTEGER_ONLY_LIBRARY
317 	FLAC__real *real_signal[FLAC__MAX_CHANNELS];      /* (@@@ currently unused) the floating-point version of the input signal */
318 	FLAC__real *real_signal_mid_side[2];              /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
319 	FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
320 	FLAC__real *windowed_signal;                      /* the integer_signal[] * current window[] */
321 #endif
322 	unsigned subframe_bps[FLAC__MAX_CHANNELS];        /* the effective bits per sample of the input signal (stream bps - wasted bits) */
323 	unsigned subframe_bps_mid_side[2];                /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
324 	FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
325 	FLAC__int32 *residual_workspace_mid_side[2][2];
326 	FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
327 	FLAC__Subframe subframe_workspace_mid_side[2][2];
328 	FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
329 	FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
330 	FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
331 	FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
332 	FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
333 	FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
334 	unsigned best_subframe[FLAC__MAX_CHANNELS];       /* index (0 or 1) into 2nd dimension of the above workspaces */
335 	unsigned best_subframe_mid_side[2];
336 	unsigned best_subframe_bits[FLAC__MAX_CHANNELS];  /* size in bits of the best subframe for each channel */
337 	unsigned best_subframe_bits_mid_side[2];
338 	FLAC__uint64 *abs_residual_partition_sums;        /* workspace where the sum of abs(candidate residual) for each partition is stored */
339 	unsigned *raw_bits_per_partition;                 /* workspace where the sum of silog2(candidate residual) for each partition is stored */
340 	FLAC__BitWriter *frame;                           /* the current frame being worked on */
341 	unsigned loose_mid_side_stereo_frames;            /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
342 	unsigned loose_mid_side_stereo_frame_count;       /* number of frames using the current channel assignment */
343 	FLAC__ChannelAssignment last_channel_assignment;
344 	FLAC__StreamMetadata streaminfo;                  /* scratchpad for STREAMINFO as it is built */
345 	FLAC__StreamMetadata_SeekTable *seek_table;       /* pointer into encoder->protected_->metadata_ where the seek table is */
346 	unsigned current_sample_number;
347 	unsigned current_frame_number;
348 	FLAC__MD5Context md5context;
349 	FLAC__CPUInfo cpuinfo;
350 	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);
351 #ifndef FLAC__INTEGER_ONLY_LIBRARY
352 	unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float 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__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
354 #else
355 	unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
356 	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]);
357 #endif
358 #ifndef FLAC__INTEGER_ONLY_LIBRARY
359 	void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
360 	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[]);
361 	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[]);
362 	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[]);
363 #endif
364 	FLAC__bool use_wide_by_block;          /* use slow 64-bit versions of some functions because of the block size */
365 	FLAC__bool use_wide_by_partition;      /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
366 	FLAC__bool use_wide_by_order;          /* use slow 64-bit versions of some functions because of the lpc order */
367 	FLAC__bool disable_constant_subframes;
368 	FLAC__bool disable_fixed_subframes;
369 	FLAC__bool disable_verbatim_subframes;
370 #if FLAC__HAS_OGG
371 	FLAC__bool is_ogg;
372 #endif
373 	FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
374 	FLAC__StreamEncoderSeekCallback seek_callback;
375 	FLAC__StreamEncoderTellCallback tell_callback;
376 	FLAC__StreamEncoderWriteCallback write_callback;
377 	FLAC__StreamEncoderMetadataCallback metadata_callback;
378 	FLAC__StreamEncoderProgressCallback progress_callback;
379 	void *client_data;
380 	unsigned first_seekpoint_to_check;
381 	FILE *file;                            /* only used when encoding to a file */
382 	FLAC__uint64 bytes_written;
383 	FLAC__uint64 samples_written;
384 	unsigned frames_written;
385 	unsigned total_frames_estimate;
386 	/* unaligned (original) pointers to allocated data */
387 	FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
388 	FLAC__int32 *integer_signal_mid_side_unaligned[2];
389 #ifndef FLAC__INTEGER_ONLY_LIBRARY
390 	FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
391 	FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
392 	FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
393 	FLAC__real *windowed_signal_unaligned;
394 #endif
395 	FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
396 	FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
397 	FLAC__uint64 *abs_residual_partition_sums_unaligned;
398 	unsigned *raw_bits_per_partition_unaligned;
399 	/*
400 	 * These fields have been moved here from private function local
401 	 * declarations merely to save stack space during encoding.
402 	 */
403 #ifndef FLAC__INTEGER_ONLY_LIBRARY
404 	FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
405 #endif
406 	FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
407 	/*
408 	 * The data for the verify section
409 	 */
410 	struct {
411 		FLAC__StreamDecoder *decoder;
412 		EncoderStateHint state_hint;
413 		FLAC__bool needs_magic_hack;
414 		verify_input_fifo input_fifo;
415 		verify_output output;
416 		struct {
417 			FLAC__uint64 absolute_sample;
418 			unsigned frame_number;
419 			unsigned channel;
420 			unsigned sample;
421 			FLAC__int32 expected;
422 			FLAC__int32 got;
423 		} error_stats;
424 	} verify;
425 	FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
426 } FLAC__StreamEncoderPrivate;
427 
428 /***********************************************************************
429  *
430  * Public static class data
431  *
432  ***********************************************************************/
433 
434 FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
435 	"FLAC__STREAM_ENCODER_OK",
436 	"FLAC__STREAM_ENCODER_UNINITIALIZED",
437 	"FLAC__STREAM_ENCODER_OGG_ERROR",
438 	"FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
439 	"FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
440 	"FLAC__STREAM_ENCODER_CLIENT_ERROR",
441 	"FLAC__STREAM_ENCODER_IO_ERROR",
442 	"FLAC__STREAM_ENCODER_FRAMING_ERROR",
443 	"FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
444 };
445 
446 FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
447 	"FLAC__STREAM_ENCODER_INIT_STATUS_OK",
448 	"FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
449 	"FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
450 	"FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
451 	"FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
452 	"FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
453 	"FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
454 	"FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
455 	"FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
456 	"FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
457 	"FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
458 	"FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
459 	"FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
460 	"FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
461 };
462 
463 FLAC_API const char * const FLAC__StreamEncoderReadStatusString[] = {
464 	"FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
465 	"FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
466 	"FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
467 	"FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
468 };
469 
470 FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
471 	"FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
472 	"FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
473 };
474 
475 FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
476 	"FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
477 	"FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
478 	"FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
479 };
480 
481 FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
482 	"FLAC__STREAM_ENCODER_TELL_STATUS_OK",
483 	"FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
484 	"FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
485 };
486 
487 /* Number of samples that will be overread to watch for end of stream.  By
488  * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
489  * always try to read blocksize+1 samples before encoding a block, so that
490  * even if the stream has a total sample count that is an integral multiple
491  * of the blocksize, we will still notice when we are encoding the last
492  * block.  This is needed, for example, to correctly set the end-of-stream
493  * marker in Ogg FLAC.
494  *
495  * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
496  * not really any reason to change it.
497  */
498 static const unsigned OVERREAD_ = 1;
499 
500 /***********************************************************************
501  *
502  * Class constructor/destructor
503  *
504  */
FLAC__stream_encoder_new(void)505 FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
506 {
507 	FLAC__StreamEncoder *encoder;
508 	unsigned i;
509 
510 	FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
511 
512 	encoder = calloc(1, sizeof(FLAC__StreamEncoder));
513 	if(encoder == 0) {
514 		return 0;
515 	}
516 
517 	encoder->protected_ = calloc(1, sizeof(FLAC__StreamEncoderProtected));
518 	if(encoder->protected_ == 0) {
519 		free(encoder);
520 		return 0;
521 	}
522 
523 	encoder->private_ = calloc(1, sizeof(FLAC__StreamEncoderPrivate));
524 	if(encoder->private_ == 0) {
525 		free(encoder->protected_);
526 		free(encoder);
527 		return 0;
528 	}
529 
530 	encoder->private_->frame = FLAC__bitwriter_new();
531 	if(encoder->private_->frame == 0) {
532 		free(encoder->private_);
533 		free(encoder->protected_);
534 		free(encoder);
535 		return 0;
536 	}
537 
538 	encoder->private_->file = 0;
539 
540 	set_defaults_(encoder);
541 
542 	encoder->private_->is_being_deleted = false;
543 
544 	for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
545 		encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
546 		encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
547 	}
548 	for(i = 0; i < 2; i++) {
549 		encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
550 		encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
551 	}
552 	for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
553 		encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
554 		encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
555 	}
556 	for(i = 0; i < 2; i++) {
557 		encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
558 		encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
559 	}
560 
561 	for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
562 		FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
563 		FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
564 	}
565 	for(i = 0; i < 2; i++) {
566 		FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
567 		FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
568 	}
569 	for(i = 0; i < 2; i++)
570 		FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
571 
572 	encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
573 
574 	return encoder;
575 }
576 
FLAC__stream_encoder_delete(FLAC__StreamEncoder * encoder)577 FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
578 {
579 	unsigned i;
580 
581 	if (encoder == NULL)
582 		return ;
583 
584 	FLAC__ASSERT(0 != encoder->protected_);
585 	FLAC__ASSERT(0 != encoder->private_);
586 	FLAC__ASSERT(0 != encoder->private_->frame);
587 
588 	encoder->private_->is_being_deleted = true;
589 
590 	(void)FLAC__stream_encoder_finish(encoder);
591 
592 	if(0 != encoder->private_->verify.decoder)
593 		FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
594 
595 	for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
596 		FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
597 		FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
598 	}
599 	for(i = 0; i < 2; i++) {
600 		FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
601 		FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
602 	}
603 	for(i = 0; i < 2; i++)
604 		FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
605 
606 	FLAC__bitwriter_delete(encoder->private_->frame);
607 	free(encoder->private_);
608 	free(encoder->protected_);
609 	free(encoder);
610 }
611 
612 /***********************************************************************
613  *
614  * Public class methods
615  *
616  ***********************************************************************/
617 
init_stream_internal_(FLAC__StreamEncoder * encoder,FLAC__StreamEncoderReadCallback read_callback,FLAC__StreamEncoderWriteCallback write_callback,FLAC__StreamEncoderSeekCallback seek_callback,FLAC__StreamEncoderTellCallback tell_callback,FLAC__StreamEncoderMetadataCallback metadata_callback,void * client_data,FLAC__bool is_ogg)618 static FLAC__StreamEncoderInitStatus init_stream_internal_(
619 	FLAC__StreamEncoder *encoder,
620 	FLAC__StreamEncoderReadCallback read_callback,
621 	FLAC__StreamEncoderWriteCallback write_callback,
622 	FLAC__StreamEncoderSeekCallback seek_callback,
623 	FLAC__StreamEncoderTellCallback tell_callback,
624 	FLAC__StreamEncoderMetadataCallback metadata_callback,
625 	void *client_data,
626 	FLAC__bool is_ogg
627 )
628 {
629 	unsigned i;
630 	FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
631 
632 	FLAC__ASSERT(0 != encoder);
633 
634 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
635 		return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
636 
637 #if !FLAC__HAS_OGG
638 	if(is_ogg)
639 		return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
640 #endif
641 
642 	if(0 == write_callback || (seek_callback && 0 == tell_callback))
643 		return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
644 
645 	if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
646 		return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
647 
648 	if(encoder->protected_->channels != 2) {
649 		encoder->protected_->do_mid_side_stereo = false;
650 		encoder->protected_->loose_mid_side_stereo = false;
651 	}
652 	else if(!encoder->protected_->do_mid_side_stereo)
653 		encoder->protected_->loose_mid_side_stereo = false;
654 
655 	if(encoder->protected_->bits_per_sample >= 32)
656 		encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
657 
658 	if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
659 		return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
660 
661 	if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
662 		return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
663 
664 	if(encoder->protected_->blocksize == 0) {
665 		if(encoder->protected_->max_lpc_order == 0)
666 			encoder->protected_->blocksize = 1152;
667 		else
668 			encoder->protected_->blocksize = 4096;
669 	}
670 
671 	if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
672 		return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
673 
674 	if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
675 		return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
676 
677 	if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
678 		return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
679 
680 	if(encoder->protected_->qlp_coeff_precision == 0) {
681 		if(encoder->protected_->bits_per_sample < 16) {
682 			/* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
683 			/* @@@ until then we'll make a guess */
684 			encoder->protected_->qlp_coeff_precision = flac_max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
685 		}
686 		else if(encoder->protected_->bits_per_sample == 16) {
687 			if(encoder->protected_->blocksize <= 192)
688 				encoder->protected_->qlp_coeff_precision = 7;
689 			else if(encoder->protected_->blocksize <= 384)
690 				encoder->protected_->qlp_coeff_precision = 8;
691 			else if(encoder->protected_->blocksize <= 576)
692 				encoder->protected_->qlp_coeff_precision = 9;
693 			else if(encoder->protected_->blocksize <= 1152)
694 				encoder->protected_->qlp_coeff_precision = 10;
695 			else if(encoder->protected_->blocksize <= 2304)
696 				encoder->protected_->qlp_coeff_precision = 11;
697 			else if(encoder->protected_->blocksize <= 4608)
698 				encoder->protected_->qlp_coeff_precision = 12;
699 			else
700 				encoder->protected_->qlp_coeff_precision = 13;
701 		}
702 		else {
703 			if(encoder->protected_->blocksize <= 384)
704 				encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
705 			else if(encoder->protected_->blocksize <= 1152)
706 				encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
707 			else
708 				encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
709 		}
710 		FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
711 	}
712 	else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
713 		return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
714 
715 	if(encoder->protected_->streamable_subset) {
716 		if(!FLAC__format_blocksize_is_subset(encoder->protected_->blocksize, encoder->protected_->sample_rate))
717 			return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
718 		if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
719 			return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
720 		if(
721 			encoder->protected_->bits_per_sample != 8 &&
722 			encoder->protected_->bits_per_sample != 12 &&
723 			encoder->protected_->bits_per_sample != 16 &&
724 			encoder->protected_->bits_per_sample != 20 &&
725 			encoder->protected_->bits_per_sample != 24
726 		)
727 			return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
728 		if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
729 			return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
730 		if(
731 			encoder->protected_->sample_rate <= 48000 &&
732 			(
733 				encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
734 				encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
735 			)
736 		) {
737 			return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
738 		}
739 	}
740 
741 	if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
742 		encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
743 	if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
744 		encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
745 
746 #if FLAC__HAS_OGG
747 	/* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
748 	if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
749 		unsigned i1;
750 		for(i1 = 1; i1 < encoder->protected_->num_metadata_blocks; i1++) {
751 			if(0 != encoder->protected_->metadata[i1] && encoder->protected_->metadata[i1]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
752 				FLAC__StreamMetadata *vc = encoder->protected_->metadata[i1];
753 				for( ; i1 > 0; i1--)
754 					encoder->protected_->metadata[i1] = encoder->protected_->metadata[i1-1];
755 				encoder->protected_->metadata[0] = vc;
756 				break;
757 			}
758 		}
759 	}
760 #endif
761 	/* keep track of any SEEKTABLE block */
762 	if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
763 		unsigned i2;
764 		for(i2 = 0; i2 < encoder->protected_->num_metadata_blocks; i2++) {
765 			if(0 != encoder->protected_->metadata[i2] && encoder->protected_->metadata[i2]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
766 				encoder->private_->seek_table = &encoder->protected_->metadata[i2]->data.seek_table;
767 				break; /* take only the first one */
768 			}
769 		}
770 	}
771 
772 	/* validate metadata */
773 	if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
774 		return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
775 	metadata_has_seektable = false;
776 	metadata_has_vorbis_comment = false;
777 	metadata_picture_has_type1 = false;
778 	metadata_picture_has_type2 = false;
779 	for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
780 		const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
781 		if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
782 			return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
783 		else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
784 			if(metadata_has_seektable) /* only one is allowed */
785 				return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
786 			metadata_has_seektable = true;
787 			if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
788 				return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
789 		}
790 		else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
791 			if(metadata_has_vorbis_comment) /* only one is allowed */
792 				return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
793 			metadata_has_vorbis_comment = true;
794 		}
795 		else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
796 			if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
797 				return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
798 		}
799 		else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
800 			if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
801 				return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
802 			if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
803 				if(metadata_picture_has_type1) /* there should only be 1 per stream */
804 					return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
805 				metadata_picture_has_type1 = true;
806 				/* standard icon must be 32x32 pixel PNG */
807 				if(
808 					m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
809 					(
810 						(strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
811 						m->data.picture.width != 32 ||
812 						m->data.picture.height != 32
813 					)
814 				)
815 					return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
816 			}
817 			else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
818 				if(metadata_picture_has_type2) /* there should only be 1 per stream */
819 					return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
820 				metadata_picture_has_type2 = true;
821 			}
822 		}
823 	}
824 
825 	encoder->private_->input_capacity = 0;
826 	for(i = 0; i < encoder->protected_->channels; i++) {
827 		encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
828 #ifndef FLAC__INTEGER_ONLY_LIBRARY
829 		encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
830 #endif
831 	}
832 	for(i = 0; i < 2; i++) {
833 		encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
834 #ifndef FLAC__INTEGER_ONLY_LIBRARY
835 		encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
836 #endif
837 	}
838 #ifndef FLAC__INTEGER_ONLY_LIBRARY
839 	for(i = 0; i < encoder->protected_->num_apodizations; i++)
840 		encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
841 	encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
842 #endif
843 	for(i = 0; i < encoder->protected_->channels; i++) {
844 		encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
845 		encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
846 		encoder->private_->best_subframe[i] = 0;
847 	}
848 	for(i = 0; i < 2; i++) {
849 		encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
850 		encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
851 		encoder->private_->best_subframe_mid_side[i] = 0;
852 	}
853 	encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
854 	encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
855 #ifndef FLAC__INTEGER_ONLY_LIBRARY
856 	encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
857 #else
858 	/* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
859 	/* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
860 	FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
861 	FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
862 	FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
863 	FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
864 	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);
865 #endif
866 	if(encoder->private_->loose_mid_side_stereo_frames == 0)
867 		encoder->private_->loose_mid_side_stereo_frames = 1;
868 	encoder->private_->loose_mid_side_stereo_frame_count = 0;
869 	encoder->private_->current_sample_number = 0;
870 	encoder->private_->current_frame_number = 0;
871 
872 	encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
873 	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? */
874 	encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
875 
876 	/*
877 	 * get the CPU info and set the function pointers
878 	 */
879 	FLAC__cpu_info(&encoder->private_->cpuinfo);
880 	/* first default to the non-asm routines */
881 #ifndef FLAC__INTEGER_ONLY_LIBRARY
882 	encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
883 #endif
884 	encoder->private_->local_precompute_partition_info_sums = precompute_partition_info_sums_;
885 	encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
886 	encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide;
887 #ifndef FLAC__INTEGER_ONLY_LIBRARY
888 	encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
889 	encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
890 	encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
891 #endif
892 	/* now override with asm where appropriate */
893 #ifndef FLAC__INTEGER_ONLY_LIBRARY
894 # ifndef FLAC__NO_ASM
895 	if(encoder->private_->cpuinfo.use_asm) {
896 #  ifdef FLAC__CPU_IA32
897 		FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
898 #   ifdef FLAC__HAS_NASM
899 		if(encoder->private_->cpuinfo.ia32.sse) {
900 			if(encoder->protected_->max_lpc_order < 4)
901 				encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4_old;
902 			else if(encoder->protected_->max_lpc_order < 8)
903 				encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8_old;
904 			else if(encoder->protected_->max_lpc_order < 12)
905 				encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12_old;
906 			else if(encoder->protected_->max_lpc_order < 16)
907 				encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_16_old;
908 			else
909 				encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
910 		}
911 		else
912 			encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
913 
914 		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 */
915 		if(encoder->private_->cpuinfo.ia32.mmx) {
916 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
917 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
918 		}
919 		else {
920 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
921 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
922 		}
923 
924 		if(encoder->private_->cpuinfo.ia32.mmx && encoder->private_->cpuinfo.ia32.cmov)
925 			encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
926 #   endif /* FLAC__HAS_NASM */
927 #   ifdef FLAC__HAS_X86INTRIN
928 #    if defined FLAC__SSE_SUPPORTED
929 		if(encoder->private_->cpuinfo.ia32.sse) {
930 			if(encoder->private_->cpuinfo.ia32.sse42 || !encoder->private_->cpuinfo.ia32.intel) { /* use new autocorrelation functions */
931 				if(encoder->protected_->max_lpc_order < 4)
932 					encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_new;
933 				else if(encoder->protected_->max_lpc_order < 8)
934 					encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_new;
935 				else if(encoder->protected_->max_lpc_order < 12)
936 					encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_new;
937 				else if(encoder->protected_->max_lpc_order < 16)
938 					encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_new;
939 				else
940 					encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
941 			}
942 			else { /* use old autocorrelation functions */
943 				if(encoder->protected_->max_lpc_order < 4)
944 					encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_old;
945 				else if(encoder->protected_->max_lpc_order < 8)
946 					encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_old;
947 				else if(encoder->protected_->max_lpc_order < 12)
948 					encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_old;
949 				else if(encoder->protected_->max_lpc_order < 16)
950 					encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_old;
951 				else
952 					encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
953 			}
954 		}
955 #    endif
956 
957 #    ifdef FLAC__SSE2_SUPPORTED
958 		if(encoder->private_->cpuinfo.ia32.sse2) {
959 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients       = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse2;
960 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_sse2;
961 		}
962 #    endif
963 #    ifdef FLAC__SSE4_1_SUPPORTED
964 		if(encoder->private_->cpuinfo.ia32.sse41) {
965 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients       = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse41;
966 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_sse41;
967 		}
968 #    endif
969 #    ifdef FLAC__AVX2_SUPPORTED
970 		if(encoder->private_->cpuinfo.ia32.avx2) {
971 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_avx2;
972 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients       = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_avx2;
973 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_avx2;
974 		}
975 #    endif
976 
977 #    ifdef FLAC__SSE2_SUPPORTED
978 		if (encoder->private_->cpuinfo.ia32.sse2) {
979 			encoder->private_->local_fixed_compute_best_predictor      = FLAC__fixed_compute_best_predictor_intrin_sse2;
980 			encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_sse2;
981 		}
982 #    endif
983 #    ifdef FLAC__SSSE3_SUPPORTED
984 		if (encoder->private_->cpuinfo.ia32.ssse3) {
985 			encoder->private_->local_fixed_compute_best_predictor      = FLAC__fixed_compute_best_predictor_intrin_ssse3;
986 			encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_ssse3;
987 		}
988 #    endif
989 #   endif /* FLAC__HAS_X86INTRIN */
990 #  elif defined FLAC__CPU_X86_64
991 		FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_X86_64);
992 #   ifdef FLAC__HAS_X86INTRIN
993 #    ifdef FLAC__SSE_SUPPORTED
994 		if(encoder->private_->cpuinfo.x86.sse42 || !encoder->private_->cpuinfo.x86.intel) { /* use new autocorrelation functions */
995 			if(encoder->protected_->max_lpc_order < 4)
996 				encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_new;
997 			else if(encoder->protected_->max_lpc_order < 8)
998 				encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_new;
999 			else if(encoder->protected_->max_lpc_order < 12)
1000 				encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_new;
1001 			else if(encoder->protected_->max_lpc_order < 16)
1002 				encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_new;
1003 		}
1004 		else {
1005 			if(encoder->protected_->max_lpc_order < 4)
1006 				encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_old;
1007 			else if(encoder->protected_->max_lpc_order < 8)
1008 				encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_old;
1009 			else if(encoder->protected_->max_lpc_order < 12)
1010 				encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_old;
1011 			else if(encoder->protected_->max_lpc_order < 16)
1012 				encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_old;
1013 		}
1014 #    endif
1015 
1016 #    ifdef FLAC__SSE2_SUPPORTED
1017 		encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_sse2;
1018 #    endif
1019 #    ifdef FLAC__SSE4_1_SUPPORTED
1020 		if(encoder->private_->cpuinfo.x86.sse41) {
1021 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse41;
1022 		}
1023 #    endif
1024 #    ifdef FLAC__AVX2_SUPPORTED
1025 		if(encoder->private_->cpuinfo.x86.avx2) {
1026 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_avx2;
1027 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients       = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_avx2;
1028 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_avx2;
1029 		}
1030 #    endif
1031 
1032 #    ifdef FLAC__SSE2_SUPPORTED
1033 		encoder->private_->local_fixed_compute_best_predictor      = FLAC__fixed_compute_best_predictor_intrin_sse2;
1034 		encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_sse2;
1035 #    endif
1036 #    ifdef FLAC__SSSE3_SUPPORTED
1037 		if (encoder->private_->cpuinfo.x86.ssse3) {
1038 			encoder->private_->local_fixed_compute_best_predictor      = FLAC__fixed_compute_best_predictor_intrin_ssse3;
1039 			encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_ssse3;
1040 		}
1041 #    endif
1042 #   endif /* FLAC__HAS_X86INTRIN */
1043 #  endif /* FLAC__CPU_... */
1044 	}
1045 # endif /* !FLAC__NO_ASM */
1046 #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
1047 #if !defined FLAC__NO_ASM && defined FLAC__HAS_X86INTRIN
1048 	if(encoder->private_->cpuinfo.use_asm) {
1049 # if defined FLAC__CPU_IA32
1050 #  ifdef FLAC__SSE2_SUPPORTED
1051 		if(encoder->private_->cpuinfo.ia32.sse2)
1052 			encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_sse2;
1053 #  endif
1054 #  ifdef FLAC__SSSE3_SUPPORTED
1055 		if(encoder->private_->cpuinfo.ia32.ssse3)
1056 			encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_ssse3;
1057 #  endif
1058 #  ifdef FLAC__AVX2_SUPPORTED
1059 		if(encoder->private_->cpuinfo.ia32.avx2)
1060 			encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_avx2;
1061 #  endif
1062 # elif defined FLAC__CPU_X86_64
1063 #  ifdef FLAC__SSE2_SUPPORTED
1064 		encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_sse2;
1065 #  endif
1066 #  ifdef FLAC__SSSE3_SUPPORTED
1067 		if(encoder->private_->cpuinfo.x86.ssse3)
1068 			encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_ssse3;
1069 #  endif
1070 #  ifdef FLAC__AVX2_SUPPORTED
1071 		if(encoder->private_->cpuinfo.x86.avx2)
1072 			encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_avx2;
1073 #  endif
1074 # endif /* FLAC__CPU_... */
1075 	}
1076 #endif /* !FLAC__NO_ASM && FLAC__HAS_X86INTRIN */
1077 	/* finally override based on wide-ness if necessary */
1078 	if(encoder->private_->use_wide_by_block) {
1079 		encoder->private_->local_fixed_compute_best_predictor = encoder->private_->local_fixed_compute_best_predictor_wide;
1080 	}
1081 
1082 	/* set state to OK; from here on, errors are fatal and we'll override the state then */
1083 	encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
1084 
1085 #if FLAC__HAS_OGG
1086 	encoder->private_->is_ogg = is_ogg;
1087 	if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
1088 		encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
1089 		return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1090 	}
1091 #endif
1092 
1093 	encoder->private_->read_callback = read_callback;
1094 	encoder->private_->write_callback = write_callback;
1095 	encoder->private_->seek_callback = seek_callback;
1096 	encoder->private_->tell_callback = tell_callback;
1097 	encoder->private_->metadata_callback = metadata_callback;
1098 	encoder->private_->client_data = client_data;
1099 
1100 	if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
1101 		/* the above function sets the state for us in case of an error */
1102 		return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1103 	}
1104 
1105 	if(!FLAC__bitwriter_init(encoder->private_->frame)) {
1106 		encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1107 		return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1108 	}
1109 
1110 	/*
1111 	 * Set up the verify stuff if necessary
1112 	 */
1113 	if(encoder->protected_->verify) {
1114 		/*
1115 		 * First, set up the fifo which will hold the
1116 		 * original signal to compare against
1117 		 */
1118 		encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
1119 		for(i = 0; i < encoder->protected_->channels; i++) {
1120 			if(0 == (encoder->private_->verify.input_fifo.data[i] = safe_malloc_mul_2op_p(sizeof(FLAC__int32), /*times*/encoder->private_->verify.input_fifo.size))) {
1121 				encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1122 				return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1123 			}
1124 		}
1125 		encoder->private_->verify.input_fifo.tail = 0;
1126 
1127 		/*
1128 		 * Now set up a stream decoder for verification
1129 		 */
1130 		if(0 == encoder->private_->verify.decoder) {
1131 			encoder->private_->verify.decoder = FLAC__stream_decoder_new();
1132 			if(0 == encoder->private_->verify.decoder) {
1133 				encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1134 				return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1135 			}
1136 		}
1137 
1138 		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) {
1139 			encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1140 			return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1141 		}
1142 	}
1143 	encoder->private_->verify.error_stats.absolute_sample = 0;
1144 	encoder->private_->verify.error_stats.frame_number = 0;
1145 	encoder->private_->verify.error_stats.channel = 0;
1146 	encoder->private_->verify.error_stats.sample = 0;
1147 	encoder->private_->verify.error_stats.expected = 0;
1148 	encoder->private_->verify.error_stats.got = 0;
1149 
1150 	/*
1151 	 * These must be done before we write any metadata, because that
1152 	 * calls the write_callback, which uses these values.
1153 	 */
1154 	encoder->private_->first_seekpoint_to_check = 0;
1155 	encoder->private_->samples_written = 0;
1156 	encoder->protected_->streaminfo_offset = 0;
1157 	encoder->protected_->seektable_offset = 0;
1158 	encoder->protected_->audio_offset = 0;
1159 
1160 	/*
1161 	 * write the stream header
1162 	 */
1163 	if(encoder->protected_->verify)
1164 		encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1165 	if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1166 		encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1167 		return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1168 	}
1169 	if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1170 		/* the above function sets the state for us in case of an error */
1171 		return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1172 	}
1173 
1174 	/*
1175 	 * write the STREAMINFO metadata block
1176 	 */
1177 	if(encoder->protected_->verify)
1178 		encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1179 	encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1180 	encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1181 	encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1182 	encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1183 	encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1184 	encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1185 	encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1186 	encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1187 	encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1188 	encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1189 	encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1190 	memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1191 	if(encoder->protected_->do_md5)
1192 		FLAC__MD5Init(&encoder->private_->md5context);
1193 	if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1194 		encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1195 		return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1196 	}
1197 	if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1198 		/* the above function sets the state for us in case of an error */
1199 		return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1200 	}
1201 
1202 	/*
1203 	 * Now that the STREAMINFO block is written, we can init this to an
1204 	 * absurdly-high value...
1205 	 */
1206 	encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1207 	/* ... and clear this to 0 */
1208 	encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1209 
1210 	/*
1211 	 * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1212 	 * if not, we will write an empty one (FLAC__add_metadata_block()
1213 	 * automatically supplies the vendor string).
1214 	 *
1215 	 * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1216 	 * the STREAMINFO.  (In the case that metadata_has_vorbis_comment is
1217 	 * true it will have already insured that the metadata list is properly
1218 	 * ordered.)
1219 	 */
1220 	if(!metadata_has_vorbis_comment) {
1221 		FLAC__StreamMetadata vorbis_comment;
1222 		vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1223 		vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1224 		vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1225 		vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1226 		vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1227 		vorbis_comment.data.vorbis_comment.num_comments = 0;
1228 		vorbis_comment.data.vorbis_comment.comments = 0;
1229 		if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1230 			encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1231 			return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1232 		}
1233 		if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1234 			/* the above function sets the state for us in case of an error */
1235 			return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1236 		}
1237 	}
1238 
1239 	/*
1240 	 * write the user's metadata blocks
1241 	 */
1242 	for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1243 		encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1244 		if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1245 			encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1246 			return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1247 		}
1248 		if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1249 			/* the above function sets the state for us in case of an error */
1250 			return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1251 		}
1252 	}
1253 
1254 	/* now that all the metadata is written, we save the stream offset */
1255 	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 */
1256 		encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1257 		return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1258 	}
1259 
1260 	if(encoder->protected_->verify)
1261 		encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1262 
1263 	return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1264 }
1265 
FLAC__stream_encoder_init_stream(FLAC__StreamEncoder * encoder,FLAC__StreamEncoderWriteCallback write_callback,FLAC__StreamEncoderSeekCallback seek_callback,FLAC__StreamEncoderTellCallback tell_callback,FLAC__StreamEncoderMetadataCallback metadata_callback,void * client_data)1266 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1267 	FLAC__StreamEncoder *encoder,
1268 	FLAC__StreamEncoderWriteCallback write_callback,
1269 	FLAC__StreamEncoderSeekCallback seek_callback,
1270 	FLAC__StreamEncoderTellCallback tell_callback,
1271 	FLAC__StreamEncoderMetadataCallback metadata_callback,
1272 	void *client_data
1273 )
1274 {
1275 	return init_stream_internal_(
1276 		encoder,
1277 		/*read_callback=*/0,
1278 		write_callback,
1279 		seek_callback,
1280 		tell_callback,
1281 		metadata_callback,
1282 		client_data,
1283 		/*is_ogg=*/false
1284 	);
1285 }
1286 
FLAC__stream_encoder_init_ogg_stream(FLAC__StreamEncoder * encoder,FLAC__StreamEncoderReadCallback read_callback,FLAC__StreamEncoderWriteCallback write_callback,FLAC__StreamEncoderSeekCallback seek_callback,FLAC__StreamEncoderTellCallback tell_callback,FLAC__StreamEncoderMetadataCallback metadata_callback,void * client_data)1287 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1288 	FLAC__StreamEncoder *encoder,
1289 	FLAC__StreamEncoderReadCallback read_callback,
1290 	FLAC__StreamEncoderWriteCallback write_callback,
1291 	FLAC__StreamEncoderSeekCallback seek_callback,
1292 	FLAC__StreamEncoderTellCallback tell_callback,
1293 	FLAC__StreamEncoderMetadataCallback metadata_callback,
1294 	void *client_data
1295 )
1296 {
1297 	return init_stream_internal_(
1298 		encoder,
1299 		read_callback,
1300 		write_callback,
1301 		seek_callback,
1302 		tell_callback,
1303 		metadata_callback,
1304 		client_data,
1305 		/*is_ogg=*/true
1306 	);
1307 }
1308 
init_FILE_internal_(FLAC__StreamEncoder * encoder,FILE * file,FLAC__StreamEncoderProgressCallback progress_callback,void * client_data,FLAC__bool is_ogg)1309 static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1310 	FLAC__StreamEncoder *encoder,
1311 	FILE *file,
1312 	FLAC__StreamEncoderProgressCallback progress_callback,
1313 	void *client_data,
1314 	FLAC__bool is_ogg
1315 )
1316 {
1317 	FLAC__StreamEncoderInitStatus init_status;
1318 
1319 	FLAC__ASSERT(0 != encoder);
1320 	FLAC__ASSERT(0 != file);
1321 
1322 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1323 		return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1324 
1325 	/* double protection */
1326 	if(file == 0) {
1327 		encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1328 		return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1329 	}
1330 
1331 	/*
1332 	 * To make sure that our file does not go unclosed after an error, we
1333 	 * must assign the FILE pointer before any further error can occur in
1334 	 * this routine.
1335 	 */
1336 	if(file == stdout)
1337 		file = get_binary_stdout_(); /* just to be safe */
1338 
1339 #ifdef _WIN32
1340 	/*
1341 	 * Windows can suffer quite badly from disk fragmentation. This can be
1342 	 * reduced significantly by setting the output buffer size to be 10MB.
1343 	 */
1344 	setvbuf(file, NULL, _IOFBF, 10*1024*1024);
1345 #endif
1346 	encoder->private_->file = file;
1347 
1348 	encoder->private_->progress_callback = progress_callback;
1349 	encoder->private_->bytes_written = 0;
1350 	encoder->private_->samples_written = 0;
1351 	encoder->private_->frames_written = 0;
1352 
1353 	init_status = init_stream_internal_(
1354 		encoder,
1355 		encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1356 		file_write_callback_,
1357 		encoder->private_->file == stdout? 0 : file_seek_callback_,
1358 		encoder->private_->file == stdout? 0 : file_tell_callback_,
1359 		/*metadata_callback=*/0,
1360 		client_data,
1361 		is_ogg
1362 	);
1363 	if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1364 		/* the above function sets the state for us in case of an error */
1365 		return init_status;
1366 	}
1367 
1368 	{
1369 		unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1370 
1371 		FLAC__ASSERT(blocksize != 0);
1372 		encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1373 	}
1374 
1375 	return init_status;
1376 }
1377 
FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder * encoder,FILE * file,FLAC__StreamEncoderProgressCallback progress_callback,void * client_data)1378 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1379 	FLAC__StreamEncoder *encoder,
1380 	FILE *file,
1381 	FLAC__StreamEncoderProgressCallback progress_callback,
1382 	void *client_data
1383 )
1384 {
1385 	return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1386 }
1387 
FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder * encoder,FILE * file,FLAC__StreamEncoderProgressCallback progress_callback,void * client_data)1388 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1389 	FLAC__StreamEncoder *encoder,
1390 	FILE *file,
1391 	FLAC__StreamEncoderProgressCallback progress_callback,
1392 	void *client_data
1393 )
1394 {
1395 	return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1396 }
1397 
init_file_internal_(FLAC__StreamEncoder * encoder,const char * filename,FLAC__StreamEncoderProgressCallback progress_callback,void * client_data,FLAC__bool is_ogg)1398 static FLAC__StreamEncoderInitStatus init_file_internal_(
1399 	FLAC__StreamEncoder *encoder,
1400 	const char *filename,
1401 	FLAC__StreamEncoderProgressCallback progress_callback,
1402 	void *client_data,
1403 	FLAC__bool is_ogg
1404 )
1405 {
1406 	FILE *file;
1407 
1408 	FLAC__ASSERT(0 != encoder);
1409 
1410 	/*
1411 	 * To make sure that our file does not go unclosed after an error, we
1412 	 * have to do the same entrance checks here that are later performed
1413 	 * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1414 	 */
1415 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1416 		return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1417 
1418 	file = filename? flac_fopen(filename, "w+b") : stdout;
1419 
1420 	if(file == 0) {
1421 		encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1422 		return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1423 	}
1424 
1425 	return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1426 }
1427 
FLAC__stream_encoder_init_file(FLAC__StreamEncoder * encoder,const char * filename,FLAC__StreamEncoderProgressCallback progress_callback,void * client_data)1428 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1429 	FLAC__StreamEncoder *encoder,
1430 	const char *filename,
1431 	FLAC__StreamEncoderProgressCallback progress_callback,
1432 	void *client_data
1433 )
1434 {
1435 	return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1436 }
1437 
FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder * encoder,const char * filename,FLAC__StreamEncoderProgressCallback progress_callback,void * client_data)1438 FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1439 	FLAC__StreamEncoder *encoder,
1440 	const char *filename,
1441 	FLAC__StreamEncoderProgressCallback progress_callback,
1442 	void *client_data
1443 )
1444 {
1445 	return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1446 }
1447 
FLAC__stream_encoder_finish(FLAC__StreamEncoder * encoder)1448 FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1449 {
1450 	FLAC__bool error = false;
1451 
1452 	FLAC__ASSERT(0 != encoder);
1453 	FLAC__ASSERT(0 != encoder->private_);
1454 	FLAC__ASSERT(0 != encoder->protected_);
1455 
1456 	if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1457 		return true;
1458 
1459 	if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1460 		if(encoder->private_->current_sample_number != 0) {
1461 			const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1462 			encoder->protected_->blocksize = encoder->private_->current_sample_number;
1463 			if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1464 				error = true;
1465 		}
1466 	}
1467 
1468 	if(encoder->protected_->do_md5)
1469 		FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1470 
1471 	if(!encoder->private_->is_being_deleted) {
1472 		if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1473 			if(encoder->private_->seek_callback) {
1474 #if FLAC__HAS_OGG
1475 				if(encoder->private_->is_ogg)
1476 					update_ogg_metadata_(encoder);
1477 				else
1478 #endif
1479 				update_metadata_(encoder);
1480 
1481 				/* check if an error occurred while updating metadata */
1482 				if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1483 					error = true;
1484 			}
1485 			if(encoder->private_->metadata_callback)
1486 				encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1487 		}
1488 
1489 		if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1490 			if(!error)
1491 				encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1492 			error = true;
1493 		}
1494 	}
1495 
1496 	if(0 != encoder->private_->file) {
1497 		if(encoder->private_->file != stdout)
1498 			fclose(encoder->private_->file);
1499 		encoder->private_->file = 0;
1500 	}
1501 
1502 #if FLAC__HAS_OGG
1503 	if(encoder->private_->is_ogg)
1504 		FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1505 #endif
1506 
1507 	free_(encoder);
1508 	set_defaults_(encoder);
1509 
1510 	if(!error)
1511 		encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1512 
1513 	return !error;
1514 }
1515 
FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder * encoder,long value)1516 FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1517 {
1518 	FLAC__ASSERT(0 != encoder);
1519 	FLAC__ASSERT(0 != encoder->private_);
1520 	FLAC__ASSERT(0 != encoder->protected_);
1521 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1522 		return false;
1523 #if FLAC__HAS_OGG
1524 	/* can't check encoder->private_->is_ogg since that's not set until init time */
1525 	FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1526 	return true;
1527 #else
1528 	(void)value;
1529 	return false;
1530 #endif
1531 }
1532 
FLAC__stream_encoder_set_verify(FLAC__StreamEncoder * encoder,FLAC__bool value)1533 FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1534 {
1535 	FLAC__ASSERT(0 != encoder);
1536 	FLAC__ASSERT(0 != encoder->private_);
1537 	FLAC__ASSERT(0 != encoder->protected_);
1538 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1539 		return false;
1540 #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1541 	encoder->protected_->verify = value;
1542 #endif
1543 	return true;
1544 }
1545 
FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder * encoder,FLAC__bool value)1546 FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1547 {
1548 	FLAC__ASSERT(0 != encoder);
1549 	FLAC__ASSERT(0 != encoder->private_);
1550 	FLAC__ASSERT(0 != encoder->protected_);
1551 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1552 		return false;
1553 	encoder->protected_->streamable_subset = value;
1554 	return true;
1555 }
1556 
FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder * encoder,FLAC__bool value)1557 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
1558 {
1559 	FLAC__ASSERT(0 != encoder);
1560 	FLAC__ASSERT(0 != encoder->private_);
1561 	FLAC__ASSERT(0 != encoder->protected_);
1562 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1563 		return false;
1564 	encoder->protected_->do_md5 = value;
1565 	return true;
1566 }
1567 
FLAC__stream_encoder_set_channels(FLAC__StreamEncoder * encoder,unsigned value)1568 FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1569 {
1570 	FLAC__ASSERT(0 != encoder);
1571 	FLAC__ASSERT(0 != encoder->private_);
1572 	FLAC__ASSERT(0 != encoder->protected_);
1573 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1574 		return false;
1575 	encoder->protected_->channels = value;
1576 	return true;
1577 }
1578 
FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder * encoder,unsigned value)1579 FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1580 {
1581 	FLAC__ASSERT(0 != encoder);
1582 	FLAC__ASSERT(0 != encoder->private_);
1583 	FLAC__ASSERT(0 != encoder->protected_);
1584 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1585 		return false;
1586 	encoder->protected_->bits_per_sample = value;
1587 	return true;
1588 }
1589 
FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder * encoder,unsigned value)1590 FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1591 {
1592 	FLAC__ASSERT(0 != encoder);
1593 	FLAC__ASSERT(0 != encoder->private_);
1594 	FLAC__ASSERT(0 != encoder->protected_);
1595 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1596 		return false;
1597 	encoder->protected_->sample_rate = value;
1598 	return true;
1599 }
1600 
FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder * encoder,unsigned value)1601 FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1602 {
1603 	FLAC__bool ok = true;
1604 	FLAC__ASSERT(0 != encoder);
1605 	FLAC__ASSERT(0 != encoder->private_);
1606 	FLAC__ASSERT(0 != encoder->protected_);
1607 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1608 		return false;
1609 	if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1610 		value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1611 	ok &= FLAC__stream_encoder_set_do_mid_side_stereo          (encoder, compression_levels_[value].do_mid_side_stereo);
1612 	ok &= FLAC__stream_encoder_set_loose_mid_side_stereo       (encoder, compression_levels_[value].loose_mid_side_stereo);
1613 #ifndef FLAC__INTEGER_ONLY_LIBRARY
1614 #if 1
1615 	ok &= FLAC__stream_encoder_set_apodization                 (encoder, compression_levels_[value].apodization);
1616 #else
1617 	/* equivalent to -A tukey(0.5) */
1618 	encoder->protected_->num_apodizations = 1;
1619 	encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1620 	encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1621 #endif
1622 #endif
1623 	ok &= FLAC__stream_encoder_set_max_lpc_order               (encoder, compression_levels_[value].max_lpc_order);
1624 	ok &= FLAC__stream_encoder_set_qlp_coeff_precision         (encoder, compression_levels_[value].qlp_coeff_precision);
1625 	ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search    (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1626 	ok &= FLAC__stream_encoder_set_do_escape_coding            (encoder, compression_levels_[value].do_escape_coding);
1627 	ok &= FLAC__stream_encoder_set_do_exhaustive_model_search  (encoder, compression_levels_[value].do_exhaustive_model_search);
1628 	ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1629 	ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1630 	ok &= FLAC__stream_encoder_set_rice_parameter_search_dist  (encoder, compression_levels_[value].rice_parameter_search_dist);
1631 	return ok;
1632 }
1633 
FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder * encoder,unsigned value)1634 FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1635 {
1636 	FLAC__ASSERT(0 != encoder);
1637 	FLAC__ASSERT(0 != encoder->private_);
1638 	FLAC__ASSERT(0 != encoder->protected_);
1639 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1640 		return false;
1641 	encoder->protected_->blocksize = value;
1642 	return true;
1643 }
1644 
FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder * encoder,FLAC__bool value)1645 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1646 {
1647 	FLAC__ASSERT(0 != encoder);
1648 	FLAC__ASSERT(0 != encoder->private_);
1649 	FLAC__ASSERT(0 != encoder->protected_);
1650 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1651 		return false;
1652 	encoder->protected_->do_mid_side_stereo = value;
1653 	return true;
1654 }
1655 
FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder * encoder,FLAC__bool value)1656 FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1657 {
1658 	FLAC__ASSERT(0 != encoder);
1659 	FLAC__ASSERT(0 != encoder->private_);
1660 	FLAC__ASSERT(0 != encoder->protected_);
1661 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1662 		return false;
1663 	encoder->protected_->loose_mid_side_stereo = value;
1664 	return true;
1665 }
1666 
1667 /*@@@@add to tests*/
FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder * encoder,const char * specification)1668 FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1669 {
1670 	FLAC__ASSERT(0 != encoder);
1671 	FLAC__ASSERT(0 != encoder->private_);
1672 	FLAC__ASSERT(0 != encoder->protected_);
1673 	FLAC__ASSERT(0 != specification);
1674 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1675 		return false;
1676 #ifdef FLAC__INTEGER_ONLY_LIBRARY
1677 	(void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1678 #else
1679 	encoder->protected_->num_apodizations = 0;
1680 	while(1) {
1681 		const char *s = strchr(specification, ';');
1682 		const size_t n = s? (size_t)(s - specification) : strlen(specification);
1683 		if     (n==8  && 0 == strncmp("bartlett"     , specification, n))
1684 			encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1685 		else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1686 			encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1687 		else if(n==8  && 0 == strncmp("blackman"     , specification, n))
1688 			encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1689 		else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1690 			encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1691 		else if(n==6  && 0 == strncmp("connes"       , specification, n))
1692 			encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1693 		else if(n==7  && 0 == strncmp("flattop"      , specification, n))
1694 			encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1695 		else if(n>7   && 0 == strncmp("gauss("       , specification, 6)) {
1696 			FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1697 			if (stddev > 0.0 && stddev <= 0.5) {
1698 				encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1699 				encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1700 			}
1701 		}
1702 		else if(n==7  && 0 == strncmp("hamming"      , specification, n))
1703 			encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1704 		else if(n==4  && 0 == strncmp("hann"         , specification, n))
1705 			encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1706 		else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1707 			encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1708 		else if(n==7  && 0 == strncmp("nuttall"      , specification, n))
1709 			encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1710 		else if(n==9  && 0 == strncmp("rectangle"    , specification, n))
1711 			encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1712 		else if(n==8  && 0 == strncmp("triangle"     , specification, n))
1713 			encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1714 		else if(n>7   && 0 == strncmp("tukey("       , specification, 6)) {
1715 			FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1716 			if (p >= 0.0 && p <= 1.0) {
1717 				encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1718 				encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1719 			}
1720 		}
1721 		else if(n>15   && 0 == strncmp("partial_tukey("       , specification, 14)) {
1722 			FLAC__int32 tukey_parts = (FLAC__int32)strtod(specification+14, 0);
1723 			const char *si_1 = strchr(specification, '/');
1724 			FLAC__real overlap = si_1?flac_min((FLAC__real)strtod(si_1+1, 0),0.99f):0.1f;
1725 			FLAC__real overlap_units = 1.0f/(1.0f - overlap) - 1.0f;
1726 			const char *si_2 = strchr((si_1?(si_1+1):specification), '/');
1727 			FLAC__real tukey_p = si_2?(FLAC__real)strtod(si_2+1, 0):0.2f;
1728 
1729 			if (tukey_parts <= 1) {
1730 				encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = tukey_p;
1731 				encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1732 			}else if (encoder->protected_->num_apodizations + tukey_parts < 32){
1733 				FLAC__int32 m;
1734 				for(m = 0; m < tukey_parts; m++){
1735 					encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.p = tukey_p;
1736 					encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.start = m/(tukey_parts+overlap_units);
1737 					encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.end = (m+1+overlap_units)/(tukey_parts+overlap_units);
1738 					encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_PARTIAL_TUKEY;
1739 				}
1740 			}
1741 		}
1742 		else if(n>16   && 0 == strncmp("punchout_tukey("       , specification, 15)) {
1743 			FLAC__int32 tukey_parts = (FLAC__int32)strtod(specification+15, 0);
1744 			const char *si_1 = strchr(specification, '/');
1745 			FLAC__real overlap = si_1?flac_min((FLAC__real)strtod(si_1+1, 0),0.99f):0.2f;
1746 			FLAC__real overlap_units = 1.0f/(1.0f - overlap) - 1.0f;
1747 			const char *si_2 = strchr((si_1?(si_1+1):specification), '/');
1748 			FLAC__real tukey_p = si_2?(FLAC__real)strtod(si_2+1, 0):0.2f;
1749 
1750 			if (tukey_parts <= 1) {
1751 				encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = tukey_p;
1752 				encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1753 			}else if (encoder->protected_->num_apodizations + tukey_parts < 32){
1754 				FLAC__int32 m;
1755 				for(m = 0; m < tukey_parts; m++){
1756 					encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.p = tukey_p;
1757 					encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.start = m/(tukey_parts+overlap_units);
1758 					encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.end = (m+1+overlap_units)/(tukey_parts+overlap_units);
1759 					encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_PUNCHOUT_TUKEY;
1760 				}
1761 			}
1762 		}
1763 		else if(n==5  && 0 == strncmp("welch"        , specification, n))
1764 			encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1765 		if (encoder->protected_->num_apodizations == 32)
1766 			break;
1767 		if (s)
1768 			specification = s+1;
1769 		else
1770 			break;
1771 	}
1772 	if(encoder->protected_->num_apodizations == 0) {
1773 		encoder->protected_->num_apodizations = 1;
1774 		encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1775 		encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1776 	}
1777 #endif
1778 	return true;
1779 }
1780 
FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder * encoder,unsigned value)1781 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1782 {
1783 	FLAC__ASSERT(0 != encoder);
1784 	FLAC__ASSERT(0 != encoder->private_);
1785 	FLAC__ASSERT(0 != encoder->protected_);
1786 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1787 		return false;
1788 	encoder->protected_->max_lpc_order = value;
1789 	return true;
1790 }
1791 
FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder * encoder,unsigned value)1792 FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1793 {
1794 	FLAC__ASSERT(0 != encoder);
1795 	FLAC__ASSERT(0 != encoder->private_);
1796 	FLAC__ASSERT(0 != encoder->protected_);
1797 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1798 		return false;
1799 	encoder->protected_->qlp_coeff_precision = value;
1800 	return true;
1801 }
1802 
FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder * encoder,FLAC__bool value)1803 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1804 {
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_qlp_coeff_prec_search = value;
1811 	return true;
1812 }
1813 
FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder * encoder,FLAC__bool value)1814 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1815 {
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 #if 0
1822 	/*@@@ deprecated: */
1823 	encoder->protected_->do_escape_coding = value;
1824 #else
1825 	(void)value;
1826 #endif
1827 	return true;
1828 }
1829 
FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder * encoder,FLAC__bool value)1830 FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1831 {
1832 	FLAC__ASSERT(0 != encoder);
1833 	FLAC__ASSERT(0 != encoder->private_);
1834 	FLAC__ASSERT(0 != encoder->protected_);
1835 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1836 		return false;
1837 	encoder->protected_->do_exhaustive_model_search = value;
1838 	return true;
1839 }
1840 
FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder * encoder,unsigned value)1841 FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1842 {
1843 	FLAC__ASSERT(0 != encoder);
1844 	FLAC__ASSERT(0 != encoder->private_);
1845 	FLAC__ASSERT(0 != encoder->protected_);
1846 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1847 		return false;
1848 	encoder->protected_->min_residual_partition_order = value;
1849 	return true;
1850 }
1851 
FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder * encoder,unsigned value)1852 FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1853 {
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_->max_residual_partition_order = value;
1860 	return true;
1861 }
1862 
FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder * encoder,unsigned value)1863 FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1864 {
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
1871 	/*@@@ deprecated: */
1872 	encoder->protected_->rice_parameter_search_dist = value;
1873 #else
1874 	(void)value;
1875 #endif
1876 	return true;
1877 }
1878 
FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder * encoder,FLAC__uint64 value)1879 FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1880 {
1881 	FLAC__ASSERT(0 != encoder);
1882 	FLAC__ASSERT(0 != encoder->private_);
1883 	FLAC__ASSERT(0 != encoder->protected_);
1884 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1885 		return false;
1886 	encoder->protected_->total_samples_estimate = value;
1887 	return true;
1888 }
1889 
FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder * encoder,FLAC__StreamMetadata ** metadata,unsigned num_blocks)1890 FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1891 {
1892 	FLAC__ASSERT(0 != encoder);
1893 	FLAC__ASSERT(0 != encoder->private_);
1894 	FLAC__ASSERT(0 != encoder->protected_);
1895 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1896 		return false;
1897 	if(0 == metadata)
1898 		num_blocks = 0;
1899 	if(0 == num_blocks)
1900 		metadata = 0;
1901 	/* realloc() does not do exactly what we want so... */
1902 	if(encoder->protected_->metadata) {
1903 		free(encoder->protected_->metadata);
1904 		encoder->protected_->metadata = 0;
1905 		encoder->protected_->num_metadata_blocks = 0;
1906 	}
1907 	if(num_blocks) {
1908 		FLAC__StreamMetadata **m;
1909 		if(0 == (m = safe_malloc_mul_2op_p(sizeof(m[0]), /*times*/num_blocks)))
1910 			return false;
1911 		memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1912 		encoder->protected_->metadata = m;
1913 		encoder->protected_->num_metadata_blocks = num_blocks;
1914 	}
1915 #if FLAC__HAS_OGG
1916 	if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1917 		return false;
1918 #endif
1919 	return true;
1920 }
1921 
1922 /*
1923  * These three functions are not static, but not publically exposed in
1924  * include/FLAC/ either.  They are used by the test suite.
1925  */
FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder * encoder,FLAC__bool value)1926 FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1927 {
1928 	FLAC__ASSERT(0 != encoder);
1929 	FLAC__ASSERT(0 != encoder->private_);
1930 	FLAC__ASSERT(0 != encoder->protected_);
1931 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1932 		return false;
1933 	encoder->private_->disable_constant_subframes = value;
1934 	return true;
1935 }
1936 
FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder * encoder,FLAC__bool value)1937 FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1938 {
1939 	FLAC__ASSERT(0 != encoder);
1940 	FLAC__ASSERT(0 != encoder->private_);
1941 	FLAC__ASSERT(0 != encoder->protected_);
1942 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1943 		return false;
1944 	encoder->private_->disable_fixed_subframes = value;
1945 	return true;
1946 }
1947 
FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder * encoder,FLAC__bool value)1948 FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1949 {
1950 	FLAC__ASSERT(0 != encoder);
1951 	FLAC__ASSERT(0 != encoder->private_);
1952 	FLAC__ASSERT(0 != encoder->protected_);
1953 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1954 		return false;
1955 	encoder->private_->disable_verbatim_subframes = value;
1956 	return true;
1957 }
1958 
FLAC__stream_encoder_get_state(const FLAC__StreamEncoder * encoder)1959 FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1960 {
1961 	FLAC__ASSERT(0 != encoder);
1962 	FLAC__ASSERT(0 != encoder->private_);
1963 	FLAC__ASSERT(0 != encoder->protected_);
1964 	return encoder->protected_->state;
1965 }
1966 
FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder * encoder)1967 FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1968 {
1969 	FLAC__ASSERT(0 != encoder);
1970 	FLAC__ASSERT(0 != encoder->private_);
1971 	FLAC__ASSERT(0 != encoder->protected_);
1972 	if(encoder->protected_->verify)
1973 		return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1974 	else
1975 		return FLAC__STREAM_DECODER_UNINITIALIZED;
1976 }
1977 
FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder * encoder)1978 FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1979 {
1980 	FLAC__ASSERT(0 != encoder);
1981 	FLAC__ASSERT(0 != encoder->private_);
1982 	FLAC__ASSERT(0 != encoder->protected_);
1983 	if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1984 		return FLAC__StreamEncoderStateString[encoder->protected_->state];
1985 	else
1986 		return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1987 }
1988 
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)1989 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)
1990 {
1991 	FLAC__ASSERT(0 != encoder);
1992 	FLAC__ASSERT(0 != encoder->private_);
1993 	FLAC__ASSERT(0 != encoder->protected_);
1994 	if(0 != absolute_sample)
1995 		*absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1996 	if(0 != frame_number)
1997 		*frame_number = encoder->private_->verify.error_stats.frame_number;
1998 	if(0 != channel)
1999 		*channel = encoder->private_->verify.error_stats.channel;
2000 	if(0 != sample)
2001 		*sample = encoder->private_->verify.error_stats.sample;
2002 	if(0 != expected)
2003 		*expected = encoder->private_->verify.error_stats.expected;
2004 	if(0 != got)
2005 		*got = encoder->private_->verify.error_stats.got;
2006 }
2007 
FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder * encoder)2008 FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
2009 {
2010 	FLAC__ASSERT(0 != encoder);
2011 	FLAC__ASSERT(0 != encoder->private_);
2012 	FLAC__ASSERT(0 != encoder->protected_);
2013 	return encoder->protected_->verify;
2014 }
2015 
FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder * encoder)2016 FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
2017 {
2018 	FLAC__ASSERT(0 != encoder);
2019 	FLAC__ASSERT(0 != encoder->private_);
2020 	FLAC__ASSERT(0 != encoder->protected_);
2021 	return encoder->protected_->streamable_subset;
2022 }
2023 
FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder * encoder)2024 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
2025 {
2026 	FLAC__ASSERT(0 != encoder);
2027 	FLAC__ASSERT(0 != encoder->private_);
2028 	FLAC__ASSERT(0 != encoder->protected_);
2029 	return encoder->protected_->do_md5;
2030 }
2031 
FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder * encoder)2032 FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
2033 {
2034 	FLAC__ASSERT(0 != encoder);
2035 	FLAC__ASSERT(0 != encoder->private_);
2036 	FLAC__ASSERT(0 != encoder->protected_);
2037 	return encoder->protected_->channels;
2038 }
2039 
FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder * encoder)2040 FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
2041 {
2042 	FLAC__ASSERT(0 != encoder);
2043 	FLAC__ASSERT(0 != encoder->private_);
2044 	FLAC__ASSERT(0 != encoder->protected_);
2045 	return encoder->protected_->bits_per_sample;
2046 }
2047 
FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder * encoder)2048 FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
2049 {
2050 	FLAC__ASSERT(0 != encoder);
2051 	FLAC__ASSERT(0 != encoder->private_);
2052 	FLAC__ASSERT(0 != encoder->protected_);
2053 	return encoder->protected_->sample_rate;
2054 }
2055 
FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder * encoder)2056 FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
2057 {
2058 	FLAC__ASSERT(0 != encoder);
2059 	FLAC__ASSERT(0 != encoder->private_);
2060 	FLAC__ASSERT(0 != encoder->protected_);
2061 	return encoder->protected_->blocksize;
2062 }
2063 
FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder * encoder)2064 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
2065 {
2066 	FLAC__ASSERT(0 != encoder);
2067 	FLAC__ASSERT(0 != encoder->private_);
2068 	FLAC__ASSERT(0 != encoder->protected_);
2069 	return encoder->protected_->do_mid_side_stereo;
2070 }
2071 
FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder * encoder)2072 FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
2073 {
2074 	FLAC__ASSERT(0 != encoder);
2075 	FLAC__ASSERT(0 != encoder->private_);
2076 	FLAC__ASSERT(0 != encoder->protected_);
2077 	return encoder->protected_->loose_mid_side_stereo;
2078 }
2079 
FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder * encoder)2080 FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
2081 {
2082 	FLAC__ASSERT(0 != encoder);
2083 	FLAC__ASSERT(0 != encoder->private_);
2084 	FLAC__ASSERT(0 != encoder->protected_);
2085 	return encoder->protected_->max_lpc_order;
2086 }
2087 
FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder * encoder)2088 FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
2089 {
2090 	FLAC__ASSERT(0 != encoder);
2091 	FLAC__ASSERT(0 != encoder->private_);
2092 	FLAC__ASSERT(0 != encoder->protected_);
2093 	return encoder->protected_->qlp_coeff_precision;
2094 }
2095 
FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder * encoder)2096 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
2097 {
2098 	FLAC__ASSERT(0 != encoder);
2099 	FLAC__ASSERT(0 != encoder->private_);
2100 	FLAC__ASSERT(0 != encoder->protected_);
2101 	return encoder->protected_->do_qlp_coeff_prec_search;
2102 }
2103 
FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder * encoder)2104 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
2105 {
2106 	FLAC__ASSERT(0 != encoder);
2107 	FLAC__ASSERT(0 != encoder->private_);
2108 	FLAC__ASSERT(0 != encoder->protected_);
2109 	return encoder->protected_->do_escape_coding;
2110 }
2111 
FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder * encoder)2112 FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
2113 {
2114 	FLAC__ASSERT(0 != encoder);
2115 	FLAC__ASSERT(0 != encoder->private_);
2116 	FLAC__ASSERT(0 != encoder->protected_);
2117 	return encoder->protected_->do_exhaustive_model_search;
2118 }
2119 
FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder * encoder)2120 FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
2121 {
2122 	FLAC__ASSERT(0 != encoder);
2123 	FLAC__ASSERT(0 != encoder->private_);
2124 	FLAC__ASSERT(0 != encoder->protected_);
2125 	return encoder->protected_->min_residual_partition_order;
2126 }
2127 
FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder * encoder)2128 FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
2129 {
2130 	FLAC__ASSERT(0 != encoder);
2131 	FLAC__ASSERT(0 != encoder->private_);
2132 	FLAC__ASSERT(0 != encoder->protected_);
2133 	return encoder->protected_->max_residual_partition_order;
2134 }
2135 
FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder * encoder)2136 FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
2137 {
2138 	FLAC__ASSERT(0 != encoder);
2139 	FLAC__ASSERT(0 != encoder->private_);
2140 	FLAC__ASSERT(0 != encoder->protected_);
2141 	return encoder->protected_->rice_parameter_search_dist;
2142 }
2143 
FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder * encoder)2144 FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
2145 {
2146 	FLAC__ASSERT(0 != encoder);
2147 	FLAC__ASSERT(0 != encoder->private_);
2148 	FLAC__ASSERT(0 != encoder->protected_);
2149 	return encoder->protected_->total_samples_estimate;
2150 }
2151 
FLAC__stream_encoder_process(FLAC__StreamEncoder * encoder,const FLAC__int32 * const buffer[],unsigned samples)2152 FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
2153 {
2154 	unsigned i, j = 0, channel;
2155 	const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2156 
2157 	FLAC__ASSERT(0 != encoder);
2158 	FLAC__ASSERT(0 != encoder->private_);
2159 	FLAC__ASSERT(0 != encoder->protected_);
2160 	FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2161 
2162 	do {
2163 		const unsigned n = flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
2164 
2165 		if(encoder->protected_->verify)
2166 			append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
2167 
2168 		for(channel = 0; channel < channels; channel++)
2169 			memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
2170 
2171 		if(encoder->protected_->do_mid_side_stereo) {
2172 			FLAC__ASSERT(channels == 2);
2173 			/* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2174 			for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2175 				encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
2176 				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' ! */
2177 			}
2178 		}
2179 		else
2180 			j += n;
2181 
2182 		encoder->private_->current_sample_number += n;
2183 
2184 		/* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2185 		if(encoder->private_->current_sample_number > blocksize) {
2186 			FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
2187 			FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2188 			if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2189 				return false;
2190 			/* move unprocessed overread samples to beginnings of arrays */
2191 			for(channel = 0; channel < channels; channel++)
2192 				encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2193 			if(encoder->protected_->do_mid_side_stereo) {
2194 				encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2195 				encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2196 			}
2197 			encoder->private_->current_sample_number = 1;
2198 		}
2199 	} while(j < samples);
2200 
2201 	return true;
2202 }
2203 
FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder * encoder,const FLAC__int32 buffer[],unsigned samples)2204 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2205 {
2206 	unsigned i, j, k, channel;
2207 	FLAC__int32 x, mid, side;
2208 	const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2209 
2210 	FLAC__ASSERT(0 != encoder);
2211 	FLAC__ASSERT(0 != encoder->private_);
2212 	FLAC__ASSERT(0 != encoder->protected_);
2213 	FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2214 
2215 	j = k = 0;
2216 	/*
2217 	 * we have several flavors of the same basic loop, optimized for
2218 	 * different conditions:
2219 	 */
2220 	if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2221 		/*
2222 		 * stereo coding: unroll channel loop
2223 		 */
2224 		do {
2225 			if(encoder->protected_->verify)
2226 				append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2227 
2228 			/* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2229 			for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2230 				encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2231 				x = buffer[k++];
2232 				encoder->private_->integer_signal[1][i] = x;
2233 				mid += x;
2234 				side -= x;
2235 				mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2236 				encoder->private_->integer_signal_mid_side[1][i] = side;
2237 				encoder->private_->integer_signal_mid_side[0][i] = mid;
2238 			}
2239 			encoder->private_->current_sample_number = i;
2240 			/* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2241 			if(i > blocksize) {
2242 				if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2243 					return false;
2244 				/* move unprocessed overread samples to beginnings of arrays */
2245 				FLAC__ASSERT(i == blocksize+OVERREAD_);
2246 				FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2247 				encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
2248 				encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
2249 				encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2250 				encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2251 				encoder->private_->current_sample_number = 1;
2252 			}
2253 		} while(j < samples);
2254 	}
2255 	else {
2256 		/*
2257 		 * independent channel coding: buffer each channel in inner loop
2258 		 */
2259 		do {
2260 			if(encoder->protected_->verify)
2261 				append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2262 
2263 			/* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2264 			for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2265 				for(channel = 0; channel < channels; channel++)
2266 					encoder->private_->integer_signal[channel][i] = buffer[k++];
2267 			}
2268 			encoder->private_->current_sample_number = i;
2269 			/* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2270 			if(i > blocksize) {
2271 				if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2272 					return false;
2273 				/* move unprocessed overread samples to beginnings of arrays */
2274 				FLAC__ASSERT(i == blocksize+OVERREAD_);
2275 				FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2276 				for(channel = 0; channel < channels; channel++)
2277 					encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2278 				encoder->private_->current_sample_number = 1;
2279 			}
2280 		} while(j < samples);
2281 	}
2282 
2283 	return true;
2284 }
2285 
2286 /***********************************************************************
2287  *
2288  * Private class methods
2289  *
2290  ***********************************************************************/
2291 
set_defaults_(FLAC__StreamEncoder * encoder)2292 void set_defaults_(FLAC__StreamEncoder *encoder)
2293 {
2294 	FLAC__ASSERT(0 != encoder);
2295 
2296 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2297 	encoder->protected_->verify = true;
2298 #else
2299 	encoder->protected_->verify = false;
2300 #endif
2301 	encoder->protected_->streamable_subset = true;
2302 	encoder->protected_->do_md5 = true;
2303 	encoder->protected_->do_mid_side_stereo = false;
2304 	encoder->protected_->loose_mid_side_stereo = false;
2305 	encoder->protected_->channels = 2;
2306 	encoder->protected_->bits_per_sample = 16;
2307 	encoder->protected_->sample_rate = 44100;
2308 	encoder->protected_->blocksize = 0;
2309 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2310 	encoder->protected_->num_apodizations = 1;
2311 	encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2312 	encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2313 #endif
2314 	encoder->protected_->max_lpc_order = 0;
2315 	encoder->protected_->qlp_coeff_precision = 0;
2316 	encoder->protected_->do_qlp_coeff_prec_search = false;
2317 	encoder->protected_->do_exhaustive_model_search = false;
2318 	encoder->protected_->do_escape_coding = false;
2319 	encoder->protected_->min_residual_partition_order = 0;
2320 	encoder->protected_->max_residual_partition_order = 0;
2321 	encoder->protected_->rice_parameter_search_dist = 0;
2322 	encoder->protected_->total_samples_estimate = 0;
2323 	encoder->protected_->metadata = 0;
2324 	encoder->protected_->num_metadata_blocks = 0;
2325 
2326 	encoder->private_->seek_table = 0;
2327 	encoder->private_->disable_constant_subframes = false;
2328 	encoder->private_->disable_fixed_subframes = false;
2329 	encoder->private_->disable_verbatim_subframes = false;
2330 #if FLAC__HAS_OGG
2331 	encoder->private_->is_ogg = false;
2332 #endif
2333 	encoder->private_->read_callback = 0;
2334 	encoder->private_->write_callback = 0;
2335 	encoder->private_->seek_callback = 0;
2336 	encoder->private_->tell_callback = 0;
2337 	encoder->private_->metadata_callback = 0;
2338 	encoder->private_->progress_callback = 0;
2339 	encoder->private_->client_data = 0;
2340 
2341 #if FLAC__HAS_OGG
2342 	FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2343 #endif
2344 
2345 	FLAC__stream_encoder_set_compression_level(encoder, 5);
2346 }
2347 
free_(FLAC__StreamEncoder * encoder)2348 void free_(FLAC__StreamEncoder *encoder)
2349 {
2350 	unsigned i, channel;
2351 
2352 	FLAC__ASSERT(0 != encoder);
2353 	if(encoder->protected_->metadata) {
2354 		free(encoder->protected_->metadata);
2355 		encoder->protected_->metadata = 0;
2356 		encoder->protected_->num_metadata_blocks = 0;
2357 	}
2358 	for(i = 0; i < encoder->protected_->channels; i++) {
2359 		if(0 != encoder->private_->integer_signal_unaligned[i]) {
2360 			free(encoder->private_->integer_signal_unaligned[i]);
2361 			encoder->private_->integer_signal_unaligned[i] = 0;
2362 		}
2363 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2364 		if(0 != encoder->private_->real_signal_unaligned[i]) {
2365 			free(encoder->private_->real_signal_unaligned[i]);
2366 			encoder->private_->real_signal_unaligned[i] = 0;
2367 		}
2368 #endif
2369 	}
2370 	for(i = 0; i < 2; i++) {
2371 		if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2372 			free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2373 			encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2374 		}
2375 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2376 		if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2377 			free(encoder->private_->real_signal_mid_side_unaligned[i]);
2378 			encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2379 		}
2380 #endif
2381 	}
2382 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2383 	for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2384 		if(0 != encoder->private_->window_unaligned[i]) {
2385 			free(encoder->private_->window_unaligned[i]);
2386 			encoder->private_->window_unaligned[i] = 0;
2387 		}
2388 	}
2389 	if(0 != encoder->private_->windowed_signal_unaligned) {
2390 		free(encoder->private_->windowed_signal_unaligned);
2391 		encoder->private_->windowed_signal_unaligned = 0;
2392 	}
2393 #endif
2394 	for(channel = 0; channel < encoder->protected_->channels; channel++) {
2395 		for(i = 0; i < 2; i++) {
2396 			if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2397 				free(encoder->private_->residual_workspace_unaligned[channel][i]);
2398 				encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2399 			}
2400 		}
2401 	}
2402 	for(channel = 0; channel < 2; channel++) {
2403 		for(i = 0; i < 2; i++) {
2404 			if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2405 				free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2406 				encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2407 			}
2408 		}
2409 	}
2410 	if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2411 		free(encoder->private_->abs_residual_partition_sums_unaligned);
2412 		encoder->private_->abs_residual_partition_sums_unaligned = 0;
2413 	}
2414 	if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2415 		free(encoder->private_->raw_bits_per_partition_unaligned);
2416 		encoder->private_->raw_bits_per_partition_unaligned = 0;
2417 	}
2418 	if(encoder->protected_->verify) {
2419 		for(i = 0; i < encoder->protected_->channels; i++) {
2420 			if(0 != encoder->private_->verify.input_fifo.data[i]) {
2421 				free(encoder->private_->verify.input_fifo.data[i]);
2422 				encoder->private_->verify.input_fifo.data[i] = 0;
2423 			}
2424 		}
2425 	}
2426 	FLAC__bitwriter_free(encoder->private_->frame);
2427 }
2428 
resize_buffers_(FLAC__StreamEncoder * encoder,unsigned new_blocksize)2429 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2430 {
2431 	FLAC__bool ok;
2432 	unsigned i, channel;
2433 
2434 	FLAC__ASSERT(new_blocksize > 0);
2435 	FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2436 	FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2437 
2438 	/* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2439 	if(new_blocksize <= encoder->private_->input_capacity)
2440 		return true;
2441 
2442 	ok = true;
2443 
2444 	/* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx() and ..._intrin_sse2()
2445 	 * require that the input arrays (in our case the integer signals)
2446 	 * have a buffer of up to 3 zeroes in front (at negative indices) for
2447 	 * alignment purposes; we use 4 in front to keep the data well-aligned.
2448 	 */
2449 
2450 	for(i = 0; ok && i < encoder->protected_->channels; i++) {
2451 		ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2452 		memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2453 		encoder->private_->integer_signal[i] += 4;
2454 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2455 #if 0 /* @@@ currently unused */
2456 		if(encoder->protected_->max_lpc_order > 0)
2457 			ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2458 #endif
2459 #endif
2460 	}
2461 	for(i = 0; ok && i < 2; i++) {
2462 		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]);
2463 		memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2464 		encoder->private_->integer_signal_mid_side[i] += 4;
2465 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2466 #if 0 /* @@@ currently unused */
2467 		if(encoder->protected_->max_lpc_order > 0)
2468 			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]);
2469 #endif
2470 #endif
2471 	}
2472 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2473 	if(ok && encoder->protected_->max_lpc_order > 0) {
2474 		for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2475 			ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2476 		ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2477 	}
2478 #endif
2479 	for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2480 		for(i = 0; ok && i < 2; i++) {
2481 			ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2482 		}
2483 	}
2484 	for(channel = 0; ok && channel < 2; channel++) {
2485 		for(i = 0; ok && i < 2; i++) {
2486 			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]);
2487 		}
2488 	}
2489 	/* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2490 	/*@@@ 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) */
2491 	ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2492 	if(encoder->protected_->do_escape_coding)
2493 		ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2494 
2495 	/* now adjust the windows if the blocksize has changed */
2496 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2497 	if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2498 		for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2499 			switch(encoder->protected_->apodizations[i].type) {
2500 				case FLAC__APODIZATION_BARTLETT:
2501 					FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2502 					break;
2503 				case FLAC__APODIZATION_BARTLETT_HANN:
2504 					FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2505 					break;
2506 				case FLAC__APODIZATION_BLACKMAN:
2507 					FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2508 					break;
2509 				case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2510 					FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2511 					break;
2512 				case FLAC__APODIZATION_CONNES:
2513 					FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2514 					break;
2515 				case FLAC__APODIZATION_FLATTOP:
2516 					FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2517 					break;
2518 				case FLAC__APODIZATION_GAUSS:
2519 					FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2520 					break;
2521 				case FLAC__APODIZATION_HAMMING:
2522 					FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2523 					break;
2524 				case FLAC__APODIZATION_HANN:
2525 					FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2526 					break;
2527 				case FLAC__APODIZATION_KAISER_BESSEL:
2528 					FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2529 					break;
2530 				case FLAC__APODIZATION_NUTTALL:
2531 					FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2532 					break;
2533 				case FLAC__APODIZATION_RECTANGLE:
2534 					FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2535 					break;
2536 				case FLAC__APODIZATION_TRIANGLE:
2537 					FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2538 					break;
2539 				case FLAC__APODIZATION_TUKEY:
2540 					FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2541 					break;
2542 				case FLAC__APODIZATION_PARTIAL_TUKEY:
2543 					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);
2544 					break;
2545 				case FLAC__APODIZATION_PUNCHOUT_TUKEY:
2546 					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);
2547 					break;
2548 				case FLAC__APODIZATION_WELCH:
2549 					FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2550 					break;
2551 				default:
2552 					FLAC__ASSERT(0);
2553 					/* double protection */
2554 					FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2555 					break;
2556 			}
2557 		}
2558 	}
2559 #endif
2560 
2561 	if(ok)
2562 		encoder->private_->input_capacity = new_blocksize;
2563 	else
2564 		encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2565 
2566 	return ok;
2567 }
2568 
write_bitbuffer_(FLAC__StreamEncoder * encoder,unsigned samples,FLAC__bool is_last_block)2569 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2570 {
2571 	const FLAC__byte *buffer;
2572 	size_t bytes;
2573 
2574 	FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2575 
2576 	if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2577 		encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2578 		return false;
2579 	}
2580 
2581 	if(encoder->protected_->verify) {
2582 		encoder->private_->verify.output.data = buffer;
2583 		encoder->private_->verify.output.bytes = bytes;
2584 		if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2585 			encoder->private_->verify.needs_magic_hack = true;
2586 		}
2587 		else {
2588 			if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2589 				FLAC__bitwriter_release_buffer(encoder->private_->frame);
2590 				FLAC__bitwriter_clear(encoder->private_->frame);
2591 				if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2592 					encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2593 				return false;
2594 			}
2595 		}
2596 	}
2597 
2598 	if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2599 		FLAC__bitwriter_release_buffer(encoder->private_->frame);
2600 		FLAC__bitwriter_clear(encoder->private_->frame);
2601 		encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2602 		return false;
2603 	}
2604 
2605 	FLAC__bitwriter_release_buffer(encoder->private_->frame);
2606 	FLAC__bitwriter_clear(encoder->private_->frame);
2607 
2608 	if(samples > 0) {
2609 		encoder->private_->streaminfo.data.stream_info.min_framesize = flac_min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2610 		encoder->private_->streaminfo.data.stream_info.max_framesize = flac_max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2611 	}
2612 
2613 	return true;
2614 }
2615 
write_frame_(FLAC__StreamEncoder * encoder,const FLAC__byte buffer[],size_t bytes,unsigned samples,FLAC__bool is_last_block)2616 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2617 {
2618 	FLAC__StreamEncoderWriteStatus status;
2619 	FLAC__uint64 output_position = 0;
2620 
2621 #if FLAC__HAS_OGG == 0
2622 	(void)is_last_block;
2623 #endif
2624 
2625 	/* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2626 	if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2627 		encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2628 		return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2629 	}
2630 
2631 	/*
2632 	 * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2633 	 */
2634 	if(samples == 0) {
2635 		FLAC__MetadataType type = (buffer[0] & 0x7f);
2636 		if(type == FLAC__METADATA_TYPE_STREAMINFO)
2637 			encoder->protected_->streaminfo_offset = output_position;
2638 		else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2639 			encoder->protected_->seektable_offset = output_position;
2640 	}
2641 
2642 	/*
2643 	 * Mark the current seek point if hit (if audio_offset == 0 that
2644 	 * means we're still writing metadata and haven't hit the first
2645 	 * frame yet)
2646 	 */
2647 	if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2648 		const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2649 		const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2650 		const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2651 		FLAC__uint64 test_sample;
2652 		unsigned i;
2653 		for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2654 			test_sample = encoder->private_->seek_table->points[i].sample_number;
2655 			if(test_sample > frame_last_sample) {
2656 				break;
2657 			}
2658 			else if(test_sample >= frame_first_sample) {
2659 				encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2660 				encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2661 				encoder->private_->seek_table->points[i].frame_samples = blocksize;
2662 				encoder->private_->first_seekpoint_to_check++;
2663 				/* DO NOT: "break;" and here's why:
2664 				 * The seektable template may contain more than one target
2665 				 * sample for any given frame; we will keep looping, generating
2666 				 * duplicate seekpoints for them, and we'll clean it up later,
2667 				 * just before writing the seektable back to the metadata.
2668 				 */
2669 			}
2670 			else {
2671 				encoder->private_->first_seekpoint_to_check++;
2672 			}
2673 		}
2674 	}
2675 
2676 #if FLAC__HAS_OGG
2677 	if(encoder->private_->is_ogg) {
2678 		status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2679 			&encoder->protected_->ogg_encoder_aspect,
2680 			buffer,
2681 			bytes,
2682 			samples,
2683 			encoder->private_->current_frame_number,
2684 			is_last_block,
2685 			(FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2686 			encoder,
2687 			encoder->private_->client_data
2688 		);
2689 	}
2690 	else
2691 #endif
2692 	status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2693 
2694 	if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2695 		encoder->private_->bytes_written += bytes;
2696 		encoder->private_->samples_written += samples;
2697 		/* we keep a high watermark on the number of frames written because
2698 		 * when the encoder goes back to write metadata, 'current_frame'
2699 		 * will drop back to 0.
2700 		 */
2701 		encoder->private_->frames_written = flac_max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2702 	}
2703 	else
2704 		encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2705 
2706 	return status;
2707 }
2708 
2709 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
update_metadata_(const FLAC__StreamEncoder * encoder)2710 void update_metadata_(const FLAC__StreamEncoder *encoder)
2711 {
2712 	FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2713 	const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2714 	const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2715 	const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2716 	const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2717 	const unsigned bps = metadata->data.stream_info.bits_per_sample;
2718 	FLAC__StreamEncoderSeekStatus seek_status;
2719 
2720 	FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2721 
2722 	/* All this is based on intimate knowledge of the stream header
2723 	 * layout, but a change to the header format that would break this
2724 	 * would also break all streams encoded in the previous format.
2725 	 */
2726 
2727 	/*
2728 	 * Write MD5 signature
2729 	 */
2730 	{
2731 		const unsigned md5_offset =
2732 			FLAC__STREAM_METADATA_HEADER_LENGTH +
2733 			(
2734 				FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2735 				FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2736 				FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2737 				FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2738 				FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2739 				FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2740 				FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2741 				FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2742 			) / 8;
2743 
2744 		if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2745 			if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2746 				encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2747 			return;
2748 		}
2749 		if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2750 			encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2751 			return;
2752 		}
2753 	}
2754 
2755 	/*
2756 	 * Write total samples
2757 	 */
2758 	{
2759 		const unsigned total_samples_byte_offset =
2760 			FLAC__STREAM_METADATA_HEADER_LENGTH +
2761 			(
2762 				FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2763 				FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2764 				FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2765 				FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2766 				FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2767 				FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2768 				FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2769 				- 4
2770 			) / 8;
2771 
2772 		b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2773 		b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2774 		b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2775 		b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2776 		b[4] = (FLAC__byte)(samples & 0xFF);
2777 		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) {
2778 			if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2779 				encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2780 			return;
2781 		}
2782 		if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2783 			encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2784 			return;
2785 		}
2786 	}
2787 
2788 	/*
2789 	 * Write min/max framesize
2790 	 */
2791 	{
2792 		const unsigned min_framesize_offset =
2793 			FLAC__STREAM_METADATA_HEADER_LENGTH +
2794 			(
2795 				FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2796 				FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2797 			) / 8;
2798 
2799 		b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2800 		b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2801 		b[2] = (FLAC__byte)(min_framesize & 0xFF);
2802 		b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2803 		b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2804 		b[5] = (FLAC__byte)(max_framesize & 0xFF);
2805 		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) {
2806 			if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2807 				encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2808 			return;
2809 		}
2810 		if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2811 			encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2812 			return;
2813 		}
2814 	}
2815 
2816 	/*
2817 	 * Write seektable
2818 	 */
2819 	if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2820 		unsigned i;
2821 
2822 		FLAC__format_seektable_sort(encoder->private_->seek_table);
2823 
2824 		FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2825 
2826 		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) {
2827 			if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2828 				encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2829 			return;
2830 		}
2831 
2832 		for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2833 			FLAC__uint64 xx;
2834 			unsigned x;
2835 			xx = encoder->private_->seek_table->points[i].sample_number;
2836 			b[7] = (FLAC__byte)xx; xx >>= 8;
2837 			b[6] = (FLAC__byte)xx; xx >>= 8;
2838 			b[5] = (FLAC__byte)xx; xx >>= 8;
2839 			b[4] = (FLAC__byte)xx; xx >>= 8;
2840 			b[3] = (FLAC__byte)xx; xx >>= 8;
2841 			b[2] = (FLAC__byte)xx; xx >>= 8;
2842 			b[1] = (FLAC__byte)xx; xx >>= 8;
2843 			b[0] = (FLAC__byte)xx; xx >>= 8;
2844 			xx = encoder->private_->seek_table->points[i].stream_offset;
2845 			b[15] = (FLAC__byte)xx; xx >>= 8;
2846 			b[14] = (FLAC__byte)xx; xx >>= 8;
2847 			b[13] = (FLAC__byte)xx; xx >>= 8;
2848 			b[12] = (FLAC__byte)xx; xx >>= 8;
2849 			b[11] = (FLAC__byte)xx; xx >>= 8;
2850 			b[10] = (FLAC__byte)xx; xx >>= 8;
2851 			b[9] = (FLAC__byte)xx; xx >>= 8;
2852 			b[8] = (FLAC__byte)xx; xx >>= 8;
2853 			x = encoder->private_->seek_table->points[i].frame_samples;
2854 			b[17] = (FLAC__byte)x; x >>= 8;
2855 			b[16] = (FLAC__byte)x; x >>= 8;
2856 			if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2857 				encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2858 				return;
2859 			}
2860 		}
2861 	}
2862 }
2863 
2864 #if FLAC__HAS_OGG
2865 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
update_ogg_metadata_(FLAC__StreamEncoder * encoder)2866 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2867 {
2868 	/* the # of bytes in the 1st packet that precede the STREAMINFO */
2869 	static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2870 		FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2871 		FLAC__OGG_MAPPING_MAGIC_LENGTH +
2872 		FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2873 		FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2874 		FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2875 		FLAC__STREAM_SYNC_LENGTH
2876 	;
2877 	FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2878 	const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2879 	const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2880 	const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2881 	const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2882 	ogg_page page;
2883 
2884 	FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2885 	FLAC__ASSERT(0 != encoder->private_->seek_callback);
2886 
2887 	/* Pre-check that client supports seeking, since we don't want the
2888 	 * ogg_helper code to ever have to deal with this condition.
2889 	 */
2890 	if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2891 		return;
2892 
2893 	/* All this is based on intimate knowledge of the stream header
2894 	 * layout, but a change to the header format that would break this
2895 	 * would also break all streams encoded in the previous format.
2896 	 */
2897 
2898 	/**
2899 	 ** Write STREAMINFO stats
2900 	 **/
2901 	simple_ogg_page__init(&page);
2902 	if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2903 		simple_ogg_page__clear(&page);
2904 		return; /* state already set */
2905 	}
2906 
2907 	/*
2908 	 * Write MD5 signature
2909 	 */
2910 	{
2911 		const unsigned md5_offset =
2912 			FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2913 			FLAC__STREAM_METADATA_HEADER_LENGTH +
2914 			(
2915 				FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2916 				FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2917 				FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2918 				FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2919 				FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2920 				FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2921 				FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2922 				FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2923 			) / 8;
2924 
2925 		if(md5_offset + 16 > (unsigned)page.body_len) {
2926 			encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2927 			simple_ogg_page__clear(&page);
2928 			return;
2929 		}
2930 		memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2931 	}
2932 
2933 	/*
2934 	 * Write total samples
2935 	 */
2936 	{
2937 		const unsigned total_samples_byte_offset =
2938 			FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2939 			FLAC__STREAM_METADATA_HEADER_LENGTH +
2940 			(
2941 				FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2942 				FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2943 				FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2944 				FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2945 				FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2946 				FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2947 				FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2948 				- 4
2949 			) / 8;
2950 
2951 		if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2952 			encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2953 			simple_ogg_page__clear(&page);
2954 			return;
2955 		}
2956 		b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2957 		b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2958 		b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2959 		b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2960 		b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2961 		b[4] = (FLAC__byte)(samples & 0xFF);
2962 		memcpy(page.body + total_samples_byte_offset, b, 5);
2963 	}
2964 
2965 	/*
2966 	 * Write min/max framesize
2967 	 */
2968 	{
2969 		const unsigned min_framesize_offset =
2970 			FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2971 			FLAC__STREAM_METADATA_HEADER_LENGTH +
2972 			(
2973 				FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2974 				FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2975 			) / 8;
2976 
2977 		if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2978 			encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2979 			simple_ogg_page__clear(&page);
2980 			return;
2981 		}
2982 		b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2983 		b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2984 		b[2] = (FLAC__byte)(min_framesize & 0xFF);
2985 		b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2986 		b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2987 		b[5] = (FLAC__byte)(max_framesize & 0xFF);
2988 		memcpy(page.body + min_framesize_offset, b, 6);
2989 	}
2990 	if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2991 		simple_ogg_page__clear(&page);
2992 		return; /* state already set */
2993 	}
2994 	simple_ogg_page__clear(&page);
2995 
2996 	/*
2997 	 * Write seektable
2998 	 */
2999 	if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
3000 		unsigned i;
3001 		FLAC__byte *p;
3002 
3003 		FLAC__format_seektable_sort(encoder->private_->seek_table);
3004 
3005 		FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
3006 
3007 		simple_ogg_page__init(&page);
3008 		if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
3009 			simple_ogg_page__clear(&page);
3010 			return; /* state already set */
3011 		}
3012 
3013 		if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
3014 			encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
3015 			simple_ogg_page__clear(&page);
3016 			return;
3017 		}
3018 
3019 		for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
3020 			FLAC__uint64 xx;
3021 			unsigned x;
3022 			xx = encoder->private_->seek_table->points[i].sample_number;
3023 			b[7] = (FLAC__byte)xx; xx >>= 8;
3024 			b[6] = (FLAC__byte)xx; xx >>= 8;
3025 			b[5] = (FLAC__byte)xx; xx >>= 8;
3026 			b[4] = (FLAC__byte)xx; xx >>= 8;
3027 			b[3] = (FLAC__byte)xx; xx >>= 8;
3028 			b[2] = (FLAC__byte)xx; xx >>= 8;
3029 			b[1] = (FLAC__byte)xx; xx >>= 8;
3030 			b[0] = (FLAC__byte)xx; xx >>= 8;
3031 			xx = encoder->private_->seek_table->points[i].stream_offset;
3032 			b[15] = (FLAC__byte)xx; xx >>= 8;
3033 			b[14] = (FLAC__byte)xx; xx >>= 8;
3034 			b[13] = (FLAC__byte)xx; xx >>= 8;
3035 			b[12] = (FLAC__byte)xx; xx >>= 8;
3036 			b[11] = (FLAC__byte)xx; xx >>= 8;
3037 			b[10] = (FLAC__byte)xx; xx >>= 8;
3038 			b[9] = (FLAC__byte)xx; xx >>= 8;
3039 			b[8] = (FLAC__byte)xx; xx >>= 8;
3040 			x = encoder->private_->seek_table->points[i].frame_samples;
3041 			b[17] = (FLAC__byte)x; x >>= 8;
3042 			b[16] = (FLAC__byte)x; x >>= 8;
3043 			memcpy(p, b, 18);
3044 		}
3045 
3046 		if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
3047 			simple_ogg_page__clear(&page);
3048 			return; /* state already set */
3049 		}
3050 		simple_ogg_page__clear(&page);
3051 	}
3052 }
3053 #endif
3054 
process_frame_(FLAC__StreamEncoder * encoder,FLAC__bool is_fractional_block,FLAC__bool is_last_block)3055 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
3056 {
3057 	FLAC__uint16 crc;
3058 	FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
3059 
3060 	/*
3061 	 * Accumulate raw signal to the MD5 signature
3062 	 */
3063 	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)) {
3064 		encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3065 		return false;
3066 	}
3067 
3068 	/*
3069 	 * Process the frame header and subframes into the frame bitbuffer
3070 	 */
3071 	if(!process_subframes_(encoder, is_fractional_block)) {
3072 		/* the above function sets the state for us in case of an error */
3073 		return false;
3074 	}
3075 
3076 	/*
3077 	 * Zero-pad the frame to a byte_boundary
3078 	 */
3079 	if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
3080 		encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3081 		return false;
3082 	}
3083 
3084 	/*
3085 	 * CRC-16 the whole thing
3086 	 */
3087 	FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
3088 	if(
3089 		!FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
3090 		!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
3091 	) {
3092 		encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3093 		return false;
3094 	}
3095 
3096 	/*
3097 	 * Write it
3098 	 */
3099 	if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
3100 		/* the above function sets the state for us in case of an error */
3101 		return false;
3102 	}
3103 
3104 	/*
3105 	 * Get ready for the next frame
3106 	 */
3107 	encoder->private_->current_sample_number = 0;
3108 	encoder->private_->current_frame_number++;
3109 	encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
3110 
3111 	return true;
3112 }
3113 
process_subframes_(FLAC__StreamEncoder * encoder,FLAC__bool is_fractional_block)3114 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
3115 {
3116 	FLAC__FrameHeader frame_header;
3117 	unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
3118 	FLAC__bool do_independent, do_mid_side;
3119 
3120 	/*
3121 	 * Calculate the min,max Rice partition orders
3122 	 */
3123 	if(is_fractional_block) {
3124 		max_partition_order = 0;
3125 	}
3126 	else {
3127 		max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
3128 		max_partition_order = flac_min(max_partition_order, encoder->protected_->max_residual_partition_order);
3129 	}
3130 	min_partition_order = flac_min(min_partition_order, max_partition_order);
3131 
3132 	/*
3133 	 * Setup the frame
3134 	 */
3135 	frame_header.blocksize = encoder->protected_->blocksize;
3136 	frame_header.sample_rate = encoder->protected_->sample_rate;
3137 	frame_header.channels = encoder->protected_->channels;
3138 	frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
3139 	frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
3140 	frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
3141 	frame_header.number.frame_number = encoder->private_->current_frame_number;
3142 
3143 	/*
3144 	 * Figure out what channel assignments to try
3145 	 */
3146 	if(encoder->protected_->do_mid_side_stereo) {
3147 		if(encoder->protected_->loose_mid_side_stereo) {
3148 			if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
3149 				do_independent = true;
3150 				do_mid_side = true;
3151 			}
3152 			else {
3153 				do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
3154 				do_mid_side = !do_independent;
3155 			}
3156 		}
3157 		else {
3158 			do_independent = true;
3159 			do_mid_side = true;
3160 		}
3161 	}
3162 	else {
3163 		do_independent = true;
3164 		do_mid_side = false;
3165 	}
3166 
3167 	FLAC__ASSERT(do_independent || do_mid_side);
3168 
3169 	/*
3170 	 * Check for wasted bits; set effective bps for each subframe
3171 	 */
3172 	if(do_independent) {
3173 		for(channel = 0; channel < encoder->protected_->channels; channel++) {
3174 			const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
3175 			encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
3176 			encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
3177 		}
3178 	}
3179 	if(do_mid_side) {
3180 		FLAC__ASSERT(encoder->protected_->channels == 2);
3181 		for(channel = 0; channel < 2; channel++) {
3182 			const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
3183 			encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
3184 			encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
3185 		}
3186 	}
3187 
3188 	/*
3189 	 * First do a normal encoding pass of each independent channel
3190 	 */
3191 	if(do_independent) {
3192 		for(channel = 0; channel < encoder->protected_->channels; channel++) {
3193 			if(!
3194 				process_subframe_(
3195 					encoder,
3196 					min_partition_order,
3197 					max_partition_order,
3198 					&frame_header,
3199 					encoder->private_->subframe_bps[channel],
3200 					encoder->private_->integer_signal[channel],
3201 					encoder->private_->subframe_workspace_ptr[channel],
3202 					encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3203 					encoder->private_->residual_workspace[channel],
3204 					encoder->private_->best_subframe+channel,
3205 					encoder->private_->best_subframe_bits+channel
3206 				)
3207 			)
3208 				return false;
3209 		}
3210 	}
3211 
3212 	/*
3213 	 * Now do mid and side channels if requested
3214 	 */
3215 	if(do_mid_side) {
3216 		FLAC__ASSERT(encoder->protected_->channels == 2);
3217 
3218 		for(channel = 0; channel < 2; channel++) {
3219 			if(!
3220 				process_subframe_(
3221 					encoder,
3222 					min_partition_order,
3223 					max_partition_order,
3224 					&frame_header,
3225 					encoder->private_->subframe_bps_mid_side[channel],
3226 					encoder->private_->integer_signal_mid_side[channel],
3227 					encoder->private_->subframe_workspace_ptr_mid_side[channel],
3228 					encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3229 					encoder->private_->residual_workspace_mid_side[channel],
3230 					encoder->private_->best_subframe_mid_side+channel,
3231 					encoder->private_->best_subframe_bits_mid_side+channel
3232 				)
3233 			)
3234 				return false;
3235 		}
3236 	}
3237 
3238 	/*
3239 	 * Compose the frame bitbuffer
3240 	 */
3241 	if(do_mid_side) {
3242 		unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3243 		FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3244 		FLAC__ChannelAssignment channel_assignment;
3245 
3246 		FLAC__ASSERT(encoder->protected_->channels == 2);
3247 
3248 		if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3249 			channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3250 		}
3251 		else {
3252 			unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3253 			unsigned min_bits;
3254 			int ca;
3255 
3256 			FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3257 			FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE   == 1);
3258 			FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE  == 2);
3259 			FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE    == 3);
3260 			FLAC__ASSERT(do_independent && do_mid_side);
3261 
3262 			/* We have to figure out which channel assignent results in the smallest frame */
3263 			bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits         [1];
3264 			bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE  ] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits_mid_side[1];
3265 			bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits         [1] + encoder->private_->best_subframe_bits_mid_side[1];
3266 			bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE   ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3267 
3268 			channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3269 			min_bits = bits[channel_assignment];
3270 			for(ca = 1; ca <= 3; ca++) {
3271 				if(bits[ca] < min_bits) {
3272 					min_bits = bits[ca];
3273 					channel_assignment = (FLAC__ChannelAssignment)ca;
3274 				}
3275 			}
3276 		}
3277 
3278 		frame_header.channel_assignment = channel_assignment;
3279 
3280 		if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3281 			encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3282 			return false;
3283 		}
3284 
3285 		switch(channel_assignment) {
3286 			case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3287 				left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3288 				right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
3289 				break;
3290 			case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3291 				left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3292 				right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3293 				break;
3294 			case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3295 				left_subframe  = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3296 				right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
3297 				break;
3298 			case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3299 				left_subframe  = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3300 				right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3301 				break;
3302 			default:
3303 				FLAC__ASSERT(0);
3304 		}
3305 
3306 		switch(channel_assignment) {
3307 			case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3308 				left_bps  = encoder->private_->subframe_bps         [0];
3309 				right_bps = encoder->private_->subframe_bps         [1];
3310 				break;
3311 			case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3312 				left_bps  = encoder->private_->subframe_bps         [0];
3313 				right_bps = encoder->private_->subframe_bps_mid_side[1];
3314 				break;
3315 			case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3316 				left_bps  = encoder->private_->subframe_bps_mid_side[1];
3317 				right_bps = encoder->private_->subframe_bps         [1];
3318 				break;
3319 			case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3320 				left_bps  = encoder->private_->subframe_bps_mid_side[0];
3321 				right_bps = encoder->private_->subframe_bps_mid_side[1];
3322 				break;
3323 			default:
3324 				FLAC__ASSERT(0);
3325 		}
3326 
3327 		/* note that encoder_add_subframe_ sets the state for us in case of an error */
3328 		if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3329 			return false;
3330 		if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3331 			return false;
3332 	}
3333 	else {
3334 		if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3335 			encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3336 			return false;
3337 		}
3338 
3339 		for(channel = 0; channel < encoder->protected_->channels; channel++) {
3340 			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)) {
3341 				/* the above function sets the state for us in case of an error */
3342 				return false;
3343 			}
3344 		}
3345 	}
3346 
3347 	if(encoder->protected_->loose_mid_side_stereo) {
3348 		encoder->private_->loose_mid_side_stereo_frame_count++;
3349 		if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3350 			encoder->private_->loose_mid_side_stereo_frame_count = 0;
3351 	}
3352 
3353 	encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3354 
3355 	return true;
3356 }
3357 
process_subframe_(FLAC__StreamEncoder * encoder,unsigned min_partition_order,unsigned max_partition_order,const FLAC__FrameHeader * frame_header,unsigned subframe_bps,const FLAC__int32 integer_signal[],FLAC__Subframe * subframe[2],FLAC__EntropyCodingMethod_PartitionedRiceContents * partitioned_rice_contents[2],FLAC__int32 * residual[2],unsigned * best_subframe,unsigned * best_bits)3358 FLAC__bool process_subframe_(
3359 	FLAC__StreamEncoder *encoder,
3360 	unsigned min_partition_order,
3361 	unsigned max_partition_order,
3362 	const FLAC__FrameHeader *frame_header,
3363 	unsigned subframe_bps,
3364 	const FLAC__int32 integer_signal[],
3365 	FLAC__Subframe *subframe[2],
3366 	FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3367 	FLAC__int32 *residual[2],
3368 	unsigned *best_subframe,
3369 	unsigned *best_bits
3370 )
3371 {
3372 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3373 	FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3374 #else
3375 	FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3376 #endif
3377 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3378 	FLAC__double lpc_residual_bits_per_sample;
3379 	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 */
3380 	FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3381 	unsigned min_lpc_order, max_lpc_order, lpc_order;
3382 	unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3383 #endif
3384 	unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3385 	unsigned rice_parameter;
3386 	unsigned _candidate_bits, _best_bits;
3387 	unsigned _best_subframe;
3388 	/* only use RICE2 partitions if stream bps > 16 */
3389 	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;
3390 
3391 	FLAC__ASSERT(frame_header->blocksize > 0);
3392 
3393 	/* verbatim subframe is the baseline against which we measure other compressed subframes */
3394 	_best_subframe = 0;
3395 	if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3396 		_best_bits = UINT_MAX;
3397 	else
3398 		_best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3399 
3400 	if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3401 		unsigned signal_is_constant = false;
3402 		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);
3403 		/* check for constant subframe */
3404 		if(
3405 			!encoder->private_->disable_constant_subframes &&
3406 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3407 			fixed_residual_bits_per_sample[1] == 0.0
3408 #else
3409 			fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3410 #endif
3411 		) {
3412 			/* the above means it's possible all samples are the same value; now double-check it: */
3413 			unsigned i;
3414 			signal_is_constant = true;
3415 			for(i = 1; i < frame_header->blocksize; i++) {
3416 				if(integer_signal[0] != integer_signal[i]) {
3417 					signal_is_constant = false;
3418 					break;
3419 				}
3420 			}
3421 		}
3422 		if(signal_is_constant) {
3423 			_candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3424 			if(_candidate_bits < _best_bits) {
3425 				_best_subframe = !_best_subframe;
3426 				_best_bits = _candidate_bits;
3427 			}
3428 		}
3429 		else {
3430 			if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3431 				/* encode fixed */
3432 				if(encoder->protected_->do_exhaustive_model_search) {
3433 					min_fixed_order = 0;
3434 					max_fixed_order = FLAC__MAX_FIXED_ORDER;
3435 				}
3436 				else {
3437 					min_fixed_order = max_fixed_order = guess_fixed_order;
3438 				}
3439 				if(max_fixed_order >= frame_header->blocksize)
3440 					max_fixed_order = frame_header->blocksize - 1;
3441 				for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3442 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3443 					if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3444 						continue; /* don't even try */
3445 					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 */
3446 #else
3447 					if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3448 						continue; /* don't even try */
3449 					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 */
3450 #endif
3451 					rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3452 					if(rice_parameter >= rice_parameter_limit) {
3453 #ifdef DEBUG_VERBOSE
3454 						fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
3455 #endif
3456 						rice_parameter = rice_parameter_limit - 1;
3457 					}
3458 					_candidate_bits =
3459 						evaluate_fixed_subframe_(
3460 							encoder,
3461 							integer_signal,
3462 							residual[!_best_subframe],
3463 							encoder->private_->abs_residual_partition_sums,
3464 							encoder->private_->raw_bits_per_partition,
3465 							frame_header->blocksize,
3466 							subframe_bps,
3467 							fixed_order,
3468 							rice_parameter,
3469 							rice_parameter_limit,
3470 							min_partition_order,
3471 							max_partition_order,
3472 							encoder->protected_->do_escape_coding,
3473 							encoder->protected_->rice_parameter_search_dist,
3474 							subframe[!_best_subframe],
3475 							partitioned_rice_contents[!_best_subframe]
3476 						);
3477 					if(_candidate_bits < _best_bits) {
3478 						_best_subframe = !_best_subframe;
3479 						_best_bits = _candidate_bits;
3480 					}
3481 				}
3482 			}
3483 
3484 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3485 			/* encode lpc */
3486 			if(encoder->protected_->max_lpc_order > 0) {
3487 				if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3488 					max_lpc_order = frame_header->blocksize-1;
3489 				else
3490 					max_lpc_order = encoder->protected_->max_lpc_order;
3491 				if(max_lpc_order > 0) {
3492 					unsigned a;
3493 					for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3494 						FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3495 						encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3496 						/* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3497 						if(autoc[0] != 0.0) {
3498 							FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3499 							if(encoder->protected_->do_exhaustive_model_search) {
3500 								min_lpc_order = 1;
3501 							}
3502 							else {
3503 								const unsigned guess_lpc_order =
3504 									FLAC__lpc_compute_best_order(
3505 										lpc_error,
3506 										max_lpc_order,
3507 										frame_header->blocksize,
3508 										subframe_bps + (
3509 											encoder->protected_->do_qlp_coeff_prec_search?
3510 												FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
3511 												encoder->protected_->qlp_coeff_precision
3512 										)
3513 									);
3514 								min_lpc_order = max_lpc_order = guess_lpc_order;
3515 							}
3516 							if(max_lpc_order >= frame_header->blocksize)
3517 								max_lpc_order = frame_header->blocksize - 1;
3518 							for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
3519 								lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
3520 								if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
3521 									continue; /* don't even try */
3522 								rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
3523 								rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3524 								if(rice_parameter >= rice_parameter_limit) {
3525 #ifdef DEBUG_VERBOSE
3526 									fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
3527 #endif
3528 									rice_parameter = rice_parameter_limit - 1;
3529 								}
3530 								if(encoder->protected_->do_qlp_coeff_prec_search) {
3531 									min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
3532 									/* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3533 									if(subframe_bps <= 16) {
3534 										max_qlp_coeff_precision = flac_min(32 - subframe_bps - FLAC__bitmath_ilog2(lpc_order), FLAC__MAX_QLP_COEFF_PRECISION);
3535 										max_qlp_coeff_precision = flac_max(max_qlp_coeff_precision, min_qlp_coeff_precision);
3536 									}
3537 									else
3538 										max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
3539 								}
3540 								else {
3541 									min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
3542 								}
3543 								for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
3544 									_candidate_bits =
3545 										evaluate_lpc_subframe_(
3546 											encoder,
3547 											integer_signal,
3548 											residual[!_best_subframe],
3549 											encoder->private_->abs_residual_partition_sums,
3550 											encoder->private_->raw_bits_per_partition,
3551 											encoder->private_->lp_coeff[lpc_order-1],
3552 											frame_header->blocksize,
3553 											subframe_bps,
3554 											lpc_order,
3555 											qlp_coeff_precision,
3556 											rice_parameter,
3557 											rice_parameter_limit,
3558 											min_partition_order,
3559 											max_partition_order,
3560 											encoder->protected_->do_escape_coding,
3561 											encoder->protected_->rice_parameter_search_dist,
3562 											subframe[!_best_subframe],
3563 											partitioned_rice_contents[!_best_subframe]
3564 										);
3565 									if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
3566 										if(_candidate_bits < _best_bits) {
3567 											_best_subframe = !_best_subframe;
3568 											_best_bits = _candidate_bits;
3569 										}
3570 									}
3571 								}
3572 							}
3573 						}
3574 					}
3575 				}
3576 			}
3577 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3578 		}
3579 	}
3580 
3581 	/* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3582 	if(_best_bits == UINT_MAX) {
3583 		FLAC__ASSERT(_best_subframe == 0);
3584 		_best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3585 	}
3586 
3587 	*best_subframe = _best_subframe;
3588 	*best_bits = _best_bits;
3589 
3590 	return true;
3591 }
3592 
add_subframe_(FLAC__StreamEncoder * encoder,unsigned blocksize,unsigned subframe_bps,const FLAC__Subframe * subframe,FLAC__BitWriter * frame)3593 FLAC__bool add_subframe_(
3594 	FLAC__StreamEncoder *encoder,
3595 	unsigned blocksize,
3596 	unsigned subframe_bps,
3597 	const FLAC__Subframe *subframe,
3598 	FLAC__BitWriter *frame
3599 )
3600 {
3601 	switch(subframe->type) {
3602 		case FLAC__SUBFRAME_TYPE_CONSTANT:
3603 			if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3604 				encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3605 				return false;
3606 			}
3607 			break;
3608 		case FLAC__SUBFRAME_TYPE_FIXED:
3609 			if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3610 				encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3611 				return false;
3612 			}
3613 			break;
3614 		case FLAC__SUBFRAME_TYPE_LPC:
3615 			if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3616 				encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3617 				return false;
3618 			}
3619 			break;
3620 		case FLAC__SUBFRAME_TYPE_VERBATIM:
3621 			if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3622 				encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3623 				return false;
3624 			}
3625 			break;
3626 		default:
3627 			FLAC__ASSERT(0);
3628 	}
3629 
3630 	return true;
3631 }
3632 
3633 #define SPOTCHECK_ESTIMATE 0
3634 #if SPOTCHECK_ESTIMATE
spotcheck_subframe_estimate_(FLAC__StreamEncoder * encoder,unsigned blocksize,unsigned subframe_bps,const FLAC__Subframe * subframe,unsigned estimate)3635 static void spotcheck_subframe_estimate_(
3636 	FLAC__StreamEncoder *encoder,
3637 	unsigned blocksize,
3638 	unsigned subframe_bps,
3639 	const FLAC__Subframe *subframe,
3640 	unsigned estimate
3641 )
3642 {
3643 	FLAC__bool ret;
3644 	FLAC__BitWriter *frame = FLAC__bitwriter_new();
3645 	if(frame == 0) {
3646 		fprintf(stderr, "EST: can't allocate frame\n");
3647 		return;
3648 	}
3649 	if(!FLAC__bitwriter_init(frame)) {
3650 		fprintf(stderr, "EST: can't init frame\n");
3651 		return;
3652 	}
3653 	ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
3654 	FLAC__ASSERT(ret);
3655 	{
3656 		const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
3657 		if(estimate != actual)
3658 			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);
3659 	}
3660 	FLAC__bitwriter_delete(frame);
3661 }
3662 #endif
3663 
evaluate_constant_subframe_(FLAC__StreamEncoder * encoder,const FLAC__int32 signal,unsigned blocksize,unsigned subframe_bps,FLAC__Subframe * subframe)3664 unsigned evaluate_constant_subframe_(
3665 	FLAC__StreamEncoder *encoder,
3666 	const FLAC__int32 signal,
3667 	unsigned blocksize,
3668 	unsigned subframe_bps,
3669 	FLAC__Subframe *subframe
3670 )
3671 {
3672 	unsigned estimate;
3673 	subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3674 	subframe->data.constant.value = signal;
3675 
3676 	estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
3677 
3678 #if SPOTCHECK_ESTIMATE
3679 	spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3680 #else
3681 	(void)encoder, (void)blocksize;
3682 #endif
3683 
3684 	return estimate;
3685 }
3686 
evaluate_fixed_subframe_(FLAC__StreamEncoder * encoder,const FLAC__int32 signal[],FLAC__int32 residual[],FLAC__uint64 abs_residual_partition_sums[],unsigned raw_bits_per_partition[],unsigned blocksize,unsigned subframe_bps,unsigned order,unsigned rice_parameter,unsigned rice_parameter_limit,unsigned min_partition_order,unsigned max_partition_order,FLAC__bool do_escape_coding,unsigned rice_parameter_search_dist,FLAC__Subframe * subframe,FLAC__EntropyCodingMethod_PartitionedRiceContents * partitioned_rice_contents)3687 unsigned evaluate_fixed_subframe_(
3688 	FLAC__StreamEncoder *encoder,
3689 	const FLAC__int32 signal[],
3690 	FLAC__int32 residual[],
3691 	FLAC__uint64 abs_residual_partition_sums[],
3692 	unsigned raw_bits_per_partition[],
3693 	unsigned blocksize,
3694 	unsigned subframe_bps,
3695 	unsigned order,
3696 	unsigned rice_parameter,
3697 	unsigned rice_parameter_limit,
3698 	unsigned min_partition_order,
3699 	unsigned max_partition_order,
3700 	FLAC__bool do_escape_coding,
3701 	unsigned rice_parameter_search_dist,
3702 	FLAC__Subframe *subframe,
3703 	FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3704 )
3705 {
3706 	unsigned i, residual_bits, estimate;
3707 	const unsigned residual_samples = blocksize - order;
3708 
3709 	FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3710 
3711 	subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3712 
3713 	subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3714 	subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3715 	subframe->data.fixed.residual = residual;
3716 
3717 	residual_bits =
3718 		find_best_partition_order_(
3719 			encoder->private_,
3720 			residual,
3721 			abs_residual_partition_sums,
3722 			raw_bits_per_partition,
3723 			residual_samples,
3724 			order,
3725 			rice_parameter,
3726 			rice_parameter_limit,
3727 			min_partition_order,
3728 			max_partition_order,
3729 			subframe_bps,
3730 			do_escape_coding,
3731 			rice_parameter_search_dist,
3732 			&subframe->data.fixed.entropy_coding_method
3733 		);
3734 
3735 	subframe->data.fixed.order = order;
3736 	for(i = 0; i < order; i++)
3737 		subframe->data.fixed.warmup[i] = signal[i];
3738 
3739 	estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
3740 
3741 #if SPOTCHECK_ESTIMATE
3742 	spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3743 #endif
3744 
3745 	return estimate;
3746 }
3747 
3748 #ifndef FLAC__INTEGER_ONLY_LIBRARY
evaluate_lpc_subframe_(FLAC__StreamEncoder * encoder,const FLAC__int32 signal[],FLAC__int32 residual[],FLAC__uint64 abs_residual_partition_sums[],unsigned raw_bits_per_partition[],const FLAC__real lp_coeff[],unsigned blocksize,unsigned subframe_bps,unsigned order,unsigned qlp_coeff_precision,unsigned rice_parameter,unsigned rice_parameter_limit,unsigned min_partition_order,unsigned max_partition_order,FLAC__bool do_escape_coding,unsigned rice_parameter_search_dist,FLAC__Subframe * subframe,FLAC__EntropyCodingMethod_PartitionedRiceContents * partitioned_rice_contents)3749 unsigned evaluate_lpc_subframe_(
3750 	FLAC__StreamEncoder *encoder,
3751 	const FLAC__int32 signal[],
3752 	FLAC__int32 residual[],
3753 	FLAC__uint64 abs_residual_partition_sums[],
3754 	unsigned raw_bits_per_partition[],
3755 	const FLAC__real lp_coeff[],
3756 	unsigned blocksize,
3757 	unsigned subframe_bps,
3758 	unsigned order,
3759 	unsigned qlp_coeff_precision,
3760 	unsigned rice_parameter,
3761 	unsigned rice_parameter_limit,
3762 	unsigned min_partition_order,
3763 	unsigned max_partition_order,
3764 	FLAC__bool do_escape_coding,
3765 	unsigned rice_parameter_search_dist,
3766 	FLAC__Subframe *subframe,
3767 	FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3768 )
3769 {
3770 	FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER]; /* WATCHOUT: the size is important; some x86 intrinsic routines need more than lpc order elements */
3771 	unsigned i, residual_bits, estimate;
3772 	int quantization, ret;
3773 	const unsigned residual_samples = blocksize - order;
3774 
3775 	/* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3776 	if(subframe_bps <= 16) {
3777 		FLAC__ASSERT(order > 0);
3778 		FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3779 		qlp_coeff_precision = flac_min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3780 	}
3781 
3782 	ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3783 	if(ret != 0)
3784 		return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3785 
3786 	if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3787 		if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3788 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3789 		else
3790 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3791 	else
3792 		encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3793 
3794 	subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3795 
3796 	subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3797 	subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3798 	subframe->data.lpc.residual = residual;
3799 
3800 	residual_bits =
3801 		find_best_partition_order_(
3802 			encoder->private_,
3803 			residual,
3804 			abs_residual_partition_sums,
3805 			raw_bits_per_partition,
3806 			residual_samples,
3807 			order,
3808 			rice_parameter,
3809 			rice_parameter_limit,
3810 			min_partition_order,
3811 			max_partition_order,
3812 			subframe_bps,
3813 			do_escape_coding,
3814 			rice_parameter_search_dist,
3815 			&subframe->data.lpc.entropy_coding_method
3816 		);
3817 
3818 	subframe->data.lpc.order = order;
3819 	subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3820 	subframe->data.lpc.quantization_level = quantization;
3821 	memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3822 	for(i = 0; i < order; i++)
3823 		subframe->data.lpc.warmup[i] = signal[i];
3824 
3825 	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;
3826 
3827 #if SPOTCHECK_ESTIMATE
3828 	spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3829 #endif
3830 
3831 	return estimate;
3832 }
3833 #endif
3834 
evaluate_verbatim_subframe_(FLAC__StreamEncoder * encoder,const FLAC__int32 signal[],unsigned blocksize,unsigned subframe_bps,FLAC__Subframe * subframe)3835 unsigned evaluate_verbatim_subframe_(
3836 	FLAC__StreamEncoder *encoder,
3837 	const FLAC__int32 signal[],
3838 	unsigned blocksize,
3839 	unsigned subframe_bps,
3840 	FLAC__Subframe *subframe
3841 )
3842 {
3843 	unsigned estimate;
3844 
3845 	subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3846 
3847 	subframe->data.verbatim.data = signal;
3848 
3849 	estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
3850 
3851 #if SPOTCHECK_ESTIMATE
3852 	spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3853 #else
3854 	(void)encoder;
3855 #endif
3856 
3857 	return estimate;
3858 }
3859 
find_best_partition_order_(FLAC__StreamEncoderPrivate * private_,const FLAC__int32 residual[],FLAC__uint64 abs_residual_partition_sums[],unsigned raw_bits_per_partition[],unsigned residual_samples,unsigned predictor_order,unsigned rice_parameter,unsigned rice_parameter_limit,unsigned min_partition_order,unsigned max_partition_order,unsigned bps,FLAC__bool do_escape_coding,unsigned rice_parameter_search_dist,FLAC__EntropyCodingMethod * best_ecm)3860 unsigned find_best_partition_order_(
3861 	FLAC__StreamEncoderPrivate *private_,
3862 	const FLAC__int32 residual[],
3863 	FLAC__uint64 abs_residual_partition_sums[],
3864 	unsigned raw_bits_per_partition[],
3865 	unsigned residual_samples,
3866 	unsigned predictor_order,
3867 	unsigned rice_parameter,
3868 	unsigned rice_parameter_limit,
3869 	unsigned min_partition_order,
3870 	unsigned max_partition_order,
3871 	unsigned bps,
3872 	FLAC__bool do_escape_coding,
3873 	unsigned rice_parameter_search_dist,
3874 	FLAC__EntropyCodingMethod *best_ecm
3875 )
3876 {
3877 	unsigned residual_bits, best_residual_bits = 0;
3878 	unsigned best_parameters_index = 0;
3879 	unsigned best_partition_order = 0;
3880 	const unsigned blocksize = residual_samples + predictor_order;
3881 
3882 	max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3883 	min_partition_order = flac_min(min_partition_order, max_partition_order);
3884 
3885 	private_->local_precompute_partition_info_sums(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
3886 
3887 	if(do_escape_coding)
3888 		precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3889 
3890 	{
3891 		int partition_order;
3892 		unsigned sum;
3893 
3894 		for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3895 			if(!
3896 				set_partitioned_rice_(
3897 #ifdef EXACT_RICE_BITS_CALCULATION
3898 					residual,
3899 #endif
3900 					abs_residual_partition_sums+sum,
3901 					raw_bits_per_partition+sum,
3902 					residual_samples,
3903 					predictor_order,
3904 					rice_parameter,
3905 					rice_parameter_limit,
3906 					rice_parameter_search_dist,
3907 					(unsigned)partition_order,
3908 					do_escape_coding,
3909 					&private_->partitioned_rice_contents_extra[!best_parameters_index],
3910 					&residual_bits
3911 				)
3912 			)
3913 			{
3914 				FLAC__ASSERT(best_residual_bits != 0);
3915 				break;
3916 			}
3917 			sum += 1u << partition_order;
3918 			if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3919 				best_residual_bits = residual_bits;
3920 				best_parameters_index = !best_parameters_index;
3921 				best_partition_order = partition_order;
3922 			}
3923 		}
3924 	}
3925 
3926 	best_ecm->data.partitioned_rice.order = best_partition_order;
3927 
3928 	{
3929 		/*
3930 		 * We are allowed to de-const the pointer based on our special
3931 		 * knowledge; it is const to the outside world.
3932 		 */
3933 		FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
3934 		unsigned partition;
3935 
3936 		/* save best parameters and raw_bits */
3937 		FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, flac_max(6u, best_partition_order));
3938 		memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
3939 		if(do_escape_coding)
3940 			memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
3941 		/*
3942 		 * Now need to check if the type should be changed to
3943 		 * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
3944 		 * size of the rice parameters.
3945 		 */
3946 		for(partition = 0; partition < (1u<<best_partition_order); partition++) {
3947 			if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3948 				best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
3949 				break;
3950 			}
3951 		}
3952 	}
3953 
3954 	return best_residual_bits;
3955 }
3956 
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)3957 void precompute_partition_info_sums_(
3958 	const FLAC__int32 residual[],
3959 	FLAC__uint64 abs_residual_partition_sums[],
3960 	unsigned residual_samples,
3961 	unsigned predictor_order,
3962 	unsigned min_partition_order,
3963 	unsigned max_partition_order,
3964 	unsigned bps
3965 )
3966 {
3967 	const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
3968 	unsigned partitions = 1u << max_partition_order;
3969 
3970 	FLAC__ASSERT(default_partition_samples > predictor_order);
3971 
3972 	/* first do max_partition_order */
3973 	{
3974 		unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
3975 		/* WATCHOUT: "+ bps + FLAC__MAX_EXTRA_RESIDUAL_BPS" is the maximum
3976 		 * assumed size of the average residual magnitude */
3977 		if(FLAC__bitmath_ilog2(default_partition_samples) + bps + FLAC__MAX_EXTRA_RESIDUAL_BPS < 32) {
3978 			FLAC__uint32 abs_residual_partition_sum;
3979 
3980 			for(partition = residual_sample = 0; partition < partitions; partition++) {
3981 				end += default_partition_samples;
3982 				abs_residual_partition_sum = 0;
3983 				for( ; residual_sample < end; residual_sample++)
3984 					abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3985 				abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3986 			}
3987 		}
3988 		else { /* have to pessimistically use 64 bits for accumulator */
3989 			FLAC__uint64 abs_residual_partition_sum;
3990 
3991 			for(partition = residual_sample = 0; partition < partitions; partition++) {
3992 				end += default_partition_samples;
3993 				abs_residual_partition_sum = 0;
3994 				for( ; residual_sample < end; residual_sample++)
3995 					abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3996 				abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3997 			}
3998 		}
3999 	}
4000 
4001 	/* now merge partitions for lower orders */
4002 	{
4003 		unsigned from_partition = 0, to_partition = partitions;
4004 		int partition_order;
4005 		for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
4006 			unsigned i;
4007 			partitions >>= 1;
4008 			for(i = 0; i < partitions; i++) {
4009 				abs_residual_partition_sums[to_partition++] =
4010 					abs_residual_partition_sums[from_partition  ] +
4011 					abs_residual_partition_sums[from_partition+1];
4012 				from_partition += 2;
4013 			}
4014 		}
4015 	}
4016 }
4017 
precompute_partition_info_escapes_(const FLAC__int32 residual[],unsigned raw_bits_per_partition[],unsigned residual_samples,unsigned predictor_order,unsigned min_partition_order,unsigned max_partition_order)4018 void precompute_partition_info_escapes_(
4019 	const FLAC__int32 residual[],
4020 	unsigned raw_bits_per_partition[],
4021 	unsigned residual_samples,
4022 	unsigned predictor_order,
4023 	unsigned min_partition_order,
4024 	unsigned max_partition_order
4025 )
4026 {
4027 	int partition_order;
4028 	unsigned from_partition, to_partition = 0;
4029 	const unsigned blocksize = residual_samples + predictor_order;
4030 
4031 	/* first do max_partition_order */
4032 	for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
4033 		FLAC__int32 r;
4034 		FLAC__uint32 rmax;
4035 		unsigned partition, partition_sample, partition_samples, residual_sample;
4036 		const unsigned partitions = 1u << partition_order;
4037 		const unsigned default_partition_samples = blocksize >> partition_order;
4038 
4039 		FLAC__ASSERT(default_partition_samples > predictor_order);
4040 
4041 		for(partition = residual_sample = 0; partition < partitions; partition++) {
4042 			partition_samples = default_partition_samples;
4043 			if(partition == 0)
4044 				partition_samples -= predictor_order;
4045 			rmax = 0;
4046 			for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
4047 				r = residual[residual_sample++];
4048 				/* OPT: maybe faster: rmax |= r ^ (r>>31) */
4049 				if(r < 0)
4050 					rmax |= ~r;
4051 				else
4052 					rmax |= r;
4053 			}
4054 			/* now we know all residual values are in the range [-rmax-1,rmax] */
4055 			raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
4056 		}
4057 		to_partition = partitions;
4058 		break; /*@@@ yuck, should remove the 'for' loop instead */
4059 	}
4060 
4061 	/* now merge partitions for lower orders */
4062 	for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
4063 		unsigned m;
4064 		unsigned i;
4065 		const unsigned partitions = 1u << partition_order;
4066 		for(i = 0; i < partitions; i++) {
4067 			m = raw_bits_per_partition[from_partition];
4068 			from_partition++;
4069 			raw_bits_per_partition[to_partition] = flac_max(m, raw_bits_per_partition[from_partition]);
4070 			from_partition++;
4071 			to_partition++;
4072 		}
4073 	}
4074 }
4075 
4076 #ifdef EXACT_RICE_BITS_CALCULATION
count_rice_bits_in_partition_(const unsigned rice_parameter,const unsigned partition_samples,const FLAC__int32 * residual)4077 static inline unsigned count_rice_bits_in_partition_(
4078 	const unsigned rice_parameter,
4079 	const unsigned partition_samples,
4080 	const FLAC__int32 *residual
4081 )
4082 {
4083 	unsigned i, partition_bits =
4084 		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 */
4085 		(1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
4086 	;
4087 	for(i = 0; i < partition_samples; i++)
4088 		partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
4089 	return partition_bits;
4090 }
4091 #else
count_rice_bits_in_partition_(const unsigned rice_parameter,const unsigned partition_samples,const FLAC__uint64 abs_residual_partition_sum)4092 static inline unsigned count_rice_bits_in_partition_(
4093 	const unsigned rice_parameter,
4094 	const unsigned partition_samples,
4095 	const FLAC__uint64 abs_residual_partition_sum
4096 )
4097 {
4098 	return
4099 		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 */
4100 		(1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
4101 		(
4102 			rice_parameter?
4103 				(unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
4104 				: (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
4105 		)
4106 		- (partition_samples >> 1)
4107 		/* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
4108 		 * The actual number of bits used is closer to the sum(for all i in the partition) of  abs(residual[i])>>(rice_parameter-1)
4109 		 * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
4110 		 * So the subtraction term tries to guess how many extra bits were contributed.
4111 		 * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
4112 		 */
4113 	;
4114 }
4115 #endif
4116 
set_partitioned_rice_(const FLAC__int32 residual[],const FLAC__uint64 abs_residual_partition_sums[],const unsigned raw_bits_per_partition[],const unsigned residual_samples,const unsigned predictor_order,const unsigned suggested_rice_parameter,const unsigned rice_parameter_limit,const unsigned rice_parameter_search_dist,const unsigned partition_order,const FLAC__bool search_for_escapes,FLAC__EntropyCodingMethod_PartitionedRiceContents * partitioned_rice_contents,unsigned * bits)4117 FLAC__bool set_partitioned_rice_(
4118 #ifdef EXACT_RICE_BITS_CALCULATION
4119 	const FLAC__int32 residual[],
4120 #endif
4121 	const FLAC__uint64 abs_residual_partition_sums[],
4122 	const unsigned raw_bits_per_partition[],
4123 	const unsigned residual_samples,
4124 	const unsigned predictor_order,
4125 	const unsigned suggested_rice_parameter,
4126 	const unsigned rice_parameter_limit,
4127 	const unsigned rice_parameter_search_dist,
4128 	const unsigned partition_order,
4129 	const FLAC__bool search_for_escapes,
4130 	FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
4131 	unsigned *bits
4132 )
4133 {
4134 	unsigned rice_parameter, partition_bits;
4135 	unsigned best_partition_bits, best_rice_parameter = 0;
4136 	unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
4137 	unsigned *parameters, *raw_bits;
4138 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4139 	unsigned min_rice_parameter, max_rice_parameter;
4140 #else
4141 	(void)rice_parameter_search_dist;
4142 #endif
4143 
4144 	FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
4145 	FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
4146 
4147 	FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, flac_max(6u, partition_order));
4148 	parameters = partitioned_rice_contents->parameters;
4149 	raw_bits = partitioned_rice_contents->raw_bits;
4150 
4151 	if(partition_order == 0) {
4152 		best_partition_bits = (unsigned)(-1);
4153 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4154 		if(rice_parameter_search_dist) {
4155 			if(suggested_rice_parameter < rice_parameter_search_dist)
4156 				min_rice_parameter = 0;
4157 			else
4158 				min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
4159 			max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
4160 			if(max_rice_parameter >= rice_parameter_limit) {
4161 #ifdef DEBUG_VERBOSE
4162 				fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
4163 #endif
4164 				max_rice_parameter = rice_parameter_limit - 1;
4165 			}
4166 		}
4167 		else
4168 			min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
4169 
4170 		for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4171 #else
4172 			rice_parameter = suggested_rice_parameter;
4173 #endif
4174 #ifdef EXACT_RICE_BITS_CALCULATION
4175 			partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
4176 #else
4177 			partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
4178 #endif
4179 			if(partition_bits < best_partition_bits) {
4180 				best_rice_parameter = rice_parameter;
4181 				best_partition_bits = partition_bits;
4182 			}
4183 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4184 		}
4185 #endif
4186 		if(search_for_escapes) {
4187 			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;
4188 			if(partition_bits <= best_partition_bits) {
4189 				raw_bits[0] = raw_bits_per_partition[0];
4190 				best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4191 				best_partition_bits = partition_bits;
4192 			}
4193 			else
4194 				raw_bits[0] = 0;
4195 		}
4196 		parameters[0] = best_rice_parameter;
4197 		bits_ += best_partition_bits;
4198 	}
4199 	else {
4200 		unsigned partition, residual_sample;
4201 		unsigned partition_samples;
4202 		FLAC__uint64 mean, k;
4203 		const unsigned partitions = 1u << partition_order;
4204 		for(partition = residual_sample = 0; partition < partitions; partition++) {
4205 			partition_samples = (residual_samples+predictor_order) >> partition_order;
4206 			if(partition == 0) {
4207 				if(partition_samples <= predictor_order)
4208 					return false;
4209 				else
4210 					partition_samples -= predictor_order;
4211 			}
4212 			mean = abs_residual_partition_sums[partition];
4213 			/* we are basically calculating the size in bits of the
4214 			 * average residual magnitude in the partition:
4215 			 *   rice_parameter = floor(log2(mean/partition_samples))
4216 			 * 'mean' is not a good name for the variable, it is
4217 			 * actually the sum of magnitudes of all residual values
4218 			 * in the partition, so the actual mean is
4219 			 * mean/partition_samples
4220 			 */
4221 #if 0 /* old simple code */
4222 			for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
4223 				;
4224 #else
4225 #if defined FLAC__CPU_X86_64 /* and other 64-bit arch, too */
4226 			if(mean <= 0x80000000/512) { /* 512: more or less optimal for both 16- and 24-bit input */
4227 #else
4228 			if(mean <= 0x80000000/8) { /* 32-bit arch: use 32-bit math if possible */
4229 #endif
4230 				FLAC__uint32 k2, mean2 = (FLAC__uint32) mean;
4231 				rice_parameter = 0; k2 = partition_samples;
4232 				while(k2*8 < mean2) { /* requires: mean <= (2^31)/8 */
4233 					rice_parameter += 4; k2 <<= 4; /* tuned for 16-bit input */
4234 				}
4235 				while(k2 < mean2) { /* requires: mean <= 2^31 */
4236 					rice_parameter++; k2 <<= 1;
4237 				}
4238 			}
4239 			else {
4240 				rice_parameter = 0; k = partition_samples;
4241 				if(mean <= FLAC__U64L(0x8000000000000000)/128) /* usually mean is _much_ smaller than this value */
4242 					while(k*128 < mean) { /* requires: mean <= (2^63)/128 */
4243 						rice_parameter += 8; k <<= 8; /* tuned for 24-bit input */
4244 					}
4245 				while(k < mean) { /* requires: mean <= 2^63 */
4246 					rice_parameter++; k <<= 1;
4247 				}
4248 			}
4249 #endif
4250 			if(rice_parameter >= rice_parameter_limit) {
4251 #ifdef DEBUG_VERBOSE
4252 				fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
4253 #endif
4254 				rice_parameter = rice_parameter_limit - 1;
4255 			}
4256 
4257 			best_partition_bits = (unsigned)(-1);
4258 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4259 			if(rice_parameter_search_dist) {
4260 				if(rice_parameter < rice_parameter_search_dist)
4261 					min_rice_parameter = 0;
4262 				else
4263 					min_rice_parameter = rice_parameter - rice_parameter_search_dist;
4264 				max_rice_parameter = rice_parameter + rice_parameter_search_dist;
4265 				if(max_rice_parameter >= rice_parameter_limit) {
4266 #ifdef DEBUG_VERBOSE
4267 					fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
4268 #endif
4269 					max_rice_parameter = rice_parameter_limit - 1;
4270 				}
4271 			}
4272 			else
4273 				min_rice_parameter = max_rice_parameter = rice_parameter;
4274 
4275 			for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4276 #endif
4277 #ifdef EXACT_RICE_BITS_CALCULATION
4278 				partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
4279 #else
4280 				partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
4281 #endif
4282 				if(partition_bits < best_partition_bits) {
4283 					best_rice_parameter = rice_parameter;
4284 					best_partition_bits = partition_bits;
4285 				}
4286 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4287 			}
4288 #endif
4289 			if(search_for_escapes) {
4290 				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;
4291 				if(partition_bits <= best_partition_bits) {
4292 					raw_bits[partition] = raw_bits_per_partition[partition];
4293 					best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4294 					best_partition_bits = partition_bits;
4295 				}
4296 				else
4297 					raw_bits[partition] = 0;
4298 			}
4299 			parameters[partition] = best_rice_parameter;
4300 			bits_ += best_partition_bits;
4301 			residual_sample += partition_samples;
4302 		}
4303 	}
4304 
4305 	*bits = bits_;
4306 	return true;
4307 }
4308 
4309 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
4310 {
4311 	unsigned i, shift;
4312 	FLAC__int32 x = 0;
4313 
4314 	for(i = 0; i < samples && !(x&1); i++)
4315 		x |= signal[i];
4316 
4317 	if(x == 0) {
4318 		shift = 0;
4319 	}
4320 	else {
4321 		for(shift = 0; !(x&1); shift++)
4322 			x >>= 1;
4323 	}
4324 
4325 	if(shift > 0) {
4326 		for(i = 0; i < samples; i++)
4327 			 signal[i] >>= shift;
4328 	}
4329 
4330 	return shift;
4331 }
4332 
4333 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4334 {
4335 	unsigned channel;
4336 
4337 	for(channel = 0; channel < channels; channel++)
4338 		memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
4339 
4340 	fifo->tail += wide_samples;
4341 
4342 	FLAC__ASSERT(fifo->tail <= fifo->size);
4343 }
4344 
4345 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4346 {
4347 	unsigned channel;
4348 	unsigned sample, wide_sample;
4349 	unsigned tail = fifo->tail;
4350 
4351 	sample = input_offset * channels;
4352 	for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
4353 		for(channel = 0; channel < channels; channel++)
4354 			fifo->data[channel][tail] = input[sample++];
4355 		tail++;
4356 	}
4357 	fifo->tail = tail;
4358 
4359 	FLAC__ASSERT(fifo->tail <= fifo->size);
4360 }
4361 
4362 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4363 {
4364 	FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4365 	const size_t encoded_bytes = encoder->private_->verify.output.bytes;
4366 	(void)decoder;
4367 
4368 	if(encoder->private_->verify.needs_magic_hack) {
4369 		FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
4370 		*bytes = FLAC__STREAM_SYNC_LENGTH;
4371 		memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
4372 		encoder->private_->verify.needs_magic_hack = false;
4373 	}
4374 	else {
4375 		if(encoded_bytes == 0) {
4376 			/*
4377 			 * If we get here, a FIFO underflow has occurred,
4378 			 * which means there is a bug somewhere.
4379 			 */
4380 			FLAC__ASSERT(0);
4381 			return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
4382 		}
4383 		else if(encoded_bytes < *bytes)
4384 			*bytes = encoded_bytes;
4385 		memcpy(buffer, encoder->private_->verify.output.data, *bytes);
4386 		encoder->private_->verify.output.data += *bytes;
4387 		encoder->private_->verify.output.bytes -= *bytes;
4388 	}
4389 
4390 	return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
4391 }
4392 
4393 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
4394 {
4395 	FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
4396 	unsigned channel;
4397 	const unsigned channels = frame->header.channels;
4398 	const unsigned blocksize = frame->header.blocksize;
4399 	const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
4400 
4401 	(void)decoder;
4402 
4403 	for(channel = 0; channel < channels; channel++) {
4404 		if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
4405 			unsigned i, sample = 0;
4406 			FLAC__int32 expect = 0, got = 0;
4407 
4408 			for(i = 0; i < blocksize; i++) {
4409 				if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
4410 					sample = i;
4411 					expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
4412 					got = (FLAC__int32)buffer[channel][i];
4413 					break;
4414 				}
4415 			}
4416 			FLAC__ASSERT(i < blocksize);
4417 			FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
4418 			encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
4419 			encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
4420 			encoder->private_->verify.error_stats.channel = channel;
4421 			encoder->private_->verify.error_stats.sample = sample;
4422 			encoder->private_->verify.error_stats.expected = expect;
4423 			encoder->private_->verify.error_stats.got = got;
4424 			encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
4425 			return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
4426 		}
4427 	}
4428 	/* dequeue the frame from the fifo */
4429 	encoder->private_->verify.input_fifo.tail -= blocksize;
4430 	FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
4431 	for(channel = 0; channel < channels; channel++)
4432 		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]));
4433 	return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4434 }
4435 
4436 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4437 {
4438 	(void)decoder, (void)metadata, (void)client_data;
4439 }
4440 
4441 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4442 {
4443 	FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4444 	(void)decoder, (void)status;
4445 	encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4446 }
4447 
4448 FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4449 {
4450 	(void)client_data;
4451 
4452 	*bytes = fread(buffer, 1, *bytes, encoder->private_->file);
4453 	if (*bytes == 0) {
4454 		if (feof(encoder->private_->file))
4455 			return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
4456 		else if (ferror(encoder->private_->file))
4457 			return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
4458 	}
4459 	return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
4460 }
4461 
4462 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4463 {
4464 	(void)client_data;
4465 
4466 	if(fseeko(encoder->private_->file, (FLAC__off_t)absolute_byte_offset, SEEK_SET) < 0)
4467 		return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4468 	else
4469 		return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4470 }
4471 
4472 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4473 {
4474 	FLAC__off_t offset;
4475 
4476 	(void)client_data;
4477 
4478 	offset = ftello(encoder->private_->file);
4479 
4480 	if(offset < 0) {
4481 		return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4482 	}
4483 	else {
4484 		*absolute_byte_offset = (FLAC__uint64)offset;
4485 		return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4486 	}
4487 }
4488 
4489 #ifdef FLAC__VALGRIND_TESTING
4490 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4491 {
4492 	size_t ret = fwrite(ptr, size, nmemb, stream);
4493 	if(!ferror(stream))
4494 		fflush(stream);
4495 	return ret;
4496 }
4497 #else
4498 #define local__fwrite fwrite
4499 #endif
4500 
4501 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
4502 {
4503 	(void)client_data, (void)current_frame;
4504 
4505 	if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4506 		FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
4507 #if FLAC__HAS_OGG
4508 			/* We would like to be able to use 'samples > 0' in the
4509 			 * clause here but currently because of the nature of our
4510 			 * Ogg writing implementation, 'samples' is always 0 (see
4511 			 * ogg_encoder_aspect.c).  The downside is extra progress
4512 			 * callbacks.
4513 			 */
4514 			encoder->private_->is_ogg? true :
4515 #endif
4516 			samples > 0
4517 		);
4518 		if(call_it) {
4519 			/* NOTE: We have to add +bytes, +samples, and +1 to the stats
4520 			 * because at this point in the callback chain, the stats
4521 			 * have not been updated.  Only after we return and control
4522 			 * gets back to write_frame_() are the stats updated
4523 			 */
4524 			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);
4525 		}
4526 		return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4527 	}
4528 	else
4529 		return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4530 }
4531 
4532 /*
4533  * This will forcibly set stdout to binary mode (for OSes that require it)
4534  */
4535 FILE *get_binary_stdout_(void)
4536 {
4537 	/* if something breaks here it is probably due to the presence or
4538 	 * absence of an underscore before the identifiers 'setmode',
4539 	 * 'fileno', and/or 'O_BINARY'; check your system header files.
4540 	 */
4541 #if defined _MSC_VER || defined __MINGW32__
4542 	_setmode(_fileno(stdout), _O_BINARY);
4543 #elif defined __CYGWIN__
4544 	/* almost certainly not needed for any modern Cygwin, but let's be safe... */
4545 	setmode(_fileno(stdout), _O_BINARY);
4546 #elif defined __EMX__
4547 	setmode(fileno(stdout), O_BINARY);
4548 #endif
4549 
4550 	return stdout;
4551 }
4552