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