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