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