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