b1167cb3ea7d1fd3db00d5b36ac403856bd9c43f
[platform/upstream/libsndfile.git] / src / flac.c
1 /*
2 ** Copyright (C) 2004-2014 Erik de Castro Lopo <erikd@mega-nerd.com>
3 ** Copyright (C) 2004 Tobias Gehrig <tgehrig@ira.uka.de>
4 **
5 ** This program is free software ; you can redistribute it and/or modify
6 ** it under the terms of the GNU Lesser General Public License as published by
7 ** the Free Software Foundation ; either version 2.1 of the License, or
8 ** (at your option) any later version.
9 **
10 ** This program is distributed in the hope that it will be useful,
11 ** but WITHOUT ANY WARRANTY ; without even the implied warranty of
12 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 ** GNU Lesser General Public License for more details.
14 **
15 ** You should have received a copy of the GNU Lesser General Public License
16 ** along with this program ; if not, write to the Free Software
17 ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 */
19
20 #include        "sfconfig.h"
21
22 #include        <stdio.h>
23 #include        <stdlib.h>
24 #include        <fcntl.h>
25 #include        <string.h>
26 #include        <ctype.h>
27 #include        <math.h>
28
29 #include        "sndfile.h"
30 #include        "common.h"
31
32 #if 0  /* HAVE_EXTERNAL_LIBS : Disable for TIZEN */
33
34 #include        <FLAC/stream_decoder.h>
35 #include        <FLAC/stream_encoder.h>
36 #include        <FLAC/metadata.h>
37
38 /*------------------------------------------------------------------------------
39 ** Private static functions.
40 */
41
42 #define FLAC_DEFAULT_COMPRESSION_LEVEL  5
43
44 #define ENC_BUFFER_SIZE 8192
45
46 typedef enum
47 {       PFLAC_PCM_SHORT = 50,
48         PFLAC_PCM_INT = 51,
49         PFLAC_PCM_FLOAT = 52,
50         PFLAC_PCM_DOUBLE = 53
51 } PFLAC_PCM ;
52
53 typedef struct
54 {
55         FLAC__StreamDecoder *fsd ;
56         FLAC__StreamEncoder *fse ;
57
58         PFLAC_PCM pcmtype ;
59         void* ptr ;
60         unsigned pos, len, remain ;
61
62         FLAC__StreamMetadata *metadata ;
63
64         const FLAC__int32 * const * wbuffer ;
65         FLAC__int32 * rbuffer [FLAC__MAX_CHANNELS] ;
66
67         FLAC__int32* encbuffer ;
68         unsigned bufferpos ;
69
70         const FLAC__Frame *frame ;
71
72         unsigned compression ;
73
74 } FLAC_PRIVATE ;
75
76 typedef struct
77 {       const char *tag ;
78         int type ;
79 } FLAC_TAG ;
80
81 static sf_count_t       flac_seek (SF_PRIVATE *psf, int mode, sf_count_t offset) ;
82 static int                      flac_byterate (SF_PRIVATE *psf) ;
83 static int                      flac_close (SF_PRIVATE *psf) ;
84
85 static int                      flac_enc_init (SF_PRIVATE *psf) ;
86 static int                      flac_read_header (SF_PRIVATE *psf) ;
87
88 static sf_count_t       flac_read_flac2s (SF_PRIVATE *psf, short *ptr, sf_count_t len) ;
89 static sf_count_t       flac_read_flac2i (SF_PRIVATE *psf, int *ptr, sf_count_t len) ;
90 static sf_count_t       flac_read_flac2f (SF_PRIVATE *psf, float *ptr, sf_count_t len) ;
91 static sf_count_t       flac_read_flac2d (SF_PRIVATE *psf, double *ptr, sf_count_t len) ;
92
93 static sf_count_t       flac_write_s2flac (SF_PRIVATE *psf, const short *ptr, sf_count_t len) ;
94 static sf_count_t       flac_write_i2flac (SF_PRIVATE *psf, const int *ptr, sf_count_t len) ;
95 static sf_count_t       flac_write_f2flac (SF_PRIVATE *psf, const float *ptr, sf_count_t len) ;
96 static sf_count_t       flac_write_d2flac (SF_PRIVATE *psf, const double *ptr, sf_count_t len) ;
97
98 static void             f2flac8_array (const float *src, FLAC__int32 *dest, int count, int normalize) ;
99 static void             f2flac16_array (const float *src, FLAC__int32 *dest, int count, int normalize) ;
100 static void             f2flac24_array (const float *src, FLAC__int32 *dest, int count, int normalize) ;
101 static void             f2flac8_clip_array (const float *src, FLAC__int32 *dest, int count, int normalize) ;
102 static void             f2flac16_clip_array (const float *src, FLAC__int32 *dest, int count, int normalize) ;
103 static void             f2flac24_clip_array (const float *src, FLAC__int32 *dest, int count, int normalize) ;
104 static void             d2flac8_array (const double *src, FLAC__int32 *dest, int count, int normalize) ;
105 static void             d2flac16_array (const double *src, FLAC__int32 *dest, int count, int normalize) ;
106 static void             d2flac24_array (const double *src, FLAC__int32 *dest, int count, int normalize) ;
107 static void             d2flac8_clip_array (const double *src, FLAC__int32 *dest, int count, int normalize) ;
108 static void             d2flac16_clip_array (const double *src, FLAC__int32 *dest, int count, int normalize) ;
109 static void             d2flac24_clip_array (const double *src, FLAC__int32 *dest, int count, int normalize) ;
110
111 static int flac_command (SF_PRIVATE *psf, int command, void *data, int datasize) ;
112
113 /* Decoder Callbacks */
114 static FLAC__StreamDecoderReadStatus sf_flac_read_callback (const FLAC__StreamDecoder *decoder, FLAC__byte buffer [], size_t *bytes, void *client_data) ;
115 static FLAC__StreamDecoderSeekStatus sf_flac_seek_callback (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data) ;
116 static FLAC__StreamDecoderTellStatus sf_flac_tell_callback (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data) ;
117 static FLAC__StreamDecoderLengthStatus sf_flac_length_callback (const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data) ;
118 static FLAC__bool sf_flac_eof_callback (const FLAC__StreamDecoder *decoder, void *client_data) ;
119 static FLAC__StreamDecoderWriteStatus sf_flac_write_callback (const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer [], void *client_data) ;
120 static void sf_flac_meta_callback (const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data) ;
121 static void sf_flac_error_callback (const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data) ;
122
123 /* Encoder Callbacks */
124 static FLAC__StreamEncoderSeekStatus sf_flac_enc_seek_callback (const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data) ;
125 static FLAC__StreamEncoderTellStatus sf_flac_enc_tell_callback (const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data) ;
126 static FLAC__StreamEncoderWriteStatus sf_flac_enc_write_callback (const FLAC__StreamEncoder *encoder, const FLAC__byte buffer [], size_t bytes, unsigned samples, unsigned current_frame, void *client_data) ;
127
128 static void
129 s2flac8_array (const short *src, FLAC__int32 *dest, int count)
130 {       while (--count >= 0)
131                 dest [count] = src [count] >> 8 ;
132 } /* s2flac8_array */
133
134 static void
135 s2flac16_array (const short *src, FLAC__int32 *dest, int count)
136 {       while (--count >= 0)
137                 dest [count] = src [count] ;
138 } /* s2flac16_array */
139
140 static void
141 s2flac24_array (const short *src, FLAC__int32 *dest, int count)
142 {       while (--count >= 0)
143                 dest [count] = src [count] << 8 ;
144 } /* s2flac24_array */
145
146 static void
147 i2flac8_array (const int *src, FLAC__int32 *dest, int count)
148 {       while (--count >= 0)
149                 dest [count] = src [count] >> 24 ;
150 } /* i2flac8_array */
151
152 static void
153 i2flac16_array (const int *src, FLAC__int32 *dest, int count)
154 {
155         while (--count >= 0)
156                 dest [count] = src [count] >> 16 ;
157 } /* i2flac16_array */
158
159 static void
160 i2flac24_array (const int *src, FLAC__int32 *dest, int count)
161 {       while (--count >= 0)
162                 dest [count] = src [count] >> 8 ;
163 } /* i2flac24_array */
164
165 static sf_count_t
166 flac_buffer_copy (SF_PRIVATE *psf)
167 {       FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
168         const FLAC__Frame *frame = pflac->frame ;
169         const FLAC__int32* const *buffer = pflac->wbuffer ;
170         unsigned i = 0, j, offset ;
171
172         /*
173         **      frame->header.blocksize is variable and we're using a constant blocksize
174         **      of FLAC__MAX_BLOCK_SIZE.
175         **      Check our assumptions here.
176         */
177         if (frame->header.blocksize > FLAC__MAX_BLOCK_SIZE)
178         {       psf_log_printf (psf, "Ooops : frame->header.blocksize (%d) > FLAC__MAX_BLOCK_SIZE (%d)\n", __func__, __LINE__, frame->header.blocksize, FLAC__MAX_BLOCK_SIZE) ;
179                 psf->error = SFE_INTERNAL ;
180                 return 0 ;
181                 } ;
182
183         if (pflac->ptr == NULL)
184         {       /*
185                 ** This pointer is reset to NULL each time the current frame has been
186                 ** decoded. Somehow its used during encoding and decoding.
187                 */
188                 for (i = 0 ; i < frame->header.channels ; i++)
189                 {
190                         if (pflac->rbuffer [i] == NULL)
191                                 pflac->rbuffer [i] = calloc (FLAC__MAX_BLOCK_SIZE, sizeof (FLAC__int32)) ;
192
193                         memcpy (pflac->rbuffer [i], buffer [i], frame->header.blocksize * sizeof (FLAC__int32)) ;
194                         } ;
195                 pflac->wbuffer = (const FLAC__int32* const*) pflac->rbuffer ;
196
197                 return 0 ;
198                 } ;
199
200         if (pflac->remain % channels != 0)
201         {       psf_log_printf (psf, "Error: pflac->remain %u    channels %u\n", pflac->remain, channels) ;
202                 return 0 ;
203                 } ;
204
205         switch (pflac->pcmtype)
206         {       case PFLAC_PCM_SHORT :
207                         {       short *retpcm = (short*) pflac->ptr ;
208                                 int shift = 16 - frame->header.bits_per_sample ;
209                                 if (shift < 0)
210                                 {       shift = abs (shift) ;
211                                         for (i = 0 ; i < frame->header.blocksize && pflac->remain > 0 ; i++)
212                                         {       offset = pflac->pos + i * frame->header.channels ;
213
214                                                 if (pflac->bufferpos >= frame->header.blocksize)
215                                                         break ;
216
217                                                 for (j = 0 ; j < frame->header.channels ; j++)
218                                                         retpcm [offset + j] = buffer [j][pflac->bufferpos] >> shift ;
219                                                 pflac->remain -= frame->header.channels ;
220                                                 pflac->bufferpos++ ;
221                                                 }
222                                         }
223                                 else
224                                 {       for (i = 0 ; i < frame->header.blocksize && pflac->remain > 0 ; i++)
225                                         {       offset = pflac->pos + i * frame->header.channels ;
226
227                                                 if (pflac->bufferpos >= frame->header.blocksize)
228                                                         break ;
229
230                                                 for (j = 0 ; j < frame->header.channels ; j++)
231                                                         retpcm [offset + j] = ((uint16_t) buffer [j][pflac->bufferpos]) << shift ;
232
233                                                 pflac->remain -= frame->header.channels ;
234                                                 pflac->bufferpos++ ;
235                                                 } ;
236                                         } ;
237                                 } ;
238                         break ;
239
240                 case PFLAC_PCM_INT :
241                         {       int *retpcm = (int*) pflac->ptr ;
242                                 int shift = 32 - frame->header.bits_per_sample ;
243                                 for (i = 0 ; i < frame->header.blocksize && pflac->remain > 0 ; i++)
244                                 {       offset = pflac->pos + i * frame->header.channels ;
245
246                                         if (pflac->bufferpos >= frame->header.blocksize)
247                                                 break ;
248
249                                         for (j = 0 ; j < frame->header.channels ; j++)
250                                                 retpcm [offset + j] = ((uint32_t) buffer [j][pflac->bufferpos]) << shift ;
251                                         pflac->remain -= frame->header.channels ;
252                                         pflac->bufferpos++ ;
253                                         } ;
254                                 } ;
255                         break ;
256
257                 case PFLAC_PCM_FLOAT :
258                         {       float *retpcm = (float*) pflac->ptr ;
259                                 float norm = (psf->norm_float == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ;
260
261                                 for (i = 0 ; i < frame->header.blocksize && pflac->remain > 0 ; i++)
262                                 {       offset = pflac->pos + i * frame->header.channels ;
263
264                                         if (pflac->bufferpos >= frame->header.blocksize)
265                                                 break ;
266
267                                         for (j = 0 ; j < frame->header.channels ; j++)
268                                                 retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ;
269                                         pflac->remain -= frame->header.channels ;
270                                         pflac->bufferpos++ ;
271                                         } ;
272                                 } ;
273                         break ;
274
275                 case PFLAC_PCM_DOUBLE :
276                         {       double *retpcm = (double*) pflac->ptr ;
277                                 double norm = (psf->norm_double == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ;
278
279                                 for (i = 0 ; i < frame->header.blocksize && pflac->remain > 0 ; i++)
280                                 {       offset = pflac->pos + i * frame->header.channels ;
281
282                                         if (pflac->bufferpos >= frame->header.blocksize)
283                                                 break ;
284
285                                         for (j = 0 ; j < frame->header.channels ; j++)
286                                                 retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ;
287                                         pflac->remain -= frame->header.channels ;
288                                         pflac->bufferpos++ ;
289                                         } ;
290                                 } ;
291                         break ;
292
293                 default :
294                         return 0 ;
295                 } ;
296
297         offset = i * frame->header.channels ;
298         pflac->pos += i * frame->header.channels ;
299
300         return offset ;
301 } /* flac_buffer_copy */
302
303
304 static FLAC__StreamDecoderReadStatus
305 sf_flac_read_callback (const FLAC__StreamDecoder * UNUSED (decoder), FLAC__byte buffer [], size_t *bytes, void *client_data)
306 {       SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
307
308         *bytes = psf_fread (buffer, 1, *bytes, psf) ;
309         if (*bytes > 0 && psf->error == 0)
310                 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE ;
311
312         return FLAC__STREAM_DECODER_READ_STATUS_ABORT ;
313 } /* sf_flac_read_callback */
314
315 static FLAC__StreamDecoderSeekStatus
316 sf_flac_seek_callback (const FLAC__StreamDecoder * UNUSED (decoder), FLAC__uint64 absolute_byte_offset, void *client_data)
317 {       SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
318
319         psf_fseek (psf, absolute_byte_offset, SEEK_SET) ;
320         if (psf->error)
321                 return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR ;
322
323         return FLAC__STREAM_DECODER_SEEK_STATUS_OK ;
324 } /* sf_flac_seek_callback */
325
326 static FLAC__StreamDecoderTellStatus
327 sf_flac_tell_callback (const FLAC__StreamDecoder * UNUSED (decoder), FLAC__uint64 *absolute_byte_offset, void *client_data)
328 {       SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
329
330         *absolute_byte_offset = psf_ftell (psf) ;
331         if (psf->error)
332                 return FLAC__STREAM_DECODER_TELL_STATUS_ERROR ;
333
334         return FLAC__STREAM_DECODER_TELL_STATUS_OK ;
335 } /* sf_flac_tell_callback */
336
337 static FLAC__StreamDecoderLengthStatus
338 sf_flac_length_callback (const FLAC__StreamDecoder * UNUSED (decoder), FLAC__uint64 *stream_length, void *client_data)
339 {       SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
340
341         if ((*stream_length = psf->filelength) == 0)
342                 return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR ;
343
344         return FLAC__STREAM_DECODER_LENGTH_STATUS_OK ;
345 } /* sf_flac_length_callback */
346
347 static FLAC__bool
348 sf_flac_eof_callback (const FLAC__StreamDecoder *UNUSED (decoder), void *client_data)
349 {       SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
350
351         if (psf_ftell (psf) == psf->filelength)
352                 return SF_TRUE ;
353
354         return SF_FALSE ;
355 } /* sf_flac_eof_callback */
356
357 static FLAC__StreamDecoderWriteStatus
358 sf_flac_write_callback (const FLAC__StreamDecoder * UNUSED (decoder), const FLAC__Frame *frame, const FLAC__int32 * const buffer [], void *client_data)
359 {       SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
360         FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
361
362         pflac->frame = frame ;
363         pflac->bufferpos = 0 ;
364
365         pflac->wbuffer = buffer ;
366
367         flac_buffer_copy (psf) ;
368
369         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE ;
370 } /* sf_flac_write_callback */
371
372 static void
373 sf_flac_meta_get_vorbiscomments (SF_PRIVATE *psf, const FLAC__StreamMetadata *metadata)
374 {       FLAC_TAG tags [] =
375         {       { "title", SF_STR_TITLE },
376                 { "copyright", SF_STR_COPYRIGHT },
377                 { "software", SF_STR_SOFTWARE },
378                 { "artist", SF_STR_ARTIST },
379                 { "comment", SF_STR_COMMENT },
380                 { "date", SF_STR_DATE },
381                 { "album", SF_STR_ALBUM },
382                 { "license", SF_STR_LICENSE },
383                 { "tracknumber", SF_STR_TRACKNUMBER },
384                 { "genre", SF_STR_GENRE }
385                 } ;
386
387         const char *value, *cptr ;
388         int k, tag_num ;
389
390         for (k = 0 ; k < ARRAY_LEN (tags) ; k++)
391         {       tag_num = FLAC__metadata_object_vorbiscomment_find_entry_from (metadata, 0, tags [k].tag) ;
392
393                 if (tag_num < 0)
394                         continue ;
395
396                 value = (const char*) metadata->data.vorbis_comment.comments [tag_num].entry ;
397                 if ((cptr = strchr (value, '=')) != NULL)
398                         value = cptr + 1 ;
399
400                 psf_log_printf (psf, "  %-10s : %s\n", tags [k].tag, value) ;
401                 psf_store_string (psf, tags [k].type, value) ;
402                 } ;
403
404         return ;
405 } /* sf_flac_meta_get_vorbiscomments */
406
407 static void
408 sf_flac_meta_callback (const FLAC__StreamDecoder * UNUSED (decoder), const FLAC__StreamMetadata *metadata, void *client_data)
409 {       SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
410         int bitwidth = 0 ;
411
412         switch (metadata->type)
413         {       case FLAC__METADATA_TYPE_STREAMINFO :
414                         psf->sf.channels = metadata->data.stream_info.channels ;
415                         psf->sf.samplerate = metadata->data.stream_info.sample_rate ;
416                         psf->sf.frames = metadata->data.stream_info.total_samples ;
417
418                         psf_log_printf (psf, "FLAC Stream Metadata\n  Channels    : %d\n  Sample rate : %d\n", psf->sf.channels, psf->sf.samplerate) ;
419
420                         if (psf->sf.frames == 0)
421                         {       psf_log_printf (psf, "  Frames      : 0 (bumping to SF_COUNT_MAX)\n") ;
422                                 psf->sf.frames = SF_COUNT_MAX ;
423                                 }
424                         else
425                                 psf_log_printf (psf, "  Frames      : %D\n", psf->sf.frames) ;
426
427                         switch (metadata->data.stream_info.bits_per_sample)
428                         {       case 8 :
429                                         psf->sf.format |= SF_FORMAT_PCM_S8 ;
430                                         bitwidth = 8 ;
431                                         break ;
432                                 case 16 :
433                                         psf->sf.format |= SF_FORMAT_PCM_16 ;
434                                         bitwidth = 16 ;
435                                         break ;
436                                 case 24 :
437                                         psf->sf.format |= SF_FORMAT_PCM_24 ;
438                                         bitwidth = 24 ;
439                                         break ;
440                                 default :
441                                         psf_log_printf (psf, "sf_flac_meta_callback : bits_per_sample %d not yet implemented.\n", metadata->data.stream_info.bits_per_sample) ;
442                                         break ;
443                                 } ;
444
445                         if (bitwidth > 0)
446                                 psf_log_printf (psf, "  Bit width   : %d\n", bitwidth) ;
447                         break ;
448
449                 case FLAC__METADATA_TYPE_VORBIS_COMMENT :
450                         psf_log_printf (psf, "Vorbis Comment Metadata\n") ;
451                         sf_flac_meta_get_vorbiscomments (psf, metadata) ;
452                         break ;
453
454                 case FLAC__METADATA_TYPE_PADDING :
455                         psf_log_printf (psf, "Padding Metadata\n") ;
456                         break ;
457
458                 case FLAC__METADATA_TYPE_APPLICATION :
459                         psf_log_printf (psf, "Application Metadata\n") ;
460                         break ;
461
462                 case FLAC__METADATA_TYPE_SEEKTABLE :
463                         psf_log_printf (psf, "Seektable Metadata\n") ;
464                         break ;
465
466                 case FLAC__METADATA_TYPE_CUESHEET :
467                         psf_log_printf (psf, "Cuesheet Metadata\n") ;
468                         break ;
469
470                 case FLAC__METADATA_TYPE_PICTURE :
471                         psf_log_printf (psf, "Picture Metadata\n") ;
472                         break ;
473
474                 case FLAC__METADATA_TYPE_UNDEFINED :
475                         psf_log_printf (psf, "Undefined Metadata\n") ;
476                         break ;
477
478                 default :
479                         psf_log_printf (psf, "sf_flac_meta_callback : metadata-type %d not yet implemented.\n", metadata->type) ;
480                         break ;
481                 } ;
482
483         return ;
484 } /* sf_flac_meta_callback */
485
486 static void
487 sf_flac_error_callback (const FLAC__StreamDecoder * UNUSED (decoder), FLAC__StreamDecoderErrorStatus status, void *client_data)
488 {       SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
489
490         psf_log_printf (psf, "ERROR : %s\n", FLAC__StreamDecoderErrorStatusString [status]) ;
491
492         switch (status)
493         {       case FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC :
494                         psf->error = SFE_FLAC_LOST_SYNC ;
495                         break ;
496                 case FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER :
497                         psf->error = SFE_FLAC_BAD_HEADER ;
498                         break ;
499                 default :
500                         psf->error = SFE_FLAC_UNKOWN_ERROR ;
501                         break ;
502                 } ;
503
504         return ;
505 } /* sf_flac_error_callback */
506
507 static FLAC__StreamEncoderSeekStatus
508 sf_flac_enc_seek_callback (const FLAC__StreamEncoder * UNUSED (encoder), FLAC__uint64 absolute_byte_offset, void *client_data)
509 {       SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
510
511         psf_fseek (psf, absolute_byte_offset, SEEK_SET) ;
512         if (psf->error)
513                 return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR ;
514
515         return FLAC__STREAM_ENCODER_SEEK_STATUS_OK ;
516 } /* sf_flac_enc_seek_callback */
517
518 static FLAC__StreamEncoderTellStatus
519 sf_flac_enc_tell_callback (const FLAC__StreamEncoder *UNUSED (encoder), FLAC__uint64 *absolute_byte_offset, void *client_data)
520 {       SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
521
522         *absolute_byte_offset = psf_ftell (psf) ;
523         if (psf->error)
524                 return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR ;
525
526         return FLAC__STREAM_ENCODER_TELL_STATUS_OK ;
527 } /* sf_flac_enc_tell_callback */
528
529 static FLAC__StreamEncoderWriteStatus
530 sf_flac_enc_write_callback (const FLAC__StreamEncoder * UNUSED (encoder), const FLAC__byte buffer [], size_t bytes, unsigned UNUSED (samples), unsigned UNUSED (current_frame), void *client_data)
531 {       SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
532
533         if (psf_fwrite (buffer, 1, bytes, psf) == (sf_count_t) bytes && psf->error == 0)
534                 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK ;
535
536         return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR ;
537 } /* sf_flac_enc_write_callback */
538
539 static void
540 flac_write_strings (SF_PRIVATE *psf, FLAC_PRIVATE* pflac)
541 {       FLAC__StreamMetadata_VorbisComment_Entry entry ;
542         int     k, string_count = 0 ;
543
544         for (k = 0 ; k < SF_MAX_STRINGS ; k++)
545         {       if (psf->strings.data [k].type != 0)
546                         string_count ++ ;
547                 } ;
548
549         if (string_count == 0)
550                 return ;
551
552         if (pflac->metadata == NULL && (pflac->metadata = FLAC__metadata_object_new (FLAC__METADATA_TYPE_VORBIS_COMMENT)) == NULL)
553         {       psf_log_printf (psf, "FLAC__metadata_object_new returned NULL\n") ;
554                 return ;
555                 } ;
556
557         for (k = 0 ; k < SF_MAX_STRINGS && psf->strings.data [k].type != 0 ; k++)
558         {       const char * key, * value ;
559
560                 switch (psf->strings.data [k].type)
561                 {       case SF_STR_SOFTWARE :
562                                 key = "software" ;
563                                 break ;
564                         case SF_STR_TITLE :
565                                 key = "title" ;
566                                 break ;
567                         case SF_STR_COPYRIGHT :
568                                 key = "copyright" ;
569                                 break ;
570                         case SF_STR_ARTIST :
571                                 key = "artist" ;
572                                 break ;
573                         case SF_STR_COMMENT :
574                                 key = "comment" ;
575                                 break ;
576                         case SF_STR_DATE :
577                                 key = "date" ;
578                                 break ;
579                         case SF_STR_ALBUM :
580                                 key = "album" ;
581                                 break ;
582                         case SF_STR_LICENSE :
583                                 key = "license" ;
584                                 break ;
585                         case SF_STR_TRACKNUMBER :
586                                 key = "tracknumber" ;
587                                 break ;
588                         case SF_STR_GENRE :
589                                 key = "genre" ;
590                                 break ;
591                         default :
592                                 continue ;
593                         } ;
594
595                 value = psf->strings.storage + psf->strings.data [k].offset ;
596
597                 FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair (&entry, key, value) ;
598                 FLAC__metadata_object_vorbiscomment_append_comment (pflac->metadata, entry, /* copy */ SF_FALSE) ;
599                 } ;
600
601         if (! FLAC__stream_encoder_set_metadata (pflac->fse, &pflac->metadata, 1))
602         {       printf ("%s %d : fail\n", __func__, __LINE__) ;
603                 return ;
604                 } ;
605
606         return ;
607 } /* flac_write_strings */
608
609 static int
610 flac_write_header (SF_PRIVATE *psf, int UNUSED (calc_length))
611 {       FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
612         int err ;
613
614         flac_write_strings (psf, pflac) ;
615
616         if ((err = FLAC__stream_encoder_init_stream (pflac->fse, sf_flac_enc_write_callback, sf_flac_enc_seek_callback, sf_flac_enc_tell_callback, NULL, psf)) != FLAC__STREAM_DECODER_INIT_STATUS_OK)
617         {       psf_log_printf (psf, "Error : FLAC encoder init returned error : %s\n", FLAC__StreamEncoderInitStatusString [err]) ;
618                 return SFE_FLAC_INIT_DECODER ;
619                 } ;
620
621         if (psf->error == 0)
622                 psf->dataoffset = psf_ftell (psf) ;
623         pflac->encbuffer = calloc (ENC_BUFFER_SIZE, sizeof (FLAC__int32)) ;
624
625         return psf->error ;
626 } /* flac_write_header */
627
628 /*------------------------------------------------------------------------------
629 ** Public function.
630 */
631
632 int
633 flac_open       (SF_PRIVATE *psf)
634 {       int             subformat ;
635         int             error = 0 ;
636
637         FLAC_PRIVATE* pflac = calloc (1, sizeof (FLAC_PRIVATE)) ;
638         psf->codec_data = pflac ;
639
640         /* Set the default value here. Over-ridden later if necessary. */
641         pflac->compression = FLAC_DEFAULT_COMPRESSION_LEVEL ;
642
643
644         if (psf->file.mode == SFM_RDWR)
645                 return SFE_BAD_MODE_RW ;
646
647         if (psf->file.mode == SFM_READ)
648         {       if ((error = flac_read_header (psf)))
649                         return error ;
650                 } ;
651
652         subformat = SF_CODEC (psf->sf.format) ;
653
654         if (psf->file.mode == SFM_WRITE)
655         {       if ((SF_CONTAINER (psf->sf.format)) != SF_FORMAT_FLAC)
656                         return  SFE_BAD_OPEN_FORMAT ;
657
658                 psf->endian = SF_ENDIAN_BIG ;
659                 psf->sf.seekable = 0 ;
660
661                 psf->strings.flags = SF_STR_ALLOW_START ;
662
663                 if ((error = flac_enc_init (psf)))
664                         return error ;
665
666                 psf->write_header = flac_write_header ;
667                 } ;
668
669         psf->datalength = psf->filelength ;
670         psf->dataoffset = 0 ;
671
672         psf->container_close = flac_close ;
673         psf->seek = flac_seek ;
674         psf->byterate = flac_byterate ;
675
676         psf->command = flac_command ;
677
678         switch (subformat)
679         {       case SF_FORMAT_PCM_S8 : /* 8-bit FLAC.  */
680                 case SF_FORMAT_PCM_16 : /* 16-bit FLAC. */
681                 case SF_FORMAT_PCM_24 : /* 24-bit FLAC. */
682                         error = flac_init (psf) ;
683                         break ;
684
685                 default : return SFE_UNIMPLEMENTED ;
686                 } ;
687
688         return error ;
689 } /* flac_open */
690
691 /*------------------------------------------------------------------------------
692 */
693
694 static int
695 flac_close      (SF_PRIVATE *psf)
696 {       FLAC_PRIVATE* pflac ;
697         int k ;
698
699         if ((pflac = (FLAC_PRIVATE*) psf->codec_data) == NULL)
700                 return 0 ;
701
702         if (pflac->metadata != NULL)
703                 FLAC__metadata_object_delete (pflac->metadata) ;
704
705         if (psf->file.mode == SFM_WRITE)
706         {       FLAC__stream_encoder_finish (pflac->fse) ;
707                 FLAC__stream_encoder_delete (pflac->fse) ;
708
709                 if (pflac->encbuffer)
710                         free (pflac->encbuffer) ;
711                 } ;
712
713         if (psf->file.mode == SFM_READ)
714         {       FLAC__stream_decoder_finish (pflac->fsd) ;
715                 FLAC__stream_decoder_delete (pflac->fsd) ;
716                 } ;
717
718         for (k = 0 ; k < ARRAY_LEN (pflac->rbuffer) ; k++)
719                 free (pflac->rbuffer [k]) ;
720
721         free (pflac) ;
722         psf->codec_data = NULL ;
723
724         return 0 ;
725 } /* flac_close */
726
727 static int
728 flac_enc_init (SF_PRIVATE *psf)
729 {       FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
730         unsigned bps ;
731
732         /* To cite the flac FAQ at
733         ** http://flac.sourceforge.net/faq.html#general__samples
734         **     "FLAC supports linear sample rates from 1Hz - 655350Hz in 1Hz
735         **     increments."
736         */
737         if (psf->sf.samplerate < 1 || psf->sf.samplerate > 655350)
738         {       psf_log_printf (psf, "flac sample rate out of range.\n", psf->sf.samplerate) ;
739                 return SFE_FLAC_BAD_SAMPLE_RATE ;
740                 } ;
741
742         psf_fseek (psf, 0, SEEK_SET) ;
743
744         switch (SF_CODEC (psf->sf.format))
745         {       case SF_FORMAT_PCM_S8 :
746                         bps = 8 ;
747                         break ;
748                 case SF_FORMAT_PCM_16 :
749                         bps = 16 ;
750                         break ;
751                 case SF_FORMAT_PCM_24 :
752                         bps = 24 ;
753                         break ;
754
755                 default :
756                         bps = 0 ;
757                         break ;
758                 } ;
759
760         if (pflac->fse)
761                 FLAC__stream_encoder_delete (pflac->fse) ;
762         if ((pflac->fse = FLAC__stream_encoder_new ()) == NULL)
763                 return SFE_FLAC_NEW_DECODER ;
764
765         if (! FLAC__stream_encoder_set_channels (pflac->fse, psf->sf.channels))
766         {       psf_log_printf (psf, "FLAC__stream_encoder_set_channels (%d) return false.\n", psf->sf.channels) ;
767                 return SFE_FLAC_INIT_DECODER ;
768                 } ;
769
770         if (! FLAC__stream_encoder_set_sample_rate (pflac->fse, psf->sf.samplerate))
771         {       psf_log_printf (psf, "FLAC__stream_encoder_set_sample_rate (%d) returned false.\n", psf->sf.samplerate) ;
772                 return SFE_FLAC_BAD_SAMPLE_RATE ;
773                 } ;
774
775         if (! FLAC__stream_encoder_set_bits_per_sample (pflac->fse, bps))
776         {       psf_log_printf (psf, "FLAC__stream_encoder_set_bits_per_sample (%d) return false.\n", bps) ;
777                 return SFE_FLAC_INIT_DECODER ;
778                 } ;
779
780         if (! FLAC__stream_encoder_set_compression_level (pflac->fse, pflac->compression))
781         {       psf_log_printf (psf, "FLAC__stream_encoder_set_compression_level (%d) return false.\n", pflac->compression) ;
782                 return SFE_FLAC_INIT_DECODER ;
783                 } ;
784
785         return 0 ;
786 } /* flac_enc_init */
787
788 static int
789 flac_read_header (SF_PRIVATE *psf)
790 {       FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
791
792         psf_fseek (psf, 0, SEEK_SET) ;
793         if (pflac->fsd)
794                 FLAC__stream_decoder_delete (pflac->fsd) ;
795         if ((pflac->fsd = FLAC__stream_decoder_new ()) == NULL)
796                 return SFE_FLAC_NEW_DECODER ;
797
798         FLAC__stream_decoder_set_metadata_respond_all (pflac->fsd) ;
799
800         if (FLAC__stream_decoder_init_stream (pflac->fsd, sf_flac_read_callback, sf_flac_seek_callback, sf_flac_tell_callback, sf_flac_length_callback, sf_flac_eof_callback, sf_flac_write_callback, sf_flac_meta_callback, sf_flac_error_callback, psf) != FLAC__STREAM_DECODER_INIT_STATUS_OK)
801                 return SFE_FLAC_INIT_DECODER ;
802
803         FLAC__stream_decoder_process_until_end_of_metadata (pflac->fsd) ;
804
805         psf_log_printf (psf, "End\n") ;
806
807         if (psf->error == 0)
808         {       FLAC__uint64 position ;
809
810                 FLAC__stream_decoder_get_decode_position (pflac->fsd, &position) ;
811                 psf->dataoffset = position ;
812                 } ;
813
814         return psf->error ;
815 } /* flac_read_header */
816
817 static int
818 flac_command (SF_PRIVATE * psf, int command, void * data, int datasize)
819 {       FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
820         double quality ;
821
822         switch (command)
823         {       case SFC_SET_COMPRESSION_LEVEL :
824                         if (data == NULL || datasize != sizeof (double))
825                                 return SF_FALSE ;
826
827                         if (psf->have_written)
828                                 return SF_FALSE ;
829
830                         /* FLAC compression level is in the range [0, 8] while libsndfile takes
831                         ** values in the range [0.0, 1.0]. Massage the libsndfile value here.
832                         */
833                         quality = (*((double *) data)) * 8.0 ;
834                         /* Clip range. */
835                         pflac->compression = lrint (SF_MAX (0.0, SF_MIN (8.0, quality))) ;
836
837                         psf_log_printf (psf, "%s : Setting SFC_SET_COMPRESSION_LEVEL to %u.\n", __func__, pflac->compression) ;
838
839                         if (flac_enc_init (psf))
840                                 return SF_FALSE ;
841
842                         return SF_TRUE ;
843
844                 default :
845                         return SF_FALSE ;
846                 } ;
847
848         return SF_FALSE ;
849 } /* flac_command */
850
851 int
852 flac_init (SF_PRIVATE *psf)
853 {
854         if (psf->file.mode == SFM_RDWR)
855                 return SFE_BAD_MODE_RW ;
856
857         if (psf->file.mode == SFM_READ)
858         {       psf->read_short         = flac_read_flac2s ;
859                 psf->read_int           = flac_read_flac2i ;
860                 psf->read_float         = flac_read_flac2f ;
861                 psf->read_double        = flac_read_flac2d ;
862                 } ;
863
864         if (psf->file.mode == SFM_WRITE)
865         {       psf->write_short        = flac_write_s2flac ;
866                 psf->write_int          = flac_write_i2flac ;
867                 psf->write_float        = flac_write_f2flac ;
868                 psf->write_double       = flac_write_d2flac ;
869                 } ;
870
871         if (psf->filelength > psf->dataoffset)
872                 psf->datalength = (psf->dataend) ? psf->dataend - psf->dataoffset : psf->filelength - psf->dataoffset ;
873         else
874                 psf->datalength = 0 ;
875
876         return 0 ;
877 } /* flac_init */
878
879 static unsigned
880 flac_read_loop (SF_PRIVATE *psf, unsigned len)
881 {       FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
882         FLAC__StreamDecoderState state ;
883
884         pflac->pos = 0 ;
885         pflac->len = len ;
886         pflac->remain = len ;
887
888         state = FLAC__stream_decoder_get_state (pflac->fsd) ;
889         if (state > FLAC__STREAM_DECODER_END_OF_STREAM)
890         {       psf_log_printf (psf, "FLAC__stream_decoder_get_state returned %s\n", FLAC__StreamDecoderStateString [state]) ;
891                 /* Current frame is busted, so NULL the pointer. */
892                 pflac->frame = NULL ;
893                 } ;
894
895         /* First copy data that has already been decoded and buffered. */
896         if (pflac->frame != NULL && pflac->bufferpos < pflac->frame->header.blocksize)
897                 flac_buffer_copy (psf) ;
898
899         while (pflac->pos < pflac->len)
900         {       if (FLAC__stream_decoder_process_single (pflac->fsd) == 0)
901                         break ;
902                 state = FLAC__stream_decoder_get_state (pflac->fsd) ;
903                 if (state >= FLAC__STREAM_DECODER_END_OF_STREAM)
904                 {       psf_log_printf (psf, "FLAC__stream_decoder_get_state returned %s\n", FLAC__StreamDecoderStateString [state]) ;
905                         /* Current frame is busted, so NULL the pointer. */
906                         pflac->frame = NULL ;
907                         break ;
908                         } ;
909                 } ;
910
911         pflac->ptr = NULL ;
912
913         return pflac->pos ;
914 } /* flac_read_loop */
915
916 static sf_count_t
917 flac_read_flac2s (SF_PRIVATE *psf, short *ptr, sf_count_t len)
918 {       FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
919         sf_count_t total = 0, current ;
920         unsigned readlen ;
921
922         pflac->pcmtype = PFLAC_PCM_SHORT ;
923
924         while (total < len)
925         {       pflac->ptr = ptr + total ;
926                 readlen = (len - total > 0x1000000) ? 0x1000000 : (unsigned) (len - total) ;
927                 current = flac_read_loop (psf, readlen) ;
928                 if (current == 0)
929                         break ;
930                 total += current ;
931                 } ;
932
933         return total ;
934 } /* flac_read_flac2s */
935
936 static sf_count_t
937 flac_read_flac2i (SF_PRIVATE *psf, int *ptr, sf_count_t len)
938 {       FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
939         sf_count_t total = 0, current ;
940         unsigned readlen ;
941
942         pflac->pcmtype = PFLAC_PCM_INT ;
943
944         while (total < len)
945         {       pflac->ptr = ptr + total ;
946                 readlen = (len - total > 0x1000000) ? 0x1000000 : (unsigned) (len - total) ;
947                 current = flac_read_loop (psf, readlen) ;
948                 if (current == 0)
949                         break ;
950                 total += current ;
951                 } ;
952
953         return total ;
954 } /* flac_read_flac2i */
955
956 static sf_count_t
957 flac_read_flac2f (SF_PRIVATE *psf, float *ptr, sf_count_t len)
958 {       FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
959         sf_count_t total = 0, current ;
960         unsigned readlen ;
961
962         pflac->pcmtype = PFLAC_PCM_FLOAT ;
963
964         while (total < len)
965         {       pflac->ptr = ptr + total ;
966                 readlen = (len - total > 0x1000000) ? 0x1000000 : (unsigned) (len - total) ;
967                 current = flac_read_loop (psf, readlen) ;
968                 if (current == 0)
969                         break ;
970                 total += current ;
971                 } ;
972
973         return total ;
974 } /* flac_read_flac2f */
975
976 static sf_count_t
977 flac_read_flac2d (SF_PRIVATE *psf, double *ptr, sf_count_t len)
978 {       FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
979         sf_count_t total = 0, current ;
980         unsigned readlen ;
981
982         pflac->pcmtype = PFLAC_PCM_DOUBLE ;
983
984         while (total < len)
985         {       pflac->ptr = ptr + total ;
986                 readlen = (len - total > 0x1000000) ? 0x1000000 : (unsigned) (len - total) ;
987                 current = flac_read_loop (psf, readlen) ;
988                 if (current == 0)
989                         break ;
990                 total += current ;
991                 } ;
992
993         return total ;
994 } /* flac_read_flac2d */
995
996 static sf_count_t
997 flac_write_s2flac (SF_PRIVATE *psf, const short *ptr, sf_count_t len)
998 {       FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
999         void (*convert) (const short *, FLAC__int32 *, int) ;
1000         int bufferlen, writecount, thiswrite ;
1001         sf_count_t      total = 0 ;
1002         FLAC__int32* buffer = pflac->encbuffer ;
1003
1004         switch (SF_CODEC (psf->sf.format))
1005         {       case SF_FORMAT_PCM_S8 :
1006                         convert = s2flac8_array ;
1007                         break ;
1008                 case SF_FORMAT_PCM_16 :
1009                         convert = s2flac16_array ;
1010                         break ;
1011                         case SF_FORMAT_PCM_24 :
1012                         convert = s2flac24_array ;
1013                         break ;
1014                 default :
1015                         return -1 ;
1016                 } ;
1017
1018         bufferlen = ENC_BUFFER_SIZE / (sizeof (FLAC__int32) * psf->sf.channels) ;
1019         bufferlen *= psf->sf.channels ;
1020
1021         while (len > 0)
1022         {       writecount = (len >= bufferlen) ? bufferlen : (int) len ;
1023                 convert (ptr + total, buffer, writecount) ;
1024                 if (FLAC__stream_encoder_process_interleaved (pflac->fse, buffer, writecount / psf->sf.channels))
1025                         thiswrite = writecount ;
1026                 else
1027                         break ;
1028                 total += thiswrite ;
1029                 if (thiswrite < writecount)
1030                         break ;
1031
1032                 len -= thiswrite ;
1033                 } ;
1034
1035         return total ;
1036 } /* flac_write_s2flac */
1037
1038 static sf_count_t
1039 flac_write_i2flac (SF_PRIVATE *psf, const int *ptr, sf_count_t len)
1040 {       FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
1041         void (*convert) (const int *, FLAC__int32 *, int) ;
1042         int bufferlen, writecount, thiswrite ;
1043         sf_count_t      total = 0 ;
1044         FLAC__int32* buffer = pflac->encbuffer ;
1045
1046         switch (SF_CODEC (psf->sf.format))
1047         {       case SF_FORMAT_PCM_S8 :
1048                         convert = i2flac8_array ;
1049                         break ;
1050                 case SF_FORMAT_PCM_16 :
1051                         convert = i2flac16_array ;
1052                         break ;
1053                 case SF_FORMAT_PCM_24 :
1054                         convert = i2flac24_array ;
1055                         break ;
1056                 default :
1057                         return -1 ;
1058                 } ;
1059
1060         bufferlen = ENC_BUFFER_SIZE / (sizeof (FLAC__int32) * psf->sf.channels) ;
1061         bufferlen *= psf->sf.channels ;
1062
1063         while (len > 0)
1064         {       writecount = (len >= bufferlen) ? bufferlen : (int) len ;
1065                 convert (ptr + total, buffer, writecount) ;
1066                 if (FLAC__stream_encoder_process_interleaved (pflac->fse, buffer, writecount / psf->sf.channels))
1067                         thiswrite = writecount ;
1068                 else
1069                         break ;
1070                 total += thiswrite ;
1071                 if (thiswrite < writecount)
1072                         break ;
1073
1074                 len -= thiswrite ;
1075                 } ;
1076
1077         return total ;
1078 } /* flac_write_i2flac */
1079
1080 static sf_count_t
1081 flac_write_f2flac (SF_PRIVATE *psf, const float *ptr, sf_count_t len)
1082 {       FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
1083         void (*convert) (const float *, FLAC__int32 *, int, int) ;
1084         int bufferlen, writecount, thiswrite ;
1085         sf_count_t      total = 0 ;
1086         FLAC__int32* buffer = pflac->encbuffer ;
1087
1088         switch (SF_CODEC (psf->sf.format))
1089         {       case SF_FORMAT_PCM_S8 :
1090                         convert = (psf->add_clipping) ? f2flac8_clip_array : f2flac8_array ;
1091                         break ;
1092                 case SF_FORMAT_PCM_16 :
1093                         convert = (psf->add_clipping) ? f2flac16_clip_array : f2flac16_array ;
1094                         break ;
1095                 case SF_FORMAT_PCM_24 :
1096                         convert = (psf->add_clipping) ? f2flac24_clip_array : f2flac24_array ;
1097                         break ;
1098                 default :
1099                         return -1 ;
1100                 } ;
1101
1102         bufferlen = ENC_BUFFER_SIZE / (sizeof (FLAC__int32) * psf->sf.channels) ;
1103         bufferlen *= psf->sf.channels ;
1104
1105         while (len > 0)
1106         {       writecount = (len >= bufferlen) ? bufferlen : (int) len ;
1107                 convert (ptr + total, buffer, writecount, psf->norm_float) ;
1108                 if (FLAC__stream_encoder_process_interleaved (pflac->fse, buffer, writecount / psf->sf.channels))
1109                         thiswrite = writecount ;
1110                 else
1111                         break ;
1112                 total += thiswrite ;
1113                 if (thiswrite < writecount)
1114                         break ;
1115
1116                 len -= thiswrite ;
1117                 } ;
1118
1119         return total ;
1120 } /* flac_write_f2flac */
1121
1122 static void
1123 f2flac8_clip_array (const float *src, FLAC__int32 *dest, int count, int normalize)
1124 {       float normfact, scaled_value ;
1125
1126         normfact = normalize ? (8.0 * 0x10) : 1.0 ;
1127
1128         while (--count >= 0)
1129         {       scaled_value = src [count] * normfact ;
1130                 if (CPU_CLIPS_POSITIVE == 0 && scaled_value >= (1.0 * 0x7F))
1131                 {       dest [count] = 0x7F ;
1132                         continue ;
1133                         } ;
1134                 if (CPU_CLIPS_NEGATIVE == 0 && scaled_value <= (-8.0 * 0x10))
1135                 {       dest [count] = 0x80 ;
1136                         continue ;
1137                         } ;
1138                 dest [count] = lrintf (scaled_value) ;
1139                 } ;
1140
1141         return ;
1142 } /* f2flac8_clip_array */
1143
1144 static void
1145 f2flac16_clip_array (const float *src, FLAC__int32 *dest, int count, int normalize)
1146 {       float normfact, scaled_value ;
1147
1148         normfact = normalize ? (8.0 * 0x1000) : 1.0 ;
1149
1150         while (--count >= 0)
1151         {       scaled_value = src [count] * normfact ;
1152                 if (CPU_CLIPS_POSITIVE == 0 && scaled_value >= (1.0 * 0x7FFF))
1153                 {       dest [count] = 0x7FFF ;
1154                         continue ;
1155                         } ;
1156                 if (CPU_CLIPS_NEGATIVE == 0 && scaled_value <= (-8.0 * 0x1000))
1157                 {       dest [count] = 0x8000 ;
1158                         continue ;
1159                         } ;
1160                 dest [count] = lrintf (scaled_value) ;
1161                 } ;
1162 } /* f2flac16_clip_array */
1163
1164 static void
1165 f2flac24_clip_array (const float *src, FLAC__int32 *dest, int count, int normalize)
1166 {       float normfact, scaled_value ;
1167
1168         normfact = normalize ? (8.0 * 0x100000) : 1.0 ;
1169
1170         while (--count >= 0)
1171         {       scaled_value = src [count] * normfact ;
1172                 if (CPU_CLIPS_POSITIVE == 0 && scaled_value >= (1.0 * 0x7FFFFF))
1173                 {       dest [count] = 0x7FFFFF ;
1174                         continue ;
1175                         } ;
1176
1177                 if (CPU_CLIPS_NEGATIVE == 0 && scaled_value <= (-8.0 * 0x100000))
1178                 {       dest [count] = 0x800000 ;
1179                         continue ;
1180                         }
1181                 dest [count] = lrintf (scaled_value) ;
1182                 } ;
1183
1184         return ;
1185 } /* f2flac24_clip_array */
1186
1187 static void
1188 f2flac8_array (const float *src, FLAC__int32 *dest, int count, int normalize)
1189 {       float normfact = normalize ? (1.0 * 0x7F) : 1.0 ;
1190
1191         while (--count >= 0)
1192                 dest [count] = lrintf (src [count] * normfact) ;
1193 } /* f2flac8_array */
1194
1195 static void
1196 f2flac16_array (const float *src, FLAC__int32 *dest, int count, int normalize)
1197 {       float normfact = normalize ? (1.0 * 0x7FFF) : 1.0 ;
1198
1199         while (--count >= 0)
1200                 dest [count] = lrintf (src [count] * normfact) ;
1201 } /* f2flac16_array */
1202
1203 static void
1204 f2flac24_array (const float *src, FLAC__int32 *dest, int count, int normalize)
1205 {       float normfact = normalize ? (1.0 * 0x7FFFFF) : 1.0 ;
1206
1207         while (--count >= 0)
1208                 dest [count] = lrintf (src [count] * normfact) ;
1209 } /* f2flac24_array */
1210
1211 static sf_count_t
1212 flac_write_d2flac (SF_PRIVATE *psf, const double *ptr, sf_count_t len)
1213 {       FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
1214         void (*convert) (const double *, FLAC__int32 *, int, int) ;
1215         int bufferlen, writecount, thiswrite ;
1216         sf_count_t      total = 0 ;
1217         FLAC__int32* buffer = pflac->encbuffer ;
1218
1219         switch (SF_CODEC (psf->sf.format))
1220         {       case SF_FORMAT_PCM_S8 :
1221                         convert = (psf->add_clipping) ? d2flac8_clip_array : d2flac8_array ;
1222                         break ;
1223                 case SF_FORMAT_PCM_16 :
1224                         convert = (psf->add_clipping) ? d2flac16_clip_array : d2flac16_array ;
1225                         break ;
1226                 case SF_FORMAT_PCM_24 :
1227                         convert = (psf->add_clipping) ? d2flac24_clip_array : d2flac24_array ;
1228                         break ;
1229                 default :
1230                         return -1 ;
1231                 } ;
1232
1233         bufferlen = ENC_BUFFER_SIZE / (sizeof (FLAC__int32) * psf->sf.channels) ;
1234         bufferlen *= psf->sf.channels ;
1235
1236         while (len > 0)
1237         {       writecount = (len >= bufferlen) ? bufferlen : (int) len ;
1238                 convert (ptr + total, buffer, writecount, psf->norm_double) ;
1239                 if (FLAC__stream_encoder_process_interleaved (pflac->fse, buffer, writecount / psf->sf.channels))
1240                         thiswrite = writecount ;
1241                 else
1242                         break ;
1243                 total += thiswrite ;
1244                 if (thiswrite < writecount)
1245                         break ;
1246
1247                 len -= thiswrite ;
1248                 } ;
1249
1250         return total ;
1251 } /* flac_write_d2flac */
1252
1253 static void
1254 d2flac8_clip_array (const double *src, FLAC__int32 *dest, int count, int normalize)
1255 {       double normfact, scaled_value ;
1256
1257         normfact = normalize ? (8.0 * 0x10) : 1.0 ;
1258
1259         while (--count >= 0)
1260         {       scaled_value = src [count] * normfact ;
1261                 if (CPU_CLIPS_POSITIVE == 0 && scaled_value >= (1.0 * 0x7F))
1262                 {       dest [count] = 0x7F ;
1263                         continue ;
1264                         } ;
1265                 if (CPU_CLIPS_NEGATIVE == 0 && scaled_value <= (-8.0 * 0x10))
1266                 {       dest [count] = 0x80 ;
1267                         continue ;
1268                         } ;
1269                 dest [count] = lrint (scaled_value) ;
1270                 } ;
1271
1272         return ;
1273 } /* d2flac8_clip_array */
1274
1275 static void
1276 d2flac16_clip_array (const double *src, FLAC__int32 *dest, int count, int normalize)
1277 {       double normfact, scaled_value ;
1278
1279         normfact = normalize ? (8.0 * 0x1000) : 1.0 ;
1280
1281         while (--count >= 0)
1282         {       scaled_value = src [count] * normfact ;
1283                 if (CPU_CLIPS_POSITIVE == 0 && scaled_value >= (1.0 * 0x7FFF))
1284                 {       dest [count] = 0x7FFF ;
1285                         continue ;
1286                         } ;
1287                 if (CPU_CLIPS_NEGATIVE == 0 && scaled_value <= (-8.0 * 0x1000))
1288                 {       dest [count] = 0x8000 ;
1289                         continue ;
1290                         } ;
1291                 dest [count] = lrint (scaled_value) ;
1292                 } ;
1293
1294         return ;
1295 } /* d2flac16_clip_array */
1296
1297 static void
1298 d2flac24_clip_array (const double *src, FLAC__int32 *dest, int count, int normalize)
1299 {       double normfact, scaled_value ;
1300
1301         normfact = normalize ? (8.0 * 0x100000) : 1.0 ;
1302
1303         while (--count >= 0)
1304         {       scaled_value = src [count] * normfact ;
1305                 if (CPU_CLIPS_POSITIVE == 0 && scaled_value >= (1.0 * 0x7FFFFF))
1306                 {       dest [count] = 0x7FFFFF ;
1307                         continue ;
1308                         } ;
1309                 if (CPU_CLIPS_NEGATIVE == 0 && scaled_value <= (-8.0 * 0x100000))
1310                 {       dest [count] = 0x800000 ;
1311                         continue ;
1312                         } ;
1313                 dest [count] = lrint (scaled_value) ;
1314                 } ;
1315
1316         return ;
1317 } /* d2flac24_clip_array */
1318
1319 static void
1320 d2flac8_array (const double *src, FLAC__int32 *dest, int count, int normalize)
1321 {       double normfact = normalize ? (1.0 * 0x7F) : 1.0 ;
1322
1323         while (--count >= 0)
1324                 dest [count] = lrint (src [count] * normfact) ;
1325 } /* d2flac8_array */
1326
1327 static void
1328 d2flac16_array (const double *src, FLAC__int32 *dest, int count, int normalize)
1329 {       double normfact = normalize ? (1.0 * 0x7FFF) : 1.0 ;
1330
1331         while (--count >= 0)
1332                 dest [count] = lrint (src [count] * normfact) ;
1333 } /* d2flac16_array */
1334
1335 static void
1336 d2flac24_array (const double *src, FLAC__int32 *dest, int count, int normalize)
1337 {       double normfact = normalize ? (1.0 * 0x7FFFFF) : 1.0 ;
1338
1339         while (--count >= 0)
1340                 dest [count] = lrint (src [count] * normfact) ;
1341 } /* d2flac24_array */
1342
1343 static sf_count_t
1344 flac_seek (SF_PRIVATE *psf, int UNUSED (mode), sf_count_t offset)
1345 {       FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
1346
1347         if (pflac == NULL)
1348                 return 0 ;
1349
1350         if (psf->dataoffset < 0)
1351         {       psf->error = SFE_BAD_SEEK ;
1352                 return ((sf_count_t) -1) ;
1353                 } ;
1354
1355         pflac->frame = NULL ;
1356
1357         if (psf->file.mode == SFM_READ)
1358         {       if (FLAC__stream_decoder_seek_absolute (pflac->fsd, offset))
1359                         return offset ;
1360
1361                 if (offset == psf->sf.frames)
1362                 {       /*
1363                         ** If we've been asked to seek to the very end of the file, libFLAC
1364                         ** will return an error. However, we know the length of the file so
1365                         ** instead of returning an error, we can return the offset.
1366                         */
1367                         return offset ;
1368                         } ;
1369
1370                 psf->error = SFE_BAD_SEEK ;
1371                 return ((sf_count_t) -1) ;
1372                 } ;
1373
1374         /* Seeking in write mode not yet supported. */
1375         psf->error = SFE_BAD_SEEK ;
1376
1377         return ((sf_count_t) -1) ;
1378 } /* flac_seek */
1379
1380 static int
1381 flac_byterate (SF_PRIVATE *psf)
1382 {
1383         if (psf->file.mode == SFM_READ)
1384                 return (psf->datalength * psf->sf.samplerate) / psf->sf.frames ;
1385
1386         return -1 ;
1387 } /* flac_byterate */
1388
1389
1390 #else /* HAVE_EXTERNAL_LIBS */
1391
1392 int
1393 flac_open       (SF_PRIVATE *psf)
1394 {
1395         psf_log_printf (psf, "This version of libsndfile was compiled without FLAC support.\n") ;
1396         return SFE_UNIMPLEMENTED ;
1397 } /* flac_open */
1398
1399 #endif