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 //	FLAC__ASSERT(samples <= blocksize);
2163 
2164 	do {
2165 		const unsigned n = flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
2166 
2167 		if(encoder->protected_->verify)
2168 			append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
2169 
2170 		for(channel = 0; channel < channels; channel++) {
2171 			if (buffer[channel] == NULL) {
2172 				return false;
2173 			}
2174 			memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
2175 		}
2176 
2177 		if(encoder->protected_->do_mid_side_stereo) {
2178 			FLAC__ASSERT(channels == 2);
2179 			/* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2180 			for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2181 				encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
2182 				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' ! */
2183 			}
2184 		}
2185 		else
2186 			j += n;
2187 
2188 		encoder->private_->current_sample_number += n;
2189 
2190 		/* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2191 		if(encoder->private_->current_sample_number > blocksize) {
2192 			FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
2193 			FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2194 			if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2195 				return false;
2196 			/* move unprocessed overread samples to beginnings of arrays */
2197 			for(channel = 0; channel < channels; channel++)
2198 				encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2199 			if(encoder->protected_->do_mid_side_stereo) {
2200 				encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2201 				encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2202 			}
2203 			encoder->private_->current_sample_number = 1;
2204 		}
2205 	} while(j < samples);
2206 
2207 	return true;
2208 }
2209 
FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder * encoder,const FLAC__int32 buffer[],unsigned samples)2210 FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2211 {
2212 	unsigned i, j, k, channel;
2213 	FLAC__int32 x, mid, side;
2214 	const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2215 
2216 	FLAC__ASSERT(0 != encoder);
2217 	FLAC__ASSERT(0 != encoder->private_);
2218 	FLAC__ASSERT(0 != encoder->protected_);
2219 	FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2220 
2221 	j = k = 0;
2222 	/*
2223 	 * we have several flavors of the same basic loop, optimized for
2224 	 * different conditions:
2225 	 */
2226 	if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2227 		/*
2228 		 * stereo coding: unroll channel loop
2229 		 */
2230 		do {
2231 			if(encoder->protected_->verify)
2232 				append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2233 
2234 			/* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2235 			for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2236 				encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2237 				x = buffer[k++];
2238 				encoder->private_->integer_signal[1][i] = x;
2239 				mid += x;
2240 				side -= x;
2241 				mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2242 				encoder->private_->integer_signal_mid_side[1][i] = side;
2243 				encoder->private_->integer_signal_mid_side[0][i] = mid;
2244 			}
2245 			encoder->private_->current_sample_number = i;
2246 			/* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2247 			if(i > blocksize) {
2248 				if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2249 					return false;
2250 				/* move unprocessed overread samples to beginnings of arrays */
2251 				FLAC__ASSERT(i == blocksize+OVERREAD_);
2252 				FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2253 				encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
2254 				encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
2255 				encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2256 				encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2257 				encoder->private_->current_sample_number = 1;
2258 			}
2259 		} while(j < samples);
2260 	}
2261 	else {
2262 		/*
2263 		 * independent channel coding: buffer each channel in inner loop
2264 		 */
2265 		do {
2266 			if(encoder->protected_->verify)
2267 				append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2268 
2269 			/* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2270 			for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2271 				for(channel = 0; channel < channels; channel++)
2272 					encoder->private_->integer_signal[channel][i] = buffer[k++];
2273 			}
2274 			encoder->private_->current_sample_number = i;
2275 			/* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2276 			if(i > blocksize) {
2277 				if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2278 					return false;
2279 				/* move unprocessed overread samples to beginnings of arrays */
2280 				FLAC__ASSERT(i == blocksize+OVERREAD_);
2281 				FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2282 				for(channel = 0; channel < channels; channel++)
2283 					encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2284 				encoder->private_->current_sample_number = 1;
2285 			}
2286 		} while(j < samples);
2287 	}
2288 
2289 	return true;
2290 }
2291 
2292 /***********************************************************************
2293  *
2294  * Private class methods
2295  *
2296  ***********************************************************************/
2297 
set_defaults_(FLAC__StreamEncoder * encoder)2298 void set_defaults_(FLAC__StreamEncoder *encoder)
2299 {
2300 	FLAC__ASSERT(0 != encoder);
2301 
2302 #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2303 	encoder->protected_->verify = true;
2304 #else
2305 	encoder->protected_->verify = false;
2306 #endif
2307 	encoder->protected_->streamable_subset = true;
2308 	encoder->protected_->do_md5 = true;
2309 	encoder->protected_->do_mid_side_stereo = false;
2310 	encoder->protected_->loose_mid_side_stereo = false;
2311 	encoder->protected_->channels = 2;
2312 	encoder->protected_->bits_per_sample = 16;
2313 	encoder->protected_->sample_rate = 44100;
2314 	encoder->protected_->blocksize = 0;
2315 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2316 	encoder->protected_->num_apodizations = 1;
2317 	encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2318 	encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2319 #endif
2320 	encoder->protected_->max_lpc_order = 0;
2321 	encoder->protected_->qlp_coeff_precision = 0;
2322 	encoder->protected_->do_qlp_coeff_prec_search = false;
2323 	encoder->protected_->do_exhaustive_model_search = false;
2324 	encoder->protected_->do_escape_coding = false;
2325 	encoder->protected_->min_residual_partition_order = 0;
2326 	encoder->protected_->max_residual_partition_order = 0;
2327 	encoder->protected_->rice_parameter_search_dist = 0;
2328 	encoder->protected_->total_samples_estimate = 0;
2329 	encoder->protected_->metadata = 0;
2330 	encoder->protected_->num_metadata_blocks = 0;
2331 
2332 	encoder->private_->seek_table = 0;
2333 	encoder->private_->disable_constant_subframes = false;
2334 	encoder->private_->disable_fixed_subframes = false;
2335 	encoder->private_->disable_verbatim_subframes = false;
2336 #if FLAC__HAS_OGG
2337 	encoder->private_->is_ogg = false;
2338 #endif
2339 	encoder->private_->read_callback = 0;
2340 	encoder->private_->write_callback = 0;
2341 	encoder->private_->seek_callback = 0;
2342 	encoder->private_->tell_callback = 0;
2343 	encoder->private_->metadata_callback = 0;
2344 	encoder->private_->progress_callback = 0;
2345 	encoder->private_->client_data = 0;
2346 
2347 #if FLAC__HAS_OGG
2348 	FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2349 #endif
2350 
2351 	FLAC__stream_encoder_set_compression_level(encoder, 5);
2352 }
2353 
free_(FLAC__StreamEncoder * encoder)2354 void free_(FLAC__StreamEncoder *encoder)
2355 {
2356 	unsigned i, channel;
2357 
2358 	FLAC__ASSERT(0 != encoder);
2359 	if(encoder->protected_->metadata) {
2360 		free(encoder->protected_->metadata);
2361 		encoder->protected_->metadata = 0;
2362 		encoder->protected_->num_metadata_blocks = 0;
2363 	}
2364 	for(i = 0; i < encoder->protected_->channels; i++) {
2365 		if(0 != encoder->private_->integer_signal_unaligned[i]) {
2366 			free(encoder->private_->integer_signal_unaligned[i]);
2367 			encoder->private_->integer_signal_unaligned[i] = 0;
2368 		}
2369 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2370 		if(0 != encoder->private_->real_signal_unaligned[i]) {
2371 			free(encoder->private_->real_signal_unaligned[i]);
2372 			encoder->private_->real_signal_unaligned[i] = 0;
2373 		}
2374 #endif
2375 	}
2376 	for(i = 0; i < 2; i++) {
2377 		if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2378 			free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2379 			encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2380 		}
2381 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2382 		if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2383 			free(encoder->private_->real_signal_mid_side_unaligned[i]);
2384 			encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2385 		}
2386 #endif
2387 	}
2388 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2389 	for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2390 		if(0 != encoder->private_->window_unaligned[i]) {
2391 			free(encoder->private_->window_unaligned[i]);
2392 			encoder->private_->window_unaligned[i] = 0;
2393 		}
2394 	}
2395 	if(0 != encoder->private_->windowed_signal_unaligned) {
2396 		free(encoder->private_->windowed_signal_unaligned);
2397 		encoder->private_->windowed_signal_unaligned = 0;
2398 	}
2399 #endif
2400 	for(channel = 0; channel < encoder->protected_->channels; channel++) {
2401 		for(i = 0; i < 2; i++) {
2402 			if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2403 				free(encoder->private_->residual_workspace_unaligned[channel][i]);
2404 				encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2405 			}
2406 		}
2407 	}
2408 	for(channel = 0; channel < 2; channel++) {
2409 		for(i = 0; i < 2; i++) {
2410 			if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2411 				free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2412 				encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2413 			}
2414 		}
2415 	}
2416 	if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2417 		free(encoder->private_->abs_residual_partition_sums_unaligned);
2418 		encoder->private_->abs_residual_partition_sums_unaligned = 0;
2419 	}
2420 	if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2421 		free(encoder->private_->raw_bits_per_partition_unaligned);
2422 		encoder->private_->raw_bits_per_partition_unaligned = 0;
2423 	}
2424 	if(encoder->protected_->verify) {
2425 		for(i = 0; i < encoder->protected_->channels; i++) {
2426 			if(0 != encoder->private_->verify.input_fifo.data[i]) {
2427 				free(encoder->private_->verify.input_fifo.data[i]);
2428 				encoder->private_->verify.input_fifo.data[i] = 0;
2429 			}
2430 		}
2431 	}
2432 	FLAC__bitwriter_free(encoder->private_->frame);
2433 }
2434 
resize_buffers_(FLAC__StreamEncoder * encoder,unsigned new_blocksize)2435 FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2436 {
2437 	FLAC__bool ok;
2438 	unsigned i, channel;
2439 
2440 	FLAC__ASSERT(new_blocksize > 0);
2441 	FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2442 	FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2443 
2444 	/* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2445 	if(new_blocksize <= encoder->private_->input_capacity)
2446 		return true;
2447 
2448 	ok = true;
2449 
2450 	/* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx() and ..._intrin_sse2()
2451 	 * require that the input arrays (in our case the integer signals)
2452 	 * have a buffer of up to 3 zeroes in front (at negative indices) for
2453 	 * alignment purposes; we use 4 in front to keep the data well-aligned.
2454 	 */
2455 
2456 	for(i = 0; ok && i < encoder->protected_->channels; i++) {
2457 		ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2458 		memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2459 		encoder->private_->integer_signal[i] += 4;
2460 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2461 #if 0 /* @@@ currently unused */
2462 		if(encoder->protected_->max_lpc_order > 0)
2463 			ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2464 #endif
2465 #endif
2466 	}
2467 	for(i = 0; ok && i < 2; i++) {
2468 		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]);
2469 		memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2470 		encoder->private_->integer_signal_mid_side[i] += 4;
2471 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2472 #if 0 /* @@@ currently unused */
2473 		if(encoder->protected_->max_lpc_order > 0)
2474 			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]);
2475 #endif
2476 #endif
2477 	}
2478 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2479 	if(ok && encoder->protected_->max_lpc_order > 0) {
2480 		for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2481 			ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2482 		ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2483 	}
2484 #endif
2485 	for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2486 		for(i = 0; ok && i < 2; i++) {
2487 			ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2488 		}
2489 	}
2490 	for(channel = 0; ok && channel < 2; channel++) {
2491 		for(i = 0; ok && i < 2; i++) {
2492 			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]);
2493 		}
2494 	}
2495 	/* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2496 	/*@@@ 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) */
2497 	ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2498 	if(encoder->protected_->do_escape_coding)
2499 		ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2500 
2501 	/* now adjust the windows if the blocksize has changed */
2502 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2503 	if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2504 		for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2505 			switch(encoder->protected_->apodizations[i].type) {
2506 				case FLAC__APODIZATION_BARTLETT:
2507 					FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2508 					break;
2509 				case FLAC__APODIZATION_BARTLETT_HANN:
2510 					FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2511 					break;
2512 				case FLAC__APODIZATION_BLACKMAN:
2513 					FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2514 					break;
2515 				case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2516 					FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2517 					break;
2518 				case FLAC__APODIZATION_CONNES:
2519 					FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2520 					break;
2521 				case FLAC__APODIZATION_FLATTOP:
2522 					FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2523 					break;
2524 				case FLAC__APODIZATION_GAUSS:
2525 					FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2526 					break;
2527 				case FLAC__APODIZATION_HAMMING:
2528 					FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2529 					break;
2530 				case FLAC__APODIZATION_HANN:
2531 					FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2532 					break;
2533 				case FLAC__APODIZATION_KAISER_BESSEL:
2534 					FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2535 					break;
2536 				case FLAC__APODIZATION_NUTTALL:
2537 					FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2538 					break;
2539 				case FLAC__APODIZATION_RECTANGLE:
2540 					FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2541 					break;
2542 				case FLAC__APODIZATION_TRIANGLE:
2543 					FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2544 					break;
2545 				case FLAC__APODIZATION_TUKEY:
2546 					FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2547 					break;
2548 				case FLAC__APODIZATION_PARTIAL_TUKEY:
2549 					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);
2550 					break;
2551 				case FLAC__APODIZATION_PUNCHOUT_TUKEY:
2552 					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);
2553 					break;
2554 				case FLAC__APODIZATION_WELCH:
2555 					FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2556 					break;
2557 				default:
2558 					FLAC__ASSERT(0);
2559 					/* double protection */
2560 					FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2561 					break;
2562 			}
2563 		}
2564 	}
2565 #endif
2566 
2567 	if(ok)
2568 		encoder->private_->input_capacity = new_blocksize;
2569 	else
2570 		encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2571 
2572 	return ok;
2573 }
2574 
write_bitbuffer_(FLAC__StreamEncoder * encoder,unsigned samples,FLAC__bool is_last_block)2575 FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2576 {
2577 	const FLAC__byte *buffer;
2578 	size_t bytes;
2579 
2580 	FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2581 
2582 	if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2583 		encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2584 		return false;
2585 	}
2586 
2587 	if(encoder->protected_->verify) {
2588 		encoder->private_->verify.output.data = buffer;
2589 		encoder->private_->verify.output.bytes = bytes;
2590 		if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2591 			encoder->private_->verify.needs_magic_hack = true;
2592 		}
2593 		else {
2594 			if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2595 				FLAC__bitwriter_release_buffer(encoder->private_->frame);
2596 				FLAC__bitwriter_clear(encoder->private_->frame);
2597 				if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2598 					encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2599 				return false;
2600 			}
2601 		}
2602 	}
2603 
2604 	if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2605 		FLAC__bitwriter_release_buffer(encoder->private_->frame);
2606 		FLAC__bitwriter_clear(encoder->private_->frame);
2607 		encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2608 		return false;
2609 	}
2610 
2611 	FLAC__bitwriter_release_buffer(encoder->private_->frame);
2612 	FLAC__bitwriter_clear(encoder->private_->frame);
2613 
2614 	if(samples > 0) {
2615 		encoder->private_->streaminfo.data.stream_info.min_framesize = flac_min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2616 		encoder->private_->streaminfo.data.stream_info.max_framesize = flac_max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2617 	}
2618 
2619 	return true;
2620 }
2621 
write_frame_(FLAC__StreamEncoder * encoder,const FLAC__byte buffer[],size_t bytes,unsigned samples,FLAC__bool is_last_block)2622 FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2623 {
2624 	FLAC__StreamEncoderWriteStatus status;
2625 	FLAC__uint64 output_position = 0;
2626 
2627 #if FLAC__HAS_OGG == 0
2628 	(void)is_last_block;
2629 #endif
2630 
2631 	/* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2632 	if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2633 		encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2634 		return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2635 	}
2636 
2637 	/*
2638 	 * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2639 	 */
2640 	if(samples == 0) {
2641 		FLAC__MetadataType type = (buffer[0] & 0x7f);
2642 		if(type == FLAC__METADATA_TYPE_STREAMINFO)
2643 			encoder->protected_->streaminfo_offset = output_position;
2644 		else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2645 			encoder->protected_->seektable_offset = output_position;
2646 	}
2647 
2648 	/*
2649 	 * Mark the current seek point if hit (if audio_offset == 0 that
2650 	 * means we're still writing metadata and haven't hit the first
2651 	 * frame yet)
2652 	 */
2653 	if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2654 		const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2655 		const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2656 		const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2657 		FLAC__uint64 test_sample;
2658 		unsigned i;
2659 		for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2660 			test_sample = encoder->private_->seek_table->points[i].sample_number;
2661 			if(test_sample > frame_last_sample) {
2662 				break;
2663 			}
2664 			else if(test_sample >= frame_first_sample) {
2665 				encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2666 				encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2667 				encoder->private_->seek_table->points[i].frame_samples = blocksize;
2668 				encoder->private_->first_seekpoint_to_check++;
2669 				/* DO NOT: "break;" and here's why:
2670 				 * The seektable template may contain more than one target
2671 				 * sample for any given frame; we will keep looping, generating
2672 				 * duplicate seekpoints for them, and we'll clean it up later,
2673 				 * just before writing the seektable back to the metadata.
2674 				 */
2675 			}
2676 			else {
2677 				encoder->private_->first_seekpoint_to_check++;
2678 			}
2679 		}
2680 	}
2681 
2682 #if FLAC__HAS_OGG
2683 	if(encoder->private_->is_ogg) {
2684 		status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2685 			&encoder->protected_->ogg_encoder_aspect,
2686 			buffer,
2687 			bytes,
2688 			samples,
2689 			encoder->private_->current_frame_number,
2690 			is_last_block,
2691 			(FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2692 			encoder,
2693 			encoder->private_->client_data
2694 		);
2695 	}
2696 	else
2697 #endif
2698 	status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2699 
2700 	if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2701 		encoder->private_->bytes_written += bytes;
2702 		encoder->private_->samples_written += samples;
2703 		/* we keep a high watermark on the number of frames written because
2704 		 * when the encoder goes back to write metadata, 'current_frame'
2705 		 * will drop back to 0.
2706 		 */
2707 		encoder->private_->frames_written = flac_max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2708 	}
2709 	else
2710 		encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2711 
2712 	return status;
2713 }
2714 
2715 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
update_metadata_(const FLAC__StreamEncoder * encoder)2716 void update_metadata_(const FLAC__StreamEncoder *encoder)
2717 {
2718 	FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2719 	const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2720 	const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2721 	const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2722 	const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2723 	const unsigned bps = metadata->data.stream_info.bits_per_sample;
2724 	FLAC__StreamEncoderSeekStatus seek_status;
2725 
2726 	FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2727 
2728 	/* All this is based on intimate knowledge of the stream header
2729 	 * layout, but a change to the header format that would break this
2730 	 * would also break all streams encoded in the previous format.
2731 	 */
2732 
2733 	/*
2734 	 * Write MD5 signature
2735 	 */
2736 	{
2737 		const unsigned md5_offset =
2738 			FLAC__STREAM_METADATA_HEADER_LENGTH +
2739 			(
2740 				FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2741 				FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2742 				FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2743 				FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2744 				FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2745 				FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2746 				FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2747 				FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2748 			) / 8;
2749 
2750 		if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2751 			if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2752 				encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2753 			return;
2754 		}
2755 		if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2756 			encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2757 			return;
2758 		}
2759 	}
2760 
2761 	/*
2762 	 * Write total samples
2763 	 */
2764 	{
2765 		const unsigned total_samples_byte_offset =
2766 			FLAC__STREAM_METADATA_HEADER_LENGTH +
2767 			(
2768 				FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2769 				FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2770 				FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2771 				FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2772 				FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2773 				FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2774 				FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2775 				- 4
2776 			) / 8;
2777 
2778 		b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2779 		b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2780 		b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2781 		b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2782 		b[4] = (FLAC__byte)(samples & 0xFF);
2783 		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) {
2784 			if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2785 				encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2786 			return;
2787 		}
2788 		if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2789 			encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2790 			return;
2791 		}
2792 	}
2793 
2794 	/*
2795 	 * Write min/max framesize
2796 	 */
2797 	{
2798 		const unsigned min_framesize_offset =
2799 			FLAC__STREAM_METADATA_HEADER_LENGTH +
2800 			(
2801 				FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2802 				FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2803 			) / 8;
2804 
2805 		b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2806 		b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2807 		b[2] = (FLAC__byte)(min_framesize & 0xFF);
2808 		b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2809 		b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2810 		b[5] = (FLAC__byte)(max_framesize & 0xFF);
2811 		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) {
2812 			if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2813 				encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2814 			return;
2815 		}
2816 		if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2817 			encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2818 			return;
2819 		}
2820 	}
2821 
2822 	/*
2823 	 * Write seektable
2824 	 */
2825 	if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2826 		unsigned i;
2827 
2828 		FLAC__format_seektable_sort(encoder->private_->seek_table);
2829 
2830 		FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2831 
2832 		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) {
2833 			if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2834 				encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2835 			return;
2836 		}
2837 
2838 		for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2839 			FLAC__uint64 xx;
2840 			unsigned x;
2841 			xx = encoder->private_->seek_table->points[i].sample_number;
2842 			b[7] = (FLAC__byte)xx; xx >>= 8;
2843 			b[6] = (FLAC__byte)xx; xx >>= 8;
2844 			b[5] = (FLAC__byte)xx; xx >>= 8;
2845 			b[4] = (FLAC__byte)xx; xx >>= 8;
2846 			b[3] = (FLAC__byte)xx; xx >>= 8;
2847 			b[2] = (FLAC__byte)xx; xx >>= 8;
2848 			b[1] = (FLAC__byte)xx; xx >>= 8;
2849 			b[0] = (FLAC__byte)xx; xx >>= 8;
2850 			xx = encoder->private_->seek_table->points[i].stream_offset;
2851 			b[15] = (FLAC__byte)xx; xx >>= 8;
2852 			b[14] = (FLAC__byte)xx; xx >>= 8;
2853 			b[13] = (FLAC__byte)xx; xx >>= 8;
2854 			b[12] = (FLAC__byte)xx; xx >>= 8;
2855 			b[11] = (FLAC__byte)xx; xx >>= 8;
2856 			b[10] = (FLAC__byte)xx; xx >>= 8;
2857 			b[9] = (FLAC__byte)xx; xx >>= 8;
2858 			b[8] = (FLAC__byte)xx; xx >>= 8;
2859 			x = encoder->private_->seek_table->points[i].frame_samples;
2860 			b[17] = (FLAC__byte)x; x >>= 8;
2861 			b[16] = (FLAC__byte)x; x >>= 8;
2862 			if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2863 				encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2864 				return;
2865 			}
2866 		}
2867 	}
2868 }
2869 
2870 #if FLAC__HAS_OGG
2871 /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
update_ogg_metadata_(FLAC__StreamEncoder * encoder)2872 void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2873 {
2874 	/* the # of bytes in the 1st packet that precede the STREAMINFO */
2875 	static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2876 		FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2877 		FLAC__OGG_MAPPING_MAGIC_LENGTH +
2878 		FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2879 		FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2880 		FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2881 		FLAC__STREAM_SYNC_LENGTH
2882 	;
2883 	FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2884 	const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2885 	const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2886 	const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2887 	const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2888 	ogg_page page;
2889 
2890 	FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2891 	FLAC__ASSERT(0 != encoder->private_->seek_callback);
2892 
2893 	/* Pre-check that client supports seeking, since we don't want the
2894 	 * ogg_helper code to ever have to deal with this condition.
2895 	 */
2896 	if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2897 		return;
2898 
2899 	/* All this is based on intimate knowledge of the stream header
2900 	 * layout, but a change to the header format that would break this
2901 	 * would also break all streams encoded in the previous format.
2902 	 */
2903 
2904 	/**
2905 	 ** Write STREAMINFO stats
2906 	 **/
2907 	simple_ogg_page__init(&page);
2908 	if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2909 		simple_ogg_page__clear(&page);
2910 		return; /* state already set */
2911 	}
2912 
2913 	/*
2914 	 * Write MD5 signature
2915 	 */
2916 	{
2917 		const unsigned md5_offset =
2918 			FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2919 			FLAC__STREAM_METADATA_HEADER_LENGTH +
2920 			(
2921 				FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2922 				FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2923 				FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2924 				FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2925 				FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2926 				FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2927 				FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2928 				FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2929 			) / 8;
2930 
2931 		if(md5_offset + 16 > (unsigned)page.body_len) {
2932 			encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2933 			simple_ogg_page__clear(&page);
2934 			return;
2935 		}
2936 		memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2937 	}
2938 
2939 	/*
2940 	 * Write total samples
2941 	 */
2942 	{
2943 		const unsigned total_samples_byte_offset =
2944 			FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2945 			FLAC__STREAM_METADATA_HEADER_LENGTH +
2946 			(
2947 				FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2948 				FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2949 				FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2950 				FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2951 				FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2952 				FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2953 				FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2954 				- 4
2955 			) / 8;
2956 
2957 		if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2958 			encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2959 			simple_ogg_page__clear(&page);
2960 			return;
2961 		}
2962 		b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2963 		b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2964 		b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2965 		b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2966 		b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2967 		b[4] = (FLAC__byte)(samples & 0xFF);
2968 		memcpy(page.body + total_samples_byte_offset, b, 5);
2969 	}
2970 
2971 	/*
2972 	 * Write min/max framesize
2973 	 */
2974 	{
2975 		const unsigned min_framesize_offset =
2976 			FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2977 			FLAC__STREAM_METADATA_HEADER_LENGTH +
2978 			(
2979 				FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2980 				FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2981 			) / 8;
2982 
2983 		if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2984 			encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2985 			simple_ogg_page__clear(&page);
2986 			return;
2987 		}
2988 		b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2989 		b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2990 		b[2] = (FLAC__byte)(min_framesize & 0xFF);
2991 		b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2992 		b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2993 		b[5] = (FLAC__byte)(max_framesize & 0xFF);
2994 		memcpy(page.body + min_framesize_offset, b, 6);
2995 	}
2996 	if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2997 		simple_ogg_page__clear(&page);
2998 		return; /* state already set */
2999 	}
3000 	simple_ogg_page__clear(&page);
3001 
3002 	/*
3003 	 * Write seektable
3004 	 */
3005 	if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
3006 		unsigned i;
3007 		FLAC__byte *p;
3008 
3009 		FLAC__format_seektable_sort(encoder->private_->seek_table);
3010 
3011 		FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
3012 
3013 		simple_ogg_page__init(&page);
3014 		if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
3015 			simple_ogg_page__clear(&page);
3016 			return; /* state already set */
3017 		}
3018 
3019 		if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
3020 			encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
3021 			simple_ogg_page__clear(&page);
3022 			return;
3023 		}
3024 
3025 		for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
3026 			FLAC__uint64 xx;
3027 			unsigned x;
3028 			xx = encoder->private_->seek_table->points[i].sample_number;
3029 			b[7] = (FLAC__byte)xx; xx >>= 8;
3030 			b[6] = (FLAC__byte)xx; xx >>= 8;
3031 			b[5] = (FLAC__byte)xx; xx >>= 8;
3032 			b[4] = (FLAC__byte)xx; xx >>= 8;
3033 			b[3] = (FLAC__byte)xx; xx >>= 8;
3034 			b[2] = (FLAC__byte)xx; xx >>= 8;
3035 			b[1] = (FLAC__byte)xx; xx >>= 8;
3036 			b[0] = (FLAC__byte)xx; xx >>= 8;
3037 			xx = encoder->private_->seek_table->points[i].stream_offset;
3038 			b[15] = (FLAC__byte)xx; xx >>= 8;
3039 			b[14] = (FLAC__byte)xx; xx >>= 8;
3040 			b[13] = (FLAC__byte)xx; xx >>= 8;
3041 			b[12] = (FLAC__byte)xx; xx >>= 8;
3042 			b[11] = (FLAC__byte)xx; xx >>= 8;
3043 			b[10] = (FLAC__byte)xx; xx >>= 8;
3044 			b[9] = (FLAC__byte)xx; xx >>= 8;
3045 			b[8] = (FLAC__byte)xx; xx >>= 8;
3046 			x = encoder->private_->seek_table->points[i].frame_samples;
3047 			b[17] = (FLAC__byte)x; x >>= 8;
3048 			b[16] = (FLAC__byte)x; x >>= 8;
3049 			memcpy(p, b, 18);
3050 		}
3051 
3052 		if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
3053 			simple_ogg_page__clear(&page);
3054 			return; /* state already set */
3055 		}
3056 		simple_ogg_page__clear(&page);
3057 	}
3058 }
3059 #endif
3060 
process_frame_(FLAC__StreamEncoder * encoder,FLAC__bool is_fractional_block,FLAC__bool is_last_block)3061 FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
3062 {
3063 	FLAC__uint16 crc;
3064 	FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
3065 
3066 	/*
3067 	 * Accumulate raw signal to the MD5 signature
3068 	 */
3069 	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)) {
3070 		encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3071 		return false;
3072 	}
3073 
3074 	/*
3075 	 * Process the frame header and subframes into the frame bitbuffer
3076 	 */
3077 	if(!process_subframes_(encoder, is_fractional_block)) {
3078 		/* the above function sets the state for us in case of an error */
3079 		return false;
3080 	}
3081 
3082 	/*
3083 	 * Zero-pad the frame to a byte_boundary
3084 	 */
3085 	if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
3086 		encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3087 		return false;
3088 	}
3089 
3090 	/*
3091 	 * CRC-16 the whole thing
3092 	 */
3093 	FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
3094 	if(
3095 		!FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
3096 		!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
3097 	) {
3098 		encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
3099 		return false;
3100 	}
3101 
3102 	/*
3103 	 * Write it
3104 	 */
3105 	if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
3106 		/* the above function sets the state for us in case of an error */
3107 		return false;
3108 	}
3109 
3110 	/*
3111 	 * Get ready for the next frame
3112 	 */
3113 	encoder->private_->current_sample_number = 0;
3114 	encoder->private_->current_frame_number++;
3115 	encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
3116 
3117 	return true;
3118 }
3119 
process_subframes_(FLAC__StreamEncoder * encoder,FLAC__bool is_fractional_block)3120 FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
3121 {
3122 	FLAC__FrameHeader frame_header;
3123 	unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
3124 	FLAC__bool do_independent, do_mid_side;
3125 
3126 	/*
3127 	 * Calculate the min,max Rice partition orders
3128 	 */
3129 	if(is_fractional_block) {
3130 		max_partition_order = 0;
3131 	}
3132 	else {
3133 		max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
3134 		max_partition_order = flac_min(max_partition_order, encoder->protected_->max_residual_partition_order);
3135 	}
3136 	min_partition_order = flac_min(min_partition_order, max_partition_order);
3137 
3138 	/*
3139 	 * Setup the frame
3140 	 */
3141 	frame_header.blocksize = encoder->protected_->blocksize;
3142 	frame_header.sample_rate = encoder->protected_->sample_rate;
3143 	frame_header.channels = encoder->protected_->channels;
3144 	frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
3145 	frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
3146 	frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
3147 	frame_header.number.frame_number = encoder->private_->current_frame_number;
3148 
3149 	/*
3150 	 * Figure out what channel assignments to try
3151 	 */
3152 	if(encoder->protected_->do_mid_side_stereo) {
3153 		if(encoder->protected_->loose_mid_side_stereo) {
3154 			if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
3155 				do_independent = true;
3156 				do_mid_side = true;
3157 			}
3158 			else {
3159 				do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
3160 				do_mid_side = !do_independent;
3161 			}
3162 		}
3163 		else {
3164 			do_independent = true;
3165 			do_mid_side = true;
3166 		}
3167 	}
3168 	else {
3169 		do_independent = true;
3170 		do_mid_side = false;
3171 	}
3172 
3173 	FLAC__ASSERT(do_independent || do_mid_side);
3174 
3175 	/*
3176 	 * Check for wasted bits; set effective bps for each subframe
3177 	 */
3178 	if(do_independent) {
3179 		for(channel = 0; channel < encoder->protected_->channels; channel++) {
3180 			const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
3181 			encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
3182 			encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
3183 		}
3184 	}
3185 	if(do_mid_side) {
3186 		FLAC__ASSERT(encoder->protected_->channels == 2);
3187 		for(channel = 0; channel < 2; channel++) {
3188 			const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
3189 			encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
3190 			encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
3191 		}
3192 	}
3193 
3194 	/*
3195 	 * First do a normal encoding pass of each independent channel
3196 	 */
3197 	if(do_independent) {
3198 		for(channel = 0; channel < encoder->protected_->channels; channel++) {
3199 			if(!
3200 				process_subframe_(
3201 					encoder,
3202 					min_partition_order,
3203 					max_partition_order,
3204 					&frame_header,
3205 					encoder->private_->subframe_bps[channel],
3206 					encoder->private_->integer_signal[channel],
3207 					encoder->private_->subframe_workspace_ptr[channel],
3208 					encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3209 					encoder->private_->residual_workspace[channel],
3210 					encoder->private_->best_subframe+channel,
3211 					encoder->private_->best_subframe_bits+channel
3212 				)
3213 			)
3214 				return false;
3215 		}
3216 	}
3217 
3218 	/*
3219 	 * Now do mid and side channels if requested
3220 	 */
3221 	if(do_mid_side) {
3222 		FLAC__ASSERT(encoder->protected_->channels == 2);
3223 
3224 		for(channel = 0; channel < 2; channel++) {
3225 			if(!
3226 				process_subframe_(
3227 					encoder,
3228 					min_partition_order,
3229 					max_partition_order,
3230 					&frame_header,
3231 					encoder->private_->subframe_bps_mid_side[channel],
3232 					encoder->private_->integer_signal_mid_side[channel],
3233 					encoder->private_->subframe_workspace_ptr_mid_side[channel],
3234 					encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3235 					encoder->private_->residual_workspace_mid_side[channel],
3236 					encoder->private_->best_subframe_mid_side+channel,
3237 					encoder->private_->best_subframe_bits_mid_side+channel
3238 				)
3239 			)
3240 				return false;
3241 		}
3242 	}
3243 
3244 	/*
3245 	 * Compose the frame bitbuffer
3246 	 */
3247 	if(do_mid_side) {
3248 		unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3249 		FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3250 		FLAC__ChannelAssignment channel_assignment;
3251 
3252 		FLAC__ASSERT(encoder->protected_->channels == 2);
3253 
3254 		if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3255 			channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3256 		}
3257 		else {
3258 			unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3259 			unsigned min_bits;
3260 			int ca;
3261 
3262 			FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3263 			FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE   == 1);
3264 			FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE  == 2);
3265 			FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE    == 3);
3266 			FLAC__ASSERT(do_independent && do_mid_side);
3267 
3268 			/* We have to figure out which channel assignent results in the smallest frame */
3269 			bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits         [1];
3270 			bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE  ] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits_mid_side[1];
3271 			bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits         [1] + encoder->private_->best_subframe_bits_mid_side[1];
3272 			bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE   ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3273 
3274 			channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3275 			min_bits = bits[channel_assignment];
3276 			for(ca = 1; ca <= 3; ca++) {
3277 				if(bits[ca] < min_bits) {
3278 					min_bits = bits[ca];
3279 					channel_assignment = (FLAC__ChannelAssignment)ca;
3280 				}
3281 			}
3282 		}
3283 
3284 		frame_header.channel_assignment = channel_assignment;
3285 
3286 		if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3287 			encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3288 			return false;
3289 		}
3290 
3291 		switch(channel_assignment) {
3292 			case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3293 				left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3294 				right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
3295 				break;
3296 			case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3297 				left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3298 				right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3299 				break;
3300 			case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3301 				left_subframe  = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3302 				right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
3303 				break;
3304 			case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3305 				left_subframe  = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3306 				right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3307 				break;
3308 			default:
3309 				FLAC__ASSERT(0);
3310 		}
3311 
3312 		switch(channel_assignment) {
3313 			case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3314 				left_bps  = encoder->private_->subframe_bps         [0];
3315 				right_bps = encoder->private_->subframe_bps         [1];
3316 				break;
3317 			case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3318 				left_bps  = encoder->private_->subframe_bps         [0];
3319 				right_bps = encoder->private_->subframe_bps_mid_side[1];
3320 				break;
3321 			case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3322 				left_bps  = encoder->private_->subframe_bps_mid_side[1];
3323 				right_bps = encoder->private_->subframe_bps         [1];
3324 				break;
3325 			case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3326 				left_bps  = encoder->private_->subframe_bps_mid_side[0];
3327 				right_bps = encoder->private_->subframe_bps_mid_side[1];
3328 				break;
3329 			default:
3330 				FLAC__ASSERT(0);
3331 		}
3332 
3333 		/* note that encoder_add_subframe_ sets the state for us in case of an error */
3334 		if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3335 			return false;
3336 		if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3337 			return false;
3338 	}
3339 	else {
3340 		if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3341 			encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3342 			return false;
3343 		}
3344 
3345 		for(channel = 0; channel < encoder->protected_->channels; channel++) {
3346 			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)) {
3347 				/* the above function sets the state for us in case of an error */
3348 				return false;
3349 			}
3350 		}
3351 	}
3352 
3353 	if(encoder->protected_->loose_mid_side_stereo) {
3354 		encoder->private_->loose_mid_side_stereo_frame_count++;
3355 		if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3356 			encoder->private_->loose_mid_side_stereo_frame_count = 0;
3357 	}
3358 
3359 	encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3360 
3361 	return true;
3362 }
3363 
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)3364 FLAC__bool process_subframe_(
3365 	FLAC__StreamEncoder *encoder,
3366 	unsigned min_partition_order,
3367 	unsigned max_partition_order,
3368 	const FLAC__FrameHeader *frame_header,
3369 	unsigned subframe_bps,
3370 	const FLAC__int32 integer_signal[],
3371 	FLAC__Subframe *subframe[2],
3372 	FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3373 	FLAC__int32 *residual[2],
3374 	unsigned *best_subframe,
3375 	unsigned *best_bits
3376 )
3377 {
3378 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3379 	FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3380 #else
3381 	FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3382 #endif
3383 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3384 	FLAC__double lpc_residual_bits_per_sample;
3385 	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 */
3386 	FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3387 	unsigned min_lpc_order, max_lpc_order, lpc_order;
3388 	unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3389 #endif
3390 	unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3391 	unsigned rice_parameter;
3392 	unsigned _candidate_bits, _best_bits;
3393 	unsigned _best_subframe;
3394 	/* only use RICE2 partitions if stream bps > 16 */
3395 	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;
3396 
3397 	FLAC__ASSERT(frame_header->blocksize > 0);
3398 
3399 	/* verbatim subframe is the baseline against which we measure other compressed subframes */
3400 	_best_subframe = 0;
3401 	if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3402 		_best_bits = UINT_MAX;
3403 	else
3404 		_best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3405 
3406 	if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3407 		unsigned signal_is_constant = false;
3408 		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);
3409 		/* check for constant subframe */
3410 		if(
3411 			!encoder->private_->disable_constant_subframes &&
3412 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3413 			fixed_residual_bits_per_sample[1] == 0.0
3414 #else
3415 			fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3416 #endif
3417 		) {
3418 			/* the above means it's possible all samples are the same value; now double-check it: */
3419 			unsigned i;
3420 			signal_is_constant = true;
3421 			for(i = 1; i < frame_header->blocksize; i++) {
3422 				if(integer_signal[0] != integer_signal[i]) {
3423 					signal_is_constant = false;
3424 					break;
3425 				}
3426 			}
3427 		}
3428 		if(signal_is_constant) {
3429 			_candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3430 			if(_candidate_bits < _best_bits) {
3431 				_best_subframe = !_best_subframe;
3432 				_best_bits = _candidate_bits;
3433 			}
3434 		}
3435 		else {
3436 			if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3437 				/* encode fixed */
3438 				if(encoder->protected_->do_exhaustive_model_search) {
3439 					min_fixed_order = 0;
3440 					max_fixed_order = FLAC__MAX_FIXED_ORDER;
3441 				}
3442 				else {
3443 					min_fixed_order = max_fixed_order = guess_fixed_order;
3444 				}
3445 				if(max_fixed_order >= frame_header->blocksize)
3446 					max_fixed_order = frame_header->blocksize - 1;
3447 				for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3448 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3449 					if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3450 						continue; /* don't even try */
3451 					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 */
3452 #else
3453 					if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3454 						continue; /* don't even try */
3455 					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 */
3456 #endif
3457 					rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3458 					if(rice_parameter >= rice_parameter_limit) {
3459 #ifdef DEBUG_VERBOSE
3460 						fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
3461 #endif
3462 						rice_parameter = rice_parameter_limit - 1;
3463 					}
3464 					_candidate_bits =
3465 						evaluate_fixed_subframe_(
3466 							encoder,
3467 							integer_signal,
3468 							residual[!_best_subframe],
3469 							encoder->private_->abs_residual_partition_sums,
3470 							encoder->private_->raw_bits_per_partition,
3471 							frame_header->blocksize,
3472 							subframe_bps,
3473 							fixed_order,
3474 							rice_parameter,
3475 							rice_parameter_limit,
3476 							min_partition_order,
3477 							max_partition_order,
3478 							encoder->protected_->do_escape_coding,
3479 							encoder->protected_->rice_parameter_search_dist,
3480 							subframe[!_best_subframe],
3481 							partitioned_rice_contents[!_best_subframe]
3482 						);
3483 					if(_candidate_bits < _best_bits) {
3484 						_best_subframe = !_best_subframe;
3485 						_best_bits = _candidate_bits;
3486 					}
3487 				}
3488 			}
3489 
3490 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3491 			/* encode lpc */
3492 			if(encoder->protected_->max_lpc_order > 0) {
3493 				if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3494 					max_lpc_order = frame_header->blocksize-1;
3495 				else
3496 					max_lpc_order = encoder->protected_->max_lpc_order;
3497 				if(max_lpc_order > 0) {
3498 					unsigned a;
3499 					for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3500 						FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3501 						encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3502 						/* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3503 						if(autoc[0] != 0.0) {
3504 							FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3505 							if(encoder->protected_->do_exhaustive_model_search) {
3506 								min_lpc_order = 1;
3507 							}
3508 							else {
3509 								const unsigned guess_lpc_order =
3510 									FLAC__lpc_compute_best_order(
3511 										lpc_error,
3512 										max_lpc_order,
3513 										frame_header->blocksize,
3514 										subframe_bps + (
3515 											encoder->protected_->do_qlp_coeff_prec_search?
3516 												FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
3517 												encoder->protected_->qlp_coeff_precision
3518 										)
3519 									);
3520 								min_lpc_order = max_lpc_order = guess_lpc_order;
3521 							}
3522 							if(max_lpc_order >= frame_header->blocksize)
3523 								max_lpc_order = frame_header->blocksize - 1;
3524 							for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
3525 								lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
3526 								if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
3527 									continue; /* don't even try */
3528 								rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
3529 								rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3530 								if(rice_parameter >= rice_parameter_limit) {
3531 #ifdef DEBUG_VERBOSE
3532 									fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
3533 #endif
3534 									rice_parameter = rice_parameter_limit - 1;
3535 								}
3536 								if(encoder->protected_->do_qlp_coeff_prec_search) {
3537 									min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
3538 									/* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3539 									if(subframe_bps <= 16) {
3540 										max_qlp_coeff_precision = flac_min(32 - subframe_bps - FLAC__bitmath_ilog2(lpc_order), FLAC__MAX_QLP_COEFF_PRECISION);
3541 										max_qlp_coeff_precision = flac_max(max_qlp_coeff_precision, min_qlp_coeff_precision);
3542 									}
3543 									else
3544 										max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
3545 								}
3546 								else {
3547 									min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
3548 								}
3549 								for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
3550 									_candidate_bits =
3551 										evaluate_lpc_subframe_(
3552 											encoder,
3553 											integer_signal,
3554 											residual[!_best_subframe],
3555 											encoder->private_->abs_residual_partition_sums,
3556 											encoder->private_->raw_bits_per_partition,
3557 											encoder->private_->lp_coeff[lpc_order-1],
3558 											frame_header->blocksize,
3559 											subframe_bps,
3560 											lpc_order,
3561 											qlp_coeff_precision,
3562 											rice_parameter,
3563 											rice_parameter_limit,
3564 											min_partition_order,
3565 											max_partition_order,
3566 											encoder->protected_->do_escape_coding,
3567 											encoder->protected_->rice_parameter_search_dist,
3568 											subframe[!_best_subframe],
3569 											partitioned_rice_contents[!_best_subframe]
3570 										);
3571 									if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
3572 										if(_candidate_bits < _best_bits) {
3573 											_best_subframe = !_best_subframe;
3574 											_best_bits = _candidate_bits;
3575 										}
3576 									}
3577 								}
3578 							}
3579 						}
3580 					}
3581 				}
3582 			}
3583 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3584 		}
3585 	}
3586 
3587 	/* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3588 	if(_best_bits == UINT_MAX) {
3589 		FLAC__ASSERT(_best_subframe == 0);
3590 		_best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3591 	}
3592 
3593 	*best_subframe = _best_subframe;
3594 	*best_bits = _best_bits;
3595 
3596 	return true;
3597 }
3598 
add_subframe_(FLAC__StreamEncoder * encoder,unsigned blocksize,unsigned subframe_bps,const FLAC__Subframe * subframe,FLAC__BitWriter * frame)3599 FLAC__bool add_subframe_(
3600 	FLAC__StreamEncoder *encoder,
3601 	unsigned blocksize,
3602 	unsigned subframe_bps,
3603 	const FLAC__Subframe *subframe,
3604 	FLAC__BitWriter *frame
3605 )
3606 {
3607 	switch(subframe->type) {
3608 		case FLAC__SUBFRAME_TYPE_CONSTANT:
3609 			if(!FLAC__subframe_add_constant(&(subframe->data.constant), 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_FIXED:
3615 			if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.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_LPC:
3621 			if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3622 				encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3623 				return false;
3624 			}
3625 			break;
3626 		case FLAC__SUBFRAME_TYPE_VERBATIM:
3627 			if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3628 				encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3629 				return false;
3630 			}
3631 			break;
3632 		default:
3633 			FLAC__ASSERT(0);
3634 	}
3635 
3636 	return true;
3637 }
3638 
3639 #define SPOTCHECK_ESTIMATE 0
3640 #if SPOTCHECK_ESTIMATE
spotcheck_subframe_estimate_(FLAC__StreamEncoder * encoder,unsigned blocksize,unsigned subframe_bps,const FLAC__Subframe * subframe,unsigned estimate)3641 static void spotcheck_subframe_estimate_(
3642 	FLAC__StreamEncoder *encoder,
3643 	unsigned blocksize,
3644 	unsigned subframe_bps,
3645 	const FLAC__Subframe *subframe,
3646 	unsigned estimate
3647 )
3648 {
3649 	FLAC__bool ret;
3650 	FLAC__BitWriter *frame = FLAC__bitwriter_new();
3651 	if(frame == 0) {
3652 		fprintf(stderr, "EST: can't allocate frame\n");
3653 		return;
3654 	}
3655 	if(!FLAC__bitwriter_init(frame)) {
3656 		fprintf(stderr, "EST: can't init frame\n");
3657 		return;
3658 	}
3659 	ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
3660 	FLAC__ASSERT(ret);
3661 	{
3662 		const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
3663 		if(estimate != actual)
3664 			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);
3665 	}
3666 	FLAC__bitwriter_delete(frame);
3667 }
3668 #endif
3669 
evaluate_constant_subframe_(FLAC__StreamEncoder * encoder,const FLAC__int32 signal,unsigned blocksize,unsigned subframe_bps,FLAC__Subframe * subframe)3670 unsigned evaluate_constant_subframe_(
3671 	FLAC__StreamEncoder *encoder,
3672 	const FLAC__int32 signal,
3673 	unsigned blocksize,
3674 	unsigned subframe_bps,
3675 	FLAC__Subframe *subframe
3676 )
3677 {
3678 	unsigned estimate;
3679 	subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3680 	subframe->data.constant.value = signal;
3681 
3682 	estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
3683 
3684 #if SPOTCHECK_ESTIMATE
3685 	spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3686 #else
3687 	(void)encoder, (void)blocksize;
3688 #endif
3689 
3690 	return estimate;
3691 }
3692 
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)3693 unsigned evaluate_fixed_subframe_(
3694 	FLAC__StreamEncoder *encoder,
3695 	const FLAC__int32 signal[],
3696 	FLAC__int32 residual[],
3697 	FLAC__uint64 abs_residual_partition_sums[],
3698 	unsigned raw_bits_per_partition[],
3699 	unsigned blocksize,
3700 	unsigned subframe_bps,
3701 	unsigned order,
3702 	unsigned rice_parameter,
3703 	unsigned rice_parameter_limit,
3704 	unsigned min_partition_order,
3705 	unsigned max_partition_order,
3706 	FLAC__bool do_escape_coding,
3707 	unsigned rice_parameter_search_dist,
3708 	FLAC__Subframe *subframe,
3709 	FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3710 )
3711 {
3712 	unsigned i, residual_bits, estimate;
3713 	const unsigned residual_samples = blocksize - order;
3714 
3715 	FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3716 
3717 	subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3718 
3719 	subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3720 	subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3721 	subframe->data.fixed.residual = residual;
3722 
3723 	residual_bits =
3724 		find_best_partition_order_(
3725 			encoder->private_,
3726 			residual,
3727 			abs_residual_partition_sums,
3728 			raw_bits_per_partition,
3729 			residual_samples,
3730 			order,
3731 			rice_parameter,
3732 			rice_parameter_limit,
3733 			min_partition_order,
3734 			max_partition_order,
3735 			subframe_bps,
3736 			do_escape_coding,
3737 			rice_parameter_search_dist,
3738 			&subframe->data.fixed.entropy_coding_method
3739 		);
3740 
3741 	subframe->data.fixed.order = order;
3742 	for(i = 0; i < order; i++)
3743 		subframe->data.fixed.warmup[i] = signal[i];
3744 
3745 	estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
3746 
3747 #if SPOTCHECK_ESTIMATE
3748 	spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3749 #endif
3750 
3751 	return estimate;
3752 }
3753 
3754 #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)3755 unsigned evaluate_lpc_subframe_(
3756 	FLAC__StreamEncoder *encoder,
3757 	const FLAC__int32 signal[],
3758 	FLAC__int32 residual[],
3759 	FLAC__uint64 abs_residual_partition_sums[],
3760 	unsigned raw_bits_per_partition[],
3761 	const FLAC__real lp_coeff[],
3762 	unsigned blocksize,
3763 	unsigned subframe_bps,
3764 	unsigned order,
3765 	unsigned qlp_coeff_precision,
3766 	unsigned rice_parameter,
3767 	unsigned rice_parameter_limit,
3768 	unsigned min_partition_order,
3769 	unsigned max_partition_order,
3770 	FLAC__bool do_escape_coding,
3771 	unsigned rice_parameter_search_dist,
3772 	FLAC__Subframe *subframe,
3773 	FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3774 )
3775 {
3776 	FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER]; /* WATCHOUT: the size is important; some x86 intrinsic routines need more than lpc order elements */
3777 	unsigned i, residual_bits, estimate;
3778 	int quantization, ret;
3779 	const unsigned residual_samples = blocksize - order;
3780 
3781 	/* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3782 	if(subframe_bps <= 16) {
3783 		FLAC__ASSERT(order > 0);
3784 		FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3785 		qlp_coeff_precision = flac_min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3786 	}
3787 
3788 	ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3789 	if(ret != 0)
3790 		return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3791 
3792 	if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3793 		if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3794 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3795 		else
3796 			encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3797 	else
3798 		encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3799 
3800 	subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3801 
3802 	subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3803 	subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3804 	subframe->data.lpc.residual = residual;
3805 
3806 	residual_bits =
3807 		find_best_partition_order_(
3808 			encoder->private_,
3809 			residual,
3810 			abs_residual_partition_sums,
3811 			raw_bits_per_partition,
3812 			residual_samples,
3813 			order,
3814 			rice_parameter,
3815 			rice_parameter_limit,
3816 			min_partition_order,
3817 			max_partition_order,
3818 			subframe_bps,
3819 			do_escape_coding,
3820 			rice_parameter_search_dist,
3821 			&subframe->data.lpc.entropy_coding_method
3822 		);
3823 
3824 	subframe->data.lpc.order = order;
3825 	subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3826 	subframe->data.lpc.quantization_level = quantization;
3827 	memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3828 	for(i = 0; i < order; i++)
3829 		subframe->data.lpc.warmup[i] = signal[i];
3830 
3831 	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;
3832 
3833 #if SPOTCHECK_ESTIMATE
3834 	spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3835 #endif
3836 
3837 	return estimate;
3838 }
3839 #endif
3840 
evaluate_verbatim_subframe_(FLAC__StreamEncoder * encoder,const FLAC__int32 signal[],unsigned blocksize,unsigned subframe_bps,FLAC__Subframe * subframe)3841 unsigned evaluate_verbatim_subframe_(
3842 	FLAC__StreamEncoder *encoder,
3843 	const FLAC__int32 signal[],
3844 	unsigned blocksize,
3845 	unsigned subframe_bps,
3846 	FLAC__Subframe *subframe
3847 )
3848 {
3849 	unsigned estimate;
3850 
3851 	subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3852 
3853 	subframe->data.verbatim.data = signal;
3854 
3855 	estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
3856 
3857 #if SPOTCHECK_ESTIMATE
3858 	spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3859 #else
3860 	(void)encoder;
3861 #endif
3862 
3863 	return estimate;
3864 }
3865 
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)3866 unsigned find_best_partition_order_(
3867 	FLAC__StreamEncoderPrivate *private_,
3868 	const FLAC__int32 residual[],
3869 	FLAC__uint64 abs_residual_partition_sums[],
3870 	unsigned raw_bits_per_partition[],
3871 	unsigned residual_samples,
3872 	unsigned predictor_order,
3873 	unsigned rice_parameter,
3874 	unsigned rice_parameter_limit,
3875 	unsigned min_partition_order,
3876 	unsigned max_partition_order,
3877 	unsigned bps,
3878 	FLAC__bool do_escape_coding,
3879 	unsigned rice_parameter_search_dist,
3880 	FLAC__EntropyCodingMethod *best_ecm
3881 )
3882 {
3883 	unsigned residual_bits, best_residual_bits = 0;
3884 	unsigned best_parameters_index = 0;
3885 	unsigned best_partition_order = 0;
3886 	const unsigned blocksize = residual_samples + predictor_order;
3887 
3888 	max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3889 	min_partition_order = flac_min(min_partition_order, max_partition_order);
3890 
3891 	private_->local_precompute_partition_info_sums(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
3892 
3893 	if(do_escape_coding)
3894 		precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3895 
3896 	{
3897 		int partition_order;
3898 		unsigned sum;
3899 
3900 		for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3901 			if(!
3902 				set_partitioned_rice_(
3903 #ifdef EXACT_RICE_BITS_CALCULATION
3904 					residual,
3905 #endif
3906 					abs_residual_partition_sums+sum,
3907 					raw_bits_per_partition+sum,
3908 					residual_samples,
3909 					predictor_order,
3910 					rice_parameter,
3911 					rice_parameter_limit,
3912 					rice_parameter_search_dist,
3913 					(unsigned)partition_order,
3914 					do_escape_coding,
3915 					&private_->partitioned_rice_contents_extra[!best_parameters_index],
3916 					&residual_bits
3917 				)
3918 			)
3919 			{
3920 				FLAC__ASSERT(best_residual_bits != 0);
3921 				break;
3922 			}
3923 			sum += 1u << partition_order;
3924 			if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3925 				best_residual_bits = residual_bits;
3926 				best_parameters_index = !best_parameters_index;
3927 				best_partition_order = partition_order;
3928 			}
3929 		}
3930 	}
3931 
3932 	best_ecm->data.partitioned_rice.order = best_partition_order;
3933 
3934 	{
3935 		/*
3936 		 * We are allowed to de-const the pointer based on our special
3937 		 * knowledge; it is const to the outside world.
3938 		 */
3939 		FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
3940 		unsigned partition;
3941 
3942 		/* save best parameters and raw_bits */
3943 		FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, flac_max(6u, best_partition_order));
3944 		memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
3945 		if(do_escape_coding)
3946 			memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
3947 		/*
3948 		 * Now need to check if the type should be changed to
3949 		 * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
3950 		 * size of the rice parameters.
3951 		 */
3952 		for(partition = 0; partition < (1u<<best_partition_order); partition++) {
3953 			if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3954 				best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
3955 				break;
3956 			}
3957 		}
3958 	}
3959 
3960 	return best_residual_bits;
3961 }
3962 
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)3963 void precompute_partition_info_sums_(
3964 	const FLAC__int32 residual[],
3965 	FLAC__uint64 abs_residual_partition_sums[],
3966 	unsigned residual_samples,
3967 	unsigned predictor_order,
3968 	unsigned min_partition_order,
3969 	unsigned max_partition_order,
3970 	unsigned bps
3971 )
3972 {
3973 	const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
3974 	unsigned partitions = 1u << max_partition_order;
3975 
3976 	FLAC__ASSERT(default_partition_samples > predictor_order);
3977 
3978 	/* first do max_partition_order */
3979 	{
3980 		unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
3981 		/* WATCHOUT: "+ bps + FLAC__MAX_EXTRA_RESIDUAL_BPS" is the maximum
3982 		 * assumed size of the average residual magnitude */
3983 		if(FLAC__bitmath_ilog2(default_partition_samples) + bps + FLAC__MAX_EXTRA_RESIDUAL_BPS < 32) {
3984 			FLAC__uint32 abs_residual_partition_sum;
3985 
3986 			for(partition = residual_sample = 0; partition < partitions; partition++) {
3987 				end += default_partition_samples;
3988 				abs_residual_partition_sum = 0;
3989 				for( ; residual_sample < end; residual_sample++)
3990 					abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3991 				abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3992 			}
3993 		}
3994 		else { /* have to pessimistically use 64 bits for accumulator */
3995 			FLAC__uint64 abs_residual_partition_sum;
3996 
3997 			for(partition = residual_sample = 0; partition < partitions; partition++) {
3998 				end += default_partition_samples;
3999 				abs_residual_partition_sum = 0;
4000 				for( ; residual_sample < end; residual_sample++)
4001 					abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
4002 				abs_residual_partition_sums[partition] = abs_residual_partition_sum;
4003 			}
4004 		}
4005 	}
4006 
4007 	/* now merge partitions for lower orders */
4008 	{
4009 		unsigned from_partition = 0, to_partition = partitions;
4010 		int partition_order;
4011 		for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
4012 			unsigned i;
4013 			partitions >>= 1;
4014 			for(i = 0; i < partitions; i++) {
4015 				abs_residual_partition_sums[to_partition++] =
4016 					abs_residual_partition_sums[from_partition  ] +
4017 					abs_residual_partition_sums[from_partition+1];
4018 				from_partition += 2;
4019 			}
4020 		}
4021 	}
4022 }
4023 
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)4024 void precompute_partition_info_escapes_(
4025 	const FLAC__int32 residual[],
4026 	unsigned raw_bits_per_partition[],
4027 	unsigned residual_samples,
4028 	unsigned predictor_order,
4029 	unsigned min_partition_order,
4030 	unsigned max_partition_order
4031 )
4032 {
4033 	int partition_order;
4034 	unsigned from_partition, to_partition = 0;
4035 	const unsigned blocksize = residual_samples + predictor_order;
4036 
4037 	/* first do max_partition_order */
4038 	for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
4039 		FLAC__int32 r;
4040 		FLAC__uint32 rmax;
4041 		unsigned partition, partition_sample, partition_samples, residual_sample;
4042 		const unsigned partitions = 1u << partition_order;
4043 		const unsigned default_partition_samples = blocksize >> partition_order;
4044 
4045 		FLAC__ASSERT(default_partition_samples > predictor_order);
4046 
4047 		for(partition = residual_sample = 0; partition < partitions; partition++) {
4048 			partition_samples = default_partition_samples;
4049 			if(partition == 0)
4050 				partition_samples -= predictor_order;
4051 			rmax = 0;
4052 			for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
4053 				r = residual[residual_sample++];
4054 				/* OPT: maybe faster: rmax |= r ^ (r>>31) */
4055 				if(r < 0)
4056 					rmax |= ~r;
4057 				else
4058 					rmax |= r;
4059 			}
4060 			/* now we know all residual values are in the range [-rmax-1,rmax] */
4061 			raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
4062 		}
4063 		to_partition = partitions;
4064 		break; /*@@@ yuck, should remove the 'for' loop instead */
4065 	}
4066 
4067 	/* now merge partitions for lower orders */
4068 	for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
4069 		unsigned m;
4070 		unsigned i;
4071 		const unsigned partitions = 1u << partition_order;
4072 		for(i = 0; i < partitions; i++) {
4073 			m = raw_bits_per_partition[from_partition];
4074 			from_partition++;
4075 			raw_bits_per_partition[to_partition] = flac_max(m, raw_bits_per_partition[from_partition]);
4076 			from_partition++;
4077 			to_partition++;
4078 		}
4079 	}
4080 }
4081 
4082 #ifdef EXACT_RICE_BITS_CALCULATION
count_rice_bits_in_partition_(const unsigned rice_parameter,const unsigned partition_samples,const FLAC__int32 * residual)4083 static inline unsigned count_rice_bits_in_partition_(
4084 	const unsigned rice_parameter,
4085 	const unsigned partition_samples,
4086 	const FLAC__int32 *residual
4087 )
4088 {
4089 	unsigned i, partition_bits =
4090 		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 */
4091 		(1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
4092 	;
4093 	for(i = 0; i < partition_samples; i++)
4094 		partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
4095 	return partition_bits;
4096 }
4097 #else
count_rice_bits_in_partition_(const unsigned rice_parameter,const unsigned partition_samples,const FLAC__uint64 abs_residual_partition_sum)4098 static inline unsigned count_rice_bits_in_partition_(
4099 	const unsigned rice_parameter,
4100 	const unsigned partition_samples,
4101 	const FLAC__uint64 abs_residual_partition_sum
4102 )
4103 {
4104 	return
4105 		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 */
4106 		(1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
4107 		(
4108 			rice_parameter?
4109 				(unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
4110 				: (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
4111 		)
4112 		- (partition_samples >> 1)
4113 		/* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
4114 		 * The actual number of bits used is closer to the sum(for all i in the partition) of  abs(residual[i])>>(rice_parameter-1)
4115 		 * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
4116 		 * So the subtraction term tries to guess how many extra bits were contributed.
4117 		 * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
4118 		 */
4119 	;
4120 }
4121 #endif
4122 
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)4123 FLAC__bool set_partitioned_rice_(
4124 #ifdef EXACT_RICE_BITS_CALCULATION
4125 	const FLAC__int32 residual[],
4126 #endif
4127 	const FLAC__uint64 abs_residual_partition_sums[],
4128 	const unsigned raw_bits_per_partition[],
4129 	const unsigned residual_samples,
4130 	const unsigned predictor_order,
4131 	const unsigned suggested_rice_parameter,
4132 	const unsigned rice_parameter_limit,
4133 	const unsigned rice_parameter_search_dist,
4134 	const unsigned partition_order,
4135 	const FLAC__bool search_for_escapes,
4136 	FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
4137 	unsigned *bits
4138 )
4139 {
4140 	unsigned rice_parameter, partition_bits;
4141 	unsigned best_partition_bits, best_rice_parameter = 0;
4142 	unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
4143 	unsigned *parameters, *raw_bits;
4144 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4145 	unsigned min_rice_parameter, max_rice_parameter;
4146 #else
4147 	(void)rice_parameter_search_dist;
4148 #endif
4149 
4150 	FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
4151 	FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
4152 
4153 	FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, flac_max(6u, partition_order));
4154 	parameters = partitioned_rice_contents->parameters;
4155 	raw_bits = partitioned_rice_contents->raw_bits;
4156 
4157 	if(partition_order == 0) {
4158 		best_partition_bits = (unsigned)(-1);
4159 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4160 		if(rice_parameter_search_dist) {
4161 			if(suggested_rice_parameter < rice_parameter_search_dist)
4162 				min_rice_parameter = 0;
4163 			else
4164 				min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
4165 			max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
4166 			if(max_rice_parameter >= rice_parameter_limit) {
4167 #ifdef DEBUG_VERBOSE
4168 				fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
4169 #endif
4170 				max_rice_parameter = rice_parameter_limit - 1;
4171 			}
4172 		}
4173 		else
4174 			min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
4175 
4176 		for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4177 #else
4178 			rice_parameter = suggested_rice_parameter;
4179 #endif
4180 #ifdef EXACT_RICE_BITS_CALCULATION
4181 			partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
4182 #else
4183 			partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
4184 #endif
4185 			if(partition_bits < best_partition_bits) {
4186 				best_rice_parameter = rice_parameter;
4187 				best_partition_bits = partition_bits;
4188 			}
4189 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4190 		}
4191 #endif
4192 		if(search_for_escapes) {
4193 			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;
4194 			if(partition_bits <= best_partition_bits) {
4195 				raw_bits[0] = raw_bits_per_partition[0];
4196 				best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4197 				best_partition_bits = partition_bits;
4198 			}
4199 			else
4200 				raw_bits[0] = 0;
4201 		}
4202 		parameters[0] = best_rice_parameter;
4203 		bits_ += best_partition_bits;
4204 	}
4205 	else {
4206 		unsigned partition, residual_sample;
4207 		unsigned partition_samples;
4208 		FLAC__uint64 mean, k;
4209 		const unsigned partitions = 1u << partition_order;
4210 		for(partition = residual_sample = 0; partition < partitions; partition++) {
4211 			partition_samples = (residual_samples+predictor_order) >> partition_order;
4212 			if(partition == 0) {
4213 				if(partition_samples <= predictor_order)
4214 					return false;
4215 				else
4216 					partition_samples -= predictor_order;
4217 			}
4218 			mean = abs_residual_partition_sums[partition];
4219 			/* we are basically calculating the size in bits of the
4220 			 * average residual magnitude in the partition:
4221 			 *   rice_parameter = floor(log2(mean/partition_samples))
4222 			 * 'mean' is not a good name for the variable, it is
4223 			 * actually the sum of magnitudes of all residual values
4224 			 * in the partition, so the actual mean is
4225 			 * mean/partition_samples
4226 			 */
4227 #if 0 /* old simple code */
4228 			for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
4229 				;
4230 #else
4231 #if defined FLAC__CPU_X86_64 /* and other 64-bit arch, too */
4232 			if(mean <= 0x80000000/512) { /* 512: more or less optimal for both 16- and 24-bit input */
4233 #else
4234 			if(mean <= 0x80000000/8) { /* 32-bit arch: use 32-bit math if possible */
4235 #endif
4236 				FLAC__uint32 k2, mean2 = (FLAC__uint32) mean;
4237 				rice_parameter = 0; k2 = partition_samples;
4238 				while(k2*8 < mean2) { /* requires: mean <= (2^31)/8 */
4239 					rice_parameter += 4; k2 <<= 4; /* tuned for 16-bit input */
4240 				}
4241 				while(k2 < mean2) { /* requires: mean <= 2^31 */
4242 					rice_parameter++; k2 <<= 1;
4243 				}
4244 			}
4245 			else {
4246 				rice_parameter = 0; k = partition_samples;
4247 				if(mean <= FLAC__U64L(0x8000000000000000)/128) /* usually mean is _much_ smaller than this value */
4248 					while(k*128 < mean) { /* requires: mean <= (2^63)/128 */
4249 						rice_parameter += 8; k <<= 8; /* tuned for 24-bit input */
4250 					}
4251 				while(k < mean) { /* requires: mean <= 2^63 */
4252 					rice_parameter++; k <<= 1;
4253 				}
4254 			}
4255 #endif
4256 			if(rice_parameter >= rice_parameter_limit) {
4257 #ifdef DEBUG_VERBOSE
4258 				fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
4259 #endif
4260 				rice_parameter = rice_parameter_limit - 1;
4261 			}
4262 
4263 			best_partition_bits = (unsigned)(-1);
4264 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4265 			if(rice_parameter_search_dist) {
4266 				if(rice_parameter < rice_parameter_search_dist)
4267 					min_rice_parameter = 0;
4268 				else
4269 					min_rice_parameter = rice_parameter - rice_parameter_search_dist;
4270 				max_rice_parameter = rice_parameter + rice_parameter_search_dist;
4271 				if(max_rice_parameter >= rice_parameter_limit) {
4272 #ifdef DEBUG_VERBOSE
4273 					fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
4274 #endif
4275 					max_rice_parameter = rice_parameter_limit - 1;
4276 				}
4277 			}
4278 			else
4279 				min_rice_parameter = max_rice_parameter = rice_parameter;
4280 
4281 			for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4282 #endif
4283 #ifdef EXACT_RICE_BITS_CALCULATION
4284 				partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
4285 #else
4286 				partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
4287 #endif
4288 				if(partition_bits < best_partition_bits) {
4289 					best_rice_parameter = rice_parameter;
4290 					best_partition_bits = partition_bits;
4291 				}
4292 #ifdef ENABLE_RICE_PARAMETER_SEARCH
4293 			}
4294 #endif
4295 			if(search_for_escapes) {
4296 				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;
4297 				if(partition_bits <= best_partition_bits) {
4298 					raw_bits[partition] = raw_bits_per_partition[partition];
4299 					best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4300 					best_partition_bits = partition_bits;
4301 				}
4302 				else
4303 					raw_bits[partition] = 0;
4304 			}
4305 			parameters[partition] = best_rice_parameter;
4306 			bits_ += best_partition_bits;
4307 			residual_sample += partition_samples;
4308 		}
4309 	}
4310 
4311 	*bits = bits_;
4312 	return true;
4313 }
4314 
4315 unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
4316 {
4317 	unsigned i, shift;
4318 	FLAC__int32 x = 0;
4319 
4320 	for(i = 0; i < samples && !(x&1); i++)
4321 		x |= signal[i];
4322 
4323 	if(x == 0) {
4324 		shift = 0;
4325 	}
4326 	else {
4327 		for(shift = 0; !(x&1); shift++)
4328 			x >>= 1;
4329 	}
4330 
4331 	if(shift > 0) {
4332 		for(i = 0; i < samples; i++)
4333 			 signal[i] >>= shift;
4334 	}
4335 
4336 	return shift;
4337 }
4338 
4339 void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4340 {
4341 	unsigned channel;
4342 
4343 	for(channel = 0; channel < channels; channel++)
4344 		memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
4345 
4346 	fifo->tail += wide_samples;
4347 
4348 	FLAC__ASSERT(fifo->tail <= fifo->size);
4349 }
4350 
4351 void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4352 {
4353 	unsigned channel;
4354 	unsigned sample, wide_sample;
4355 	unsigned tail = fifo->tail;
4356 
4357 	sample = input_offset * channels;
4358 	for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
4359 		for(channel = 0; channel < channels; channel++)
4360 			fifo->data[channel][tail] = input[sample++];
4361 		tail++;
4362 	}
4363 	fifo->tail = tail;
4364 
4365 	FLAC__ASSERT(fifo->tail <= fifo->size);
4366 }
4367 
4368 FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4369 {
4370 	FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4371 	const size_t encoded_bytes = encoder->private_->verify.output.bytes;
4372 	(void)decoder;
4373 
4374 	if(encoder->private_->verify.needs_magic_hack) {
4375 		FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
4376 		*bytes = FLAC__STREAM_SYNC_LENGTH;
4377 		memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
4378 		encoder->private_->verify.needs_magic_hack = false;
4379 	}
4380 	else {
4381 		if(encoded_bytes == 0) {
4382 			/*
4383 			 * If we get here, a FIFO underflow has occurred,
4384 			 * which means there is a bug somewhere.
4385 			 */
4386 			FLAC__ASSERT(0);
4387 			return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
4388 		}
4389 		else if(encoded_bytes < *bytes)
4390 			*bytes = encoded_bytes;
4391 		memcpy(buffer, encoder->private_->verify.output.data, *bytes);
4392 		encoder->private_->verify.output.data += *bytes;
4393 		encoder->private_->verify.output.bytes -= *bytes;
4394 	}
4395 
4396 	return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
4397 }
4398 
4399 FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
4400 {
4401 	FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
4402 	unsigned channel;
4403 	const unsigned channels = frame->header.channels;
4404 	const unsigned blocksize = frame->header.blocksize;
4405 	const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
4406 
4407 	(void)decoder;
4408 
4409 	for(channel = 0; channel < channels; channel++) {
4410 		if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
4411 			unsigned i, sample = 0;
4412 			FLAC__int32 expect = 0, got = 0;
4413 
4414 			for(i = 0; i < blocksize; i++) {
4415 				if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
4416 					sample = i;
4417 					expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
4418 					got = (FLAC__int32)buffer[channel][i];
4419 					break;
4420 				}
4421 			}
4422 			FLAC__ASSERT(i < blocksize);
4423 			FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
4424 			encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
4425 			encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
4426 			encoder->private_->verify.error_stats.channel = channel;
4427 			encoder->private_->verify.error_stats.sample = sample;
4428 			encoder->private_->verify.error_stats.expected = expect;
4429 			encoder->private_->verify.error_stats.got = got;
4430 			encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
4431 			return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
4432 		}
4433 	}
4434 	/* dequeue the frame from the fifo */
4435 	encoder->private_->verify.input_fifo.tail -= blocksize;
4436 	FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
4437 	for(channel = 0; channel < channels; channel++)
4438 		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]));
4439 	return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4440 }
4441 
4442 void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4443 {
4444 	(void)decoder, (void)metadata, (void)client_data;
4445 }
4446 
4447 void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4448 {
4449 	FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4450 	(void)decoder, (void)status;
4451 	encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4452 }
4453 
4454 FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4455 {
4456 	(void)client_data;
4457 
4458 	*bytes = fread(buffer, 1, *bytes, encoder->private_->file);
4459 	if (*bytes == 0) {
4460 		if (feof(encoder->private_->file))
4461 			return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
4462 		else if (ferror(encoder->private_->file))
4463 			return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
4464 	}
4465 	return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
4466 }
4467 
4468 FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4469 {
4470 	(void)client_data;
4471 
4472 	if(fseeko(encoder->private_->file, (FLAC__off_t)absolute_byte_offset, SEEK_SET) < 0)
4473 		return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4474 	else
4475 		return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4476 }
4477 
4478 FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4479 {
4480 	FLAC__off_t offset;
4481 
4482 	(void)client_data;
4483 
4484 	offset = ftello(encoder->private_->file);
4485 
4486 	if(offset < 0) {
4487 		return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4488 	}
4489 	else {
4490 		*absolute_byte_offset = (FLAC__uint64)offset;
4491 		return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4492 	}
4493 }
4494 
4495 #ifdef FLAC__VALGRIND_TESTING
4496 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4497 {
4498 	size_t ret = fwrite(ptr, size, nmemb, stream);
4499 	if(!ferror(stream))
4500 		fflush(stream);
4501 	return ret;
4502 }
4503 #else
4504 #define local__fwrite fwrite
4505 #endif
4506 
4507 FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
4508 {
4509 	(void)client_data, (void)current_frame;
4510 
4511 	if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4512 		FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
4513 #if FLAC__HAS_OGG
4514 			/* We would like to be able to use 'samples > 0' in the
4515 			 * clause here but currently because of the nature of our
4516 			 * Ogg writing implementation, 'samples' is always 0 (see
4517 			 * ogg_encoder_aspect.c).  The downside is extra progress
4518 			 * callbacks.
4519 			 */
4520 			encoder->private_->is_ogg? true :
4521 #endif
4522 			samples > 0
4523 		);
4524 		if(call_it) {
4525 			/* NOTE: We have to add +bytes, +samples, and +1 to the stats
4526 			 * because at this point in the callback chain, the stats
4527 			 * have not been updated.  Only after we return and control
4528 			 * gets back to write_frame_() are the stats updated
4529 			 */
4530 			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);
4531 		}
4532 		return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4533 	}
4534 	else
4535 		return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4536 }
4537 
4538 /*
4539  * This will forcibly set stdout to binary mode (for OSes that require it)
4540  */
4541 FILE *get_binary_stdout_(void)
4542 {
4543 	/* if something breaks here it is probably due to the presence or
4544 	 * absence of an underscore before the identifiers 'setmode',
4545 	 * 'fileno', and/or 'O_BINARY'; check your system header files.
4546 	 */
4547 #if defined _MSC_VER || defined __MINGW32__
4548 	_setmode(_fileno(stdout), _O_BINARY);
4549 #elif defined __CYGWIN__
4550 	/* almost certainly not needed for any modern Cygwin, but let's be safe... */
4551 	setmode(_fileno(stdout), _O_BINARY);
4552 #elif defined __EMX__
4553 	setmode(fileno(stdout), O_BINARY);
4554 #endif
4555 
4556 	return stdout;
4557 }
4558