Merge tag 'upstream/1.0.31' into tizen
[platform/upstream/libsndfile.git] / src / aiff.c
1 /*
2 ** Copyright (C) 1999-2018 Erik de Castro Lopo <erikd@mega-nerd.com>
3 ** Copyright (C) 2005 David Viens <davidv@plogue.com>
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 <string.h>
25 #include <time.h>
26 #include <ctype.h>
27 #include <inttypes.h>
28
29 #include "sndfile.h"
30 #include "sfendian.h"
31 #include "common.h"
32 #include "chanmap.h"
33
34 /*------------------------------------------------------------------------------
35  * Macros to handle big/little endian issues.
36  */
37
38 #define FORM_MARKER             (MAKE_MARKER ('F', 'O', 'R', 'M'))
39 #define AIFF_MARKER             (MAKE_MARKER ('A', 'I', 'F', 'F'))
40 #define AIFC_MARKER             (MAKE_MARKER ('A', 'I', 'F', 'C'))
41 #define COMM_MARKER             (MAKE_MARKER ('C', 'O', 'M', 'M'))
42 #define SSND_MARKER             (MAKE_MARKER ('S', 'S', 'N', 'D'))
43 #define MARK_MARKER             (MAKE_MARKER ('M', 'A', 'R', 'K'))
44 #define INST_MARKER             (MAKE_MARKER ('I', 'N', 'S', 'T'))
45 #define APPL_MARKER             (MAKE_MARKER ('A', 'P', 'P', 'L'))
46 #define CHAN_MARKER             (MAKE_MARKER ('C', 'H', 'A', 'N'))
47
48 #define c_MARKER                (MAKE_MARKER ('(', 'c', ')', ' '))
49 #define NAME_MARKER             (MAKE_MARKER ('N', 'A', 'M', 'E'))
50 #define AUTH_MARKER             (MAKE_MARKER ('A', 'U', 'T', 'H'))
51 #define ANNO_MARKER             (MAKE_MARKER ('A', 'N', 'N', 'O'))
52 #define COMT_MARKER             (MAKE_MARKER ('C', 'O', 'M', 'T'))
53 #define FVER_MARKER             (MAKE_MARKER ('F', 'V', 'E', 'R'))
54 #define SFX_MARKER              (MAKE_MARKER ('S', 'F', 'X', '!'))
55
56 #define PEAK_MARKER             (MAKE_MARKER ('P', 'E', 'A', 'K'))
57 #define basc_MARKER             (MAKE_MARKER ('b', 'a', 's', 'c'))
58
59 /* Supported AIFC encodings.*/
60 #define NONE_MARKER             (MAKE_MARKER ('N', 'O', 'N', 'E'))
61 #define sowt_MARKER             (MAKE_MARKER ('s', 'o', 'w', 't'))
62 #define twos_MARKER             (MAKE_MARKER ('t', 'w', 'o', 's'))
63 #define raw_MARKER              (MAKE_MARKER ('r', 'a', 'w', ' '))
64 #define in24_MARKER             (MAKE_MARKER ('i', 'n', '2', '4'))
65 #define ni24_MARKER             (MAKE_MARKER ('4', '2', 'n', '1'))
66 #define in32_MARKER             (MAKE_MARKER ('i', 'n', '3', '2'))
67 #define ni32_MARKER             (MAKE_MARKER ('2', '3', 'n', 'i'))
68
69 #define fl32_MARKER             (MAKE_MARKER ('f', 'l', '3', '2'))
70 #define FL32_MARKER             (MAKE_MARKER ('F', 'L', '3', '2'))
71 #define fl64_MARKER             (MAKE_MARKER ('f', 'l', '6', '4'))
72 #define FL64_MARKER             (MAKE_MARKER ('F', 'L', '6', '4'))
73
74 #define ulaw_MARKER             (MAKE_MARKER ('u', 'l', 'a', 'w'))
75 #define ULAW_MARKER             (MAKE_MARKER ('U', 'L', 'A', 'W'))
76 #define alaw_MARKER             (MAKE_MARKER ('a', 'l', 'a', 'w'))
77 #define ALAW_MARKER             (MAKE_MARKER ('A', 'L', 'A', 'W'))
78
79 #define DWVW_MARKER             (MAKE_MARKER ('D', 'W', 'V', 'W'))
80 #define GSM_MARKER              (MAKE_MARKER ('G', 'S', 'M', ' '))
81 #define ima4_MARKER             (MAKE_MARKER ('i', 'm', 'a', '4'))
82
83 /*
84 **      This value is officially assigned to Mega Nerd Pty Ltd by Apple
85 **      Corportation as the Application marker for libsndfile.
86 **
87 **      See : http://developer.apple.com/faq/datatype.html
88 */
89 #define m3ga_MARKER             (MAKE_MARKER ('m', '3', 'g', 'a'))
90
91 /* Unsupported AIFC encodings.*/
92
93 #define MAC3_MARKER             (MAKE_MARKER ('M', 'A', 'C', '3'))
94 #define MAC6_MARKER             (MAKE_MARKER ('M', 'A', 'C', '6'))
95 #define ADP4_MARKER             (MAKE_MARKER ('A', 'D', 'P', '4'))
96
97 /* Predfined chunk sizes. */
98 #define SIZEOF_AIFF_COMM                18
99 #define SIZEOF_AIFC_COMM_MIN    22
100 #define SIZEOF_AIFC_COMM                24
101 #define SIZEOF_SSND_CHUNK               8
102 #define SIZEOF_INST_CHUNK               20
103
104 /* Is it constant? */
105
106 /* AIFC/IMA4 defines. */
107 #define AIFC_IMA4_BLOCK_LEN                             34
108 #define AIFC_IMA4_SAMPLES_PER_BLOCK             64
109
110 #define AIFF_PEAK_CHUNK_SIZE(ch)        (2 * sizeof (int) + ch * (sizeof (float) + sizeof (int)))
111
112 /*------------------------------------------------------------------------------
113  * Typedefs for file chunks.
114  */
115
116 enum
117 {       HAVE_FORM               = 0x01,
118         HAVE_AIFF               = 0x02,
119         HAVE_AIFC               = 0x04,
120         HAVE_FVER               = 0x08,
121         HAVE_COMM               = 0x10,
122         HAVE_SSND               = 0x20
123 } ;
124
125 typedef struct
126 {       uint32_t        size ;
127         int16_t         numChannels ;
128         uint32_t        numSampleFrames ;
129         int16_t         sampleSize ;
130         uint8_t         sampleRate [10] ;
131         uint32_t        encoding ;
132         char                    zero_bytes [2] ;
133 } COMM_CHUNK ;
134
135 typedef struct
136 {       uint32_t        offset ;
137         uint32_t        blocksize ;
138 } SSND_CHUNK ;
139
140 typedef struct
141 {       int16_t         playMode ;
142         uint16_t        beginLoop ;
143         uint16_t        endLoop ;
144 } INST_LOOP ;
145
146 typedef struct
147 {       int8_t          baseNote ;              /* all notes are MIDI note numbers */
148         int8_t          detune ;                /* cents off, only -50 to +50 are significant */
149         int8_t          lowNote ;
150         int8_t          highNote ;
151         int8_t          lowVelocity ;   /* 1 to 127 */
152         int8_t          highVelocity ;  /* 1 to 127 */
153         int16_t         gain ;                  /* in dB, 0 is normal */
154         INST_LOOP       sustain_loop ;
155         INST_LOOP       release_loop ;
156 } INST_CHUNK ;
157
158
159 enum
160 {       basc_SCALE_MINOR = 1,
161         basc_SCALE_MAJOR,
162         basc_SCALE_NEITHER,
163         basc_SCALE_BOTH
164 } ;
165
166 enum
167 {       basc_TYPE_LOOP = 0,
168         basc_TYPE_ONE_SHOT
169 } ;
170
171
172 typedef struct
173 {       uint32_t        version ;
174         uint32_t        numBeats ;
175         uint16_t        rootNote ;
176         uint16_t        scaleType ;
177         uint16_t        sigNumerator ;
178         uint16_t        sigDenominator ;
179         uint16_t        loopType ;
180 } basc_CHUNK ;
181
182 typedef struct
183 {       uint16_t        markerID ;
184         uint32_t        position ;
185 } MARK_ID_POS ;
186
187 typedef struct
188 {       sf_count_t      comm_offset ;
189         sf_count_t      ssnd_offset ;
190
191         int32_t         chanmap_tag ;
192
193         MARK_ID_POS *markstr ;
194 } AIFF_PRIVATE ;
195
196 /*------------------------------------------------------------------------------
197  * Private static functions.
198  */
199
200 static int      aiff_close (SF_PRIVATE *psf) ;
201
202 static int      tenbytefloat2int (uint8_t *bytes) ;
203 static void uint2tenbytefloat (uint32_t num, uint8_t *bytes) ;
204
205 static int      aiff_read_comm_chunk (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt) ;
206
207 static int      aiff_read_header (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt) ;
208
209 static int      aiff_write_header (SF_PRIVATE *psf, int calc_length) ;
210 static int      aiff_write_tailer (SF_PRIVATE *psf) ;
211 static void     aiff_write_strings (SF_PRIVATE *psf, int location) ;
212
213 static int      aiff_command (SF_PRIVATE *psf, int command, void *data, int datasize) ;
214
215 static const char *get_loop_mode_str (int16_t mode) ;
216
217 static int16_t get_loop_mode (int16_t mode) ;
218
219 static int aiff_read_basc_chunk (SF_PRIVATE * psf, int) ;
220
221 static int aiff_read_chanmap (SF_PRIVATE * psf, unsigned dword) ;
222
223 static uint32_t marker_to_position (const MARK_ID_POS *m, uint16_t n, int marksize) ;
224
225 static int aiff_set_chunk (SF_PRIVATE *psf, const SF_CHUNK_INFO * chunk_info) ;
226 static SF_CHUNK_ITERATOR * aiff_next_chunk_iterator (SF_PRIVATE *psf, SF_CHUNK_ITERATOR * iterator) ;
227 static int aiff_get_chunk_size (SF_PRIVATE *psf, const SF_CHUNK_ITERATOR * iterator, SF_CHUNK_INFO * chunk_info) ;
228 static int aiff_get_chunk_data (SF_PRIVATE *psf, const SF_CHUNK_ITERATOR * iterator, SF_CHUNK_INFO * chunk_info) ;
229
230 /*------------------------------------------------------------------------------
231 ** Public function.
232 */
233
234 int
235 aiff_open (SF_PRIVATE *psf)
236 {       COMM_CHUNK comm_fmt ;
237         int error, subformat ;
238
239         memset (&comm_fmt, 0, sizeof (comm_fmt)) ;
240
241         subformat = SF_CODEC (psf->sf.format) ;
242
243         if ((psf->container_data = calloc (1, sizeof (AIFF_PRIVATE))) == NULL)
244                 return SFE_MALLOC_FAILED ;
245
246         psf->container_close = aiff_close ;
247
248         if (psf->file.mode == SFM_READ || (psf->file.mode == SFM_RDWR && psf->filelength > 0))
249         {       if ((error = aiff_read_header (psf, &comm_fmt)))
250                         return error ;
251
252                 psf->next_chunk_iterator = aiff_next_chunk_iterator ;
253                 psf->get_chunk_size = aiff_get_chunk_size ;
254                 psf->get_chunk_data = aiff_get_chunk_data ;
255
256                 psf_fseek (psf, psf->dataoffset, SEEK_SET) ;
257                 } ;
258
259         if (psf->file.mode == SFM_WRITE || psf->file.mode == SFM_RDWR)
260         {       if (psf->is_pipe)
261                         return SFE_NO_PIPE_WRITE ;
262
263                 if ((SF_CONTAINER (psf->sf.format)) != SF_FORMAT_AIFF)
264                         return SFE_BAD_OPEN_FORMAT ;
265
266                 if (psf->file.mode == SFM_WRITE && (subformat == SF_FORMAT_FLOAT || subformat == SF_FORMAT_DOUBLE))
267                 {       if ((psf->peak_info = peak_info_calloc (psf->sf.channels)) == NULL)
268                                 return SFE_MALLOC_FAILED ;
269                         psf->peak_info->peak_loc = SF_PEAK_START ;
270                         } ;
271
272                 if (psf->file.mode != SFM_RDWR || psf->filelength < 40)
273                 {       psf->filelength = 0 ;
274                         psf->datalength = 0 ;
275                         psf->dataoffset = 0 ;
276                         psf->sf.frames = 0 ;
277                         } ;
278
279                 psf->strings.flags = SF_STR_ALLOW_START | SF_STR_ALLOW_END ;
280
281                 if ((error = aiff_write_header (psf, SF_FALSE)))
282                         return error ;
283
284                 psf->write_header       = aiff_write_header ;
285                 psf->set_chunk          = aiff_set_chunk ;
286                 } ;
287
288         psf->command = aiff_command ;
289
290         switch (SF_CODEC (psf->sf.format))
291         {       case SF_FORMAT_PCM_U8 :
292                                 error = pcm_init (psf) ;
293                                 break ;
294
295                 case SF_FORMAT_PCM_S8 :
296                                 error = pcm_init (psf) ;
297                                 break ;
298
299                 case SF_FORMAT_PCM_16 :
300                 case SF_FORMAT_PCM_24 :
301                 case SF_FORMAT_PCM_32 :
302                                 error = pcm_init (psf) ;
303                                 break ;
304
305                 case SF_FORMAT_ULAW :
306                                 error = ulaw_init (psf) ;
307                                 break ;
308
309                 case SF_FORMAT_ALAW :
310                                 error = alaw_init (psf) ;
311                                 break ;
312
313                 /* Lite remove start */
314                 case SF_FORMAT_FLOAT :
315                                 error = float32_init (psf) ;
316                                 break ;
317
318                 case SF_FORMAT_DOUBLE :
319                                 error = double64_init (psf) ;
320                                 break ;
321
322                 case SF_FORMAT_DWVW_12 :
323                                 if (psf->sf.frames > comm_fmt.numSampleFrames)
324                                         psf->sf.frames = comm_fmt.numSampleFrames ;
325                                 break ;
326
327                 case SF_FORMAT_DWVW_16 :
328                                 error = dwvw_init (psf, 16) ;
329                                 if (psf->sf.frames > comm_fmt.numSampleFrames)
330                                         psf->sf.frames = comm_fmt.numSampleFrames ;
331                                 break ;
332
333                 case SF_FORMAT_DWVW_24 :
334                                 error = dwvw_init (psf, 24) ;
335                                 if (psf->sf.frames > comm_fmt.numSampleFrames)
336                                         psf->sf.frames = comm_fmt.numSampleFrames ;
337                                 break ;
338
339                 case SF_FORMAT_DWVW_N :
340                                 if (psf->file.mode != SFM_READ)
341                                 {       error = SFE_DWVW_BAD_BITWIDTH ;
342                                         break ;
343                                         } ;
344                                 if (comm_fmt.sampleSize >= 8 && comm_fmt.sampleSize < 24)
345                                 {       error = dwvw_init (psf, comm_fmt.sampleSize) ;
346                                         if (psf->sf.frames > comm_fmt.numSampleFrames)
347                                                 psf->sf.frames = comm_fmt.numSampleFrames ;
348                                         break ;
349                                         } ;
350                                 psf_log_printf (psf, "AIFC/DWVW : Bad bitwidth %d\n", comm_fmt.sampleSize) ;
351                                 error = SFE_DWVW_BAD_BITWIDTH ;
352                                 break ;
353
354                 case SF_FORMAT_IMA_ADPCM :
355                                 /*
356                                 **      IMA ADPCM encoded AIFF files always have a block length
357                                 **      of 34 which decodes to 64 samples.
358                                 */
359                                 error = aiff_ima_init (psf, AIFC_IMA4_BLOCK_LEN, AIFC_IMA4_SAMPLES_PER_BLOCK) ;
360                                 break ;
361                 /* Lite remove end */
362
363                 default : return SFE_UNIMPLEMENTED ;
364                 } ;
365
366         if (psf->file.mode != SFM_WRITE && psf->sf.frames - comm_fmt.numSampleFrames != 0)
367         {       psf_log_printf (psf,
368                         "*** Frame count read from 'COMM' chunk (%u) not equal to frame count\n"
369                         "*** calculated from length of 'SSND' chunk (%u).\n",
370                         comm_fmt.numSampleFrames, (uint32_t) psf->sf.frames) ;
371                 } ;
372
373         return error ;
374 } /* aiff_open */
375
376 /*==========================================================================================
377 ** Private functions.
378 */
379
380 /* This function ought to check size */
381 static uint32_t
382 marker_to_position (const MARK_ID_POS *m, uint16_t n, int marksize)
383 {       int i ;
384
385         for (i = 0 ; i < marksize ; i++)
386                 if (m [i].markerID == n)
387                         return m [i].position ;
388         return 0 ;
389 } /* marker_to_position */
390
391 static int
392 aiff_read_header (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
393 {       SSND_CHUNK      ssnd_fmt ;
394         AIFF_PRIVATE *paiff ;
395         BUF_UNION       ubuf ;
396         uint32_t        chunk_size = 0, FORMsize, SSNDsize, bytesread, mark_count = 0 ;
397         int                     k, found_chunk = 0, done = 0, error = 0 ;
398         char            *cptr ;
399         int                     instr_found = 0, mark_found = 0 ;
400
401         if (psf->filelength > SF_PLATFORM_S64 (0xffffffff))
402                 psf_log_printf (psf, "Warning : filelength > 0xffffffff. This is bad!!!!\n") ;
403
404         if ((paiff = psf->container_data) == NULL)
405                 return SFE_INTERNAL ;
406
407         paiff->comm_offset = 0 ;
408         paiff->ssnd_offset = 0 ;
409
410         /* Set position to start of file to begin reading header. */
411         psf_binheader_readf (psf, "p", 0) ;
412
413         memset (comm_fmt, 0, sizeof (COMM_CHUNK)) ;
414
415         /* Until recently AIF* file were all BIG endian. */
416         psf->endian = SF_ENDIAN_BIG ;
417
418         /*      AIFF files can apparently have their chunks in any order. However, they
419         **      must have a FORM chunk. Approach here is to read all the chunks one by
420         **      one and then check for the mandatory chunks at the end.
421         */
422         while (! done)
423         {       unsigned        marker ;
424                 size_t jump = chunk_size & 1 ;
425
426                 marker = chunk_size = 0 ;
427                 psf_binheader_readf (psf, "Ejm4", jump, &marker, &chunk_size) ;
428                 if (marker == 0)
429                 {       sf_count_t pos = psf_ftell (psf) ;
430                         psf_log_printf (psf, "Have 0 marker at position %D (0x%x).\n", pos, pos) ;
431                         break ;
432                         } ;
433
434                 if (psf->file.mode == SFM_RDWR && (found_chunk & HAVE_SSND))
435                         return SFE_AIFF_RW_SSND_NOT_LAST ;
436
437                 psf_store_read_chunk_u32 (&psf->rchunks, marker, psf_ftell (psf), chunk_size) ;
438
439                 switch (marker)
440                 {       case FORM_MARKER :
441                                         if (found_chunk)
442                                                 return SFE_AIFF_NO_FORM ;
443
444                                         FORMsize = chunk_size ;
445
446                                         found_chunk |= HAVE_FORM ;
447                                         psf_binheader_readf (psf, "m", &marker) ;
448                                         switch (marker)
449                                         {       case AIFC_MARKER :
450                                                 case AIFF_MARKER :
451                                                         found_chunk |= (marker == AIFC_MARKER) ? (HAVE_AIFC | HAVE_AIFF) : HAVE_AIFF ;
452                                                         break ;
453                                                 default :
454                                                         break ;
455                                                 } ;
456
457                                         if (psf->fileoffset > 0 && psf->filelength > FORMsize + 8)
458                                         {       /* Set file length. */
459                                                 psf->filelength = FORMsize + 8 ;
460                                                 psf_log_printf (psf, "FORM : %u\n %M\n", FORMsize, marker) ;
461                                                 }
462                                         else if (FORMsize != psf->filelength - 2 * SIGNED_SIZEOF (chunk_size))
463                                         {       chunk_size = psf->filelength - 2 * sizeof (chunk_size) ;
464                                                 psf_log_printf (psf, "FORM : %u (should be %u)\n %M\n", FORMsize, chunk_size, marker) ;
465                                                 FORMsize = chunk_size ;
466                                                 }
467                                         else
468                                                 psf_log_printf (psf, "FORM : %u\n %M\n", FORMsize, marker) ;
469                                         /* Set this to 0, so we don't jump a byte when parsing the next marker. */
470                                         chunk_size = 0 ;
471                                         break ;
472
473
474                         case COMM_MARKER :
475                                         paiff->comm_offset = psf_ftell (psf) - 8 ;
476                                         chunk_size += chunk_size & 1 ;
477                                         comm_fmt->size = chunk_size ;
478                                         if ((error = aiff_read_comm_chunk (psf, comm_fmt)) != 0)
479                                                 return error ;
480
481                                         found_chunk |= HAVE_COMM ;
482                                         break ;
483
484                         case PEAK_MARKER :
485                                         /* Must have COMM chunk before PEAK chunk. */
486                                         if ((found_chunk & (HAVE_FORM | HAVE_AIFF | HAVE_COMM)) != (HAVE_FORM | HAVE_AIFF | HAVE_COMM))
487                                                 return SFE_AIFF_PEAK_B4_COMM ;
488
489                                         psf_log_printf (psf, "%M : %d\n", marker, chunk_size) ;
490                                         if (chunk_size != AIFF_PEAK_CHUNK_SIZE (psf->sf.channels))
491                                         {       psf_binheader_readf (psf, "j", chunk_size) ;
492                                                 psf_log_printf (psf, "*** File PEAK chunk too big.\n") ;
493                                                 return SFE_WAV_BAD_PEAK ;
494                                                 } ;
495
496                                         if (psf->peak_info)
497                                         {       psf_log_printf (psf, "*** Found existing peak info, using last one.\n") ;
498                                                 free (psf->peak_info) ;
499                                                 psf->peak_info = NULL ;
500                                                 } ;
501                                         if ((psf->peak_info = peak_info_calloc (psf->sf.channels)) == NULL)
502                                                 return SFE_MALLOC_FAILED ;
503
504                                         /* read in rest of PEAK chunk. */
505                                         psf_binheader_readf (psf, "E44", &(psf->peak_info->version), &(psf->peak_info->timestamp)) ;
506
507                                         if (psf->peak_info->version != 1)
508                                                 psf_log_printf (psf, "  version    : %d *** (should be version 1)\n", psf->peak_info->version) ;
509                                         else
510                                                 psf_log_printf (psf, "  version    : %d\n", psf->peak_info->version) ;
511
512                                         psf_log_printf (psf, "  time stamp : %d\n", psf->peak_info->timestamp) ;
513                                         psf_log_printf (psf, "    Ch   Position       Value\n") ;
514
515                                         cptr = ubuf.cbuf ;
516                                         for (k = 0 ; k < psf->sf.channels ; k++)
517                                         {       float value ;
518                                                 uint32_t position ;
519
520                                                 psf_binheader_readf (psf, "Ef4", &value, &position) ;
521                                                 psf->peak_info->peaks [k].value = value ;
522                                                 psf->peak_info->peaks [k].position = position ;
523
524                                                 snprintf (cptr, sizeof (ubuf.scbuf), "    %2d   %-12" PRId64 "   %g\n",
525                                                                 k, psf->peak_info->peaks [k].position, psf->peak_info->peaks [k].value) ;
526                                                 cptr [sizeof (ubuf.scbuf) - 1] = 0 ;
527                                                 psf_log_printf (psf, "%s", cptr) ;
528                                                 } ;
529
530                                         psf->peak_info->peak_loc = ((found_chunk & HAVE_SSND) == 0) ? SF_PEAK_START : SF_PEAK_END ;
531                                         break ;
532
533                         case SSND_MARKER :
534                                         if ((found_chunk & HAVE_AIFC) && (found_chunk & HAVE_FVER) == 0)
535                                                 psf_log_printf (psf, "*** Valid AIFC files should have an FVER chunk.\n") ;
536
537                                         paiff->ssnd_offset = psf_ftell (psf) - 8 ;
538                                         SSNDsize = chunk_size ;
539                                         psf_binheader_readf (psf, "E44", &(ssnd_fmt.offset), &(ssnd_fmt.blocksize)) ;
540
541                                         psf->datalength = SSNDsize - sizeof (ssnd_fmt) ;
542                                         psf->dataoffset = psf_ftell (psf) ;
543
544                                         if (psf->datalength > psf->filelength - psf->dataoffset || psf->datalength < 0)
545                                         {       psf_log_printf (psf, " SSND : %u (should be %D)\n", SSNDsize, psf->filelength - psf->dataoffset + sizeof (SSND_CHUNK)) ;
546                                                 psf->datalength = psf->filelength - psf->dataoffset ;
547                                                 }
548                                         else
549                                                 psf_log_printf (psf, " SSND : %u\n", SSNDsize) ;
550
551                                         if (ssnd_fmt.offset == 0 || psf->dataoffset + ssnd_fmt.offset == ssnd_fmt.blocksize)
552                                         {       psf_log_printf (psf, "  Offset     : %u\n", ssnd_fmt.offset) ;
553                                                 psf_log_printf (psf, "  Block Size : %u\n", ssnd_fmt.blocksize) ;
554
555                                                 psf->dataoffset += ssnd_fmt.offset ;
556                                                 psf->datalength -= ssnd_fmt.offset ;
557                                                 }
558                                         else
559                                         {       psf_log_printf (psf, "  Offset     : %u\n", ssnd_fmt.offset) ;
560                                                 psf_log_printf (psf, "  Block Size : %u ???\n", ssnd_fmt.blocksize) ;
561                                                 psf->dataoffset += ssnd_fmt.offset ;
562                                                 psf->datalength -= ssnd_fmt.offset ;
563                                                 } ;
564
565                                         /* Only set dataend if there really is data at the end. */
566                                         if (psf->datalength + psf->dataoffset < psf->filelength)
567                                                 psf->dataend = psf->datalength + psf->dataoffset ;
568
569                                         found_chunk |= HAVE_SSND ;
570
571                                         if (! psf->sf.seekable)
572                                                 break ;
573
574                                         /* Seek to end of SSND chunk. */
575                                         psf_fseek (psf, psf->dataoffset + psf->datalength, SEEK_SET) ;
576                                         break ;
577
578                         case c_MARKER :
579                                         if (chunk_size == 0)
580                                                 break ;
581                                         if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf))
582                                         {       psf_log_printf (psf, " %M : %d (too big)\n", marker, chunk_size) ;
583                                                 return SFE_INTERNAL ;
584                                                 } ;
585
586                                         cptr = ubuf.cbuf ;
587                                         psf_binheader_readf (psf, "b", cptr, chunk_size + (chunk_size & 1)) ;
588                                         cptr [chunk_size] = 0 ;
589
590                                         psf_sanitize_string (cptr, chunk_size) ;
591
592                                         psf_log_printf (psf, " %M : %s\n", marker, cptr) ;
593                                         psf_store_string (psf, SF_STR_COPYRIGHT, cptr) ;
594                                         chunk_size += chunk_size & 1 ;
595                                         break ;
596
597                         case AUTH_MARKER :
598                                         if (chunk_size == 0)
599                                                 break ;
600                                         if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf) - 1)
601                                         {       psf_log_printf (psf, " %M : %d (too big)\n", marker, chunk_size) ;
602                                                 return SFE_INTERNAL ;
603                                                 } ;
604
605                                         cptr = ubuf.cbuf ;
606                                         psf_binheader_readf (psf, "b", cptr, chunk_size + (chunk_size & 1)) ;
607                                         cptr [chunk_size] = 0 ;
608                                         psf_log_printf (psf, " %M : %s\n", marker, cptr) ;
609                                         psf_store_string (psf, SF_STR_ARTIST, cptr) ;
610                                         chunk_size += chunk_size & 1 ;
611                                         break ;
612
613                         case COMT_MARKER :
614                                 {       uint16_t count, id, len ;
615                                         uint32_t timestamp, bytes ;
616
617                                         if (chunk_size == 0)
618                                                 break ;
619                                         bytes = chunk_size ;
620                                         bytes -= psf_binheader_readf (psf, "E2", &count) ;
621                                         psf_log_printf (psf, " %M : %d\n  count  : %d\n", marker, chunk_size, count) ;
622
623                                         for (k = 0 ; k < count ; k++)
624                                         {       bytes -= psf_binheader_readf (psf, "E422", &timestamp, &id, &len) ;
625                                                 psf_log_printf (psf, "   time   : 0x%x\n   marker : %x\n   length : %d\n", timestamp, id, len) ;
626
627                                                 if (len + 1 > SIGNED_SIZEOF (ubuf.scbuf))
628                                                 {       psf_log_printf (psf, "\nError : string length (%d) too big.\n", len) ;
629                                                         return SFE_INTERNAL ;
630                                                         } ;
631
632                                                 cptr = ubuf.cbuf ;
633                                                 bytes -= psf_binheader_readf (psf, "b", cptr, len) ;
634                                                 cptr [len] = 0 ;
635                                                 psf_log_printf (psf, "   string : %s\n", cptr) ;
636                                                 } ;
637
638                                         if (bytes > 0)
639                                                 psf_binheader_readf (psf, "j", bytes) ;
640                                         } ;
641                                         break ;
642
643                         case APPL_MARKER :
644                                 {       unsigned appl_marker ;
645
646                                         if (chunk_size == 0)
647                                                 break ;
648                                         if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf) - 1)
649                                         {       psf_log_printf (psf, " %M : %u (too big, skipping)\n", marker, chunk_size) ;
650                                                 psf_binheader_readf (psf, "j", chunk_size + (chunk_size & 1)) ;
651                                                 break ;
652                                                 } ;
653
654                                         if (chunk_size < 4)
655                                         {       psf_log_printf (psf, " %M : %d (too small, skipping)\n", marker, chunk_size) ;
656                                                 psf_binheader_readf (psf, "j", chunk_size + (chunk_size & 1)) ;
657                                                 break ;
658                                                 } ;
659
660                                         cptr = ubuf.cbuf ;
661                                         psf_binheader_readf (psf, "mb", &appl_marker, cptr, chunk_size + (chunk_size & 1) - 4) ;
662                                         cptr [chunk_size] = 0 ;
663
664                                         for (k = 0 ; k < (int) chunk_size ; k++)
665                                                 if (! psf_isprint (cptr [k]))
666                                                 {       cptr [k] = 0 ;
667                                                         break ;
668                                                         } ;
669
670                                         psf_log_printf (psf, " %M : %d\n  AppSig : %M\n  Name   : %s\n", marker, chunk_size, appl_marker, cptr) ;
671                                         psf_store_string (psf, SF_STR_SOFTWARE, cptr) ;
672                                         chunk_size += chunk_size & 1 ;
673                                         } ;
674                                         break ;
675
676                         case NAME_MARKER :
677                                         if (chunk_size == 0)
678                                                 break ;
679                                         if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf) - 2)
680                                         {       psf_log_printf (psf, " %M : %d (too big)\n", marker, chunk_size) ;
681                                                 return SFE_INTERNAL ;
682                                                 } ;
683
684                                         cptr = ubuf.cbuf ;
685                                         psf_binheader_readf (psf, "b", cptr, chunk_size + (chunk_size & 1)) ;
686                                         cptr [chunk_size] = 0 ;
687                                         psf_log_printf (psf, " %M : %s\n", marker, cptr) ;
688                                         psf_store_string (psf, SF_STR_TITLE, cptr) ;
689                                         chunk_size += chunk_size & 1 ;
690                                         break ;
691
692                         case ANNO_MARKER :
693                                         if (chunk_size == 0)
694                                                 break ;
695                                         if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf) - 2)
696                                         {       psf_log_printf (psf, " %M : %d (too big)\n", marker, chunk_size) ;
697                                                 return SFE_INTERNAL ;
698                                                 } ;
699
700                                         cptr = ubuf.cbuf ;
701                                         psf_binheader_readf (psf, "b", cptr, chunk_size + (chunk_size & 1)) ;
702                                         cptr [chunk_size] = 0 ;
703                                         psf_log_printf (psf, " %M : %s\n", marker, cptr) ;
704                                         psf_store_string (psf, SF_STR_COMMENT, cptr) ;
705                                         chunk_size += chunk_size & 1 ;
706                                         break ;
707
708                         case INST_MARKER :
709                                         if (chunk_size != SIZEOF_INST_CHUNK)
710                                         {       psf_log_printf (psf, " %M : %d (should be %d)\n", marker, chunk_size, SIZEOF_INST_CHUNK) ;
711                                                 psf_binheader_readf (psf, "j", chunk_size) ;
712                                                 break ;
713                                                 } ;
714                                         psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
715                                         {       uint8_t bytes [6] ;
716                                                 int16_t gain ;
717
718                                                 if (psf->instrument == NULL && (psf->instrument = psf_instrument_alloc ()) == NULL)
719                                                         return SFE_MALLOC_FAILED ;
720
721                                                 psf_binheader_readf (psf, "b", bytes, 6) ;
722                                                 psf_log_printf (psf, "  Base Note : %u\n  Detune    : %u\n"
723                                                                                         "  Low  Note : %u\n  High Note : %u\n"
724                                                                                         "  Low  Vel. : %u\n  High Vel. : %u\n",
725                                                                                         bytes [0], bytes [1], bytes [2], bytes [3], bytes [4], bytes [5]) ;
726                                                 psf->instrument->basenote = bytes [0] ;
727                                                 psf->instrument->detune = bytes [1] ;
728                                                 psf->instrument->key_lo = bytes [2] ;
729                                                 psf->instrument->key_hi = bytes [3] ;
730                                                 psf->instrument->velocity_lo = bytes [4] ;
731                                                 psf->instrument->velocity_hi = bytes [5] ;
732                                                 psf_binheader_readf (psf, "E2", &gain) ;
733                                                 psf->instrument->gain = gain ;
734                                                 psf_log_printf (psf, "  Gain (dB) : %d\n", gain) ;
735                                                 } ;
736                                         {       int16_t mode ; /* 0 - no loop, 1 - forward looping, 2 - backward looping */
737                                                 const char      *loop_mode ;
738                                                 uint16_t begin, end ;
739
740                                                 psf_binheader_readf (psf, "E222", &mode, &begin, &end) ;
741                                                 loop_mode = get_loop_mode_str (mode) ;
742                                                 mode = get_loop_mode (mode) ;
743                                                 if (mode == SF_LOOP_NONE)
744                                                 {       psf->instrument->loop_count = 0 ;
745                                                         psf->instrument->loops [0].mode = SF_LOOP_NONE ;
746                                                         }
747                                                 else
748                                                 {       psf->instrument->loop_count = 1 ;
749                                                         psf->instrument->loops [0].mode = SF_LOOP_FORWARD ;
750                                                         psf->instrument->loops [0].start = begin ;
751                                                         psf->instrument->loops [0].end = end ;
752                                                         psf->instrument->loops [0].count = 0 ;
753                                                         } ;
754                                                 psf_log_printf (psf, "  Sustain\n   mode  : %d => %s\n   begin : %u\n   end   : %u\n",
755                                                                                         mode, loop_mode, begin, end) ;
756                                                 psf_binheader_readf (psf, "E222", &mode, &begin, &end) ;
757                                                 loop_mode = get_loop_mode_str (mode) ;
758                                                 mode = get_loop_mode (mode) ;
759                                                 if (mode == SF_LOOP_NONE)
760                                                         psf->instrument->loops [1].mode = SF_LOOP_NONE ;
761                                                 else
762                                                 {       psf->instrument->loop_count += 1 ;
763                                                         psf->instrument->loops [1].mode = SF_LOOP_FORWARD ;
764                                                         psf->instrument->loops [1].start = begin ;
765                                                         psf->instrument->loops [1].end = end ;
766                                                         psf->instrument->loops [1].count = 0 ;
767                                                         } ;
768                                                 psf_log_printf (psf, "  Release\n   mode  : %d => %s\n   begin : %u\n   end   : %u\n",
769                                                                                 mode, loop_mode, begin, end) ;
770                                                 } ;
771                                         instr_found++ ;
772                                         break ;
773
774                         case basc_MARKER :
775                                         psf_log_printf (psf, " basc : %u\n", chunk_size) ;
776
777                                         if ((error = aiff_read_basc_chunk (psf, chunk_size)))
778                                                 return error ;
779                                         break ;
780
781                         case MARK_MARKER :
782                                         psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
783                                         {       uint16_t mark_id, n = 0 ;
784                                                 uint32_t position ;
785
786                                                 bytesread = psf_binheader_readf (psf, "E2", &n) ;
787                                                 mark_count = n ;
788                                                 psf_log_printf (psf, "  Count : %u\n", mark_count) ;
789                                                 if (paiff->markstr != NULL)
790                                                 {       psf_log_printf (psf, "*** Second MARK chunk found. Throwing away the first.\n") ;
791                                                         free (paiff->markstr) ;
792                                                         } ;
793                                                 paiff->markstr = calloc (mark_count, sizeof (MARK_ID_POS)) ;
794                                                 if (paiff->markstr == NULL)
795                                                         return SFE_MALLOC_FAILED ;
796
797                                                 if (mark_count > 2500) /* 2500 is close to the largest number of cues possible because of block sizes */
798                                                 {       psf_log_printf (psf, "  More than 2500 markers, skipping!\n") ;
799                                                         psf_binheader_readf (psf, "j", chunk_size - bytesread) ;
800                                                         break ;
801                                                 } ;
802
803                                                 if (psf->cues)
804                                                 {       free (psf->cues) ;
805                                                         psf->cues = NULL ;
806                                                         } ;
807                                                 if ((psf->cues = psf_cues_alloc (mark_count)) == NULL)
808                                                         return SFE_MALLOC_FAILED ;
809
810                                                 for (n = 0 ; n < mark_count && bytesread < chunk_size ; n++)
811                                                 {       uint32_t pstr_len ;
812                                                         uint8_t ch ;
813
814                                                         bytesread += psf_binheader_readf (psf, "E241", &mark_id, &position, &ch) ;
815                                                         psf_log_printf (psf, "   Mark ID  : %u\n   Position : %u\n", mark_id, position) ;
816
817                                                         psf->cues->cue_points [n].indx = mark_id ;
818                                                         psf->cues->cue_points [n].position = 0 ;
819                                                         psf->cues->cue_points [n].fcc_chunk = MAKE_MARKER ('d', 'a', 't', 'a') ; /* always data */
820                                                         psf->cues->cue_points [n].chunk_start = 0 ;
821                                                         psf->cues->cue_points [n].block_start = 0 ;
822                                                         psf->cues->cue_points [n].sample_offset = position ;
823
824                                                         pstr_len = (ch & 1) ? ch : ch + 1 ;
825
826                                                         if (pstr_len < sizeof (ubuf.scbuf) - 1)
827                                                         {       bytesread += psf_binheader_readf (psf, "b", ubuf.scbuf, pstr_len) ;
828                                                                 ubuf.scbuf [pstr_len] = 0 ;
829                                                                 }
830                                                         else
831                                                         {       uint32_t read_len = pstr_len - (sizeof (ubuf.scbuf) - 1) ;
832                                                                 bytesread += psf_binheader_readf (psf, "bj", ubuf.scbuf, read_len, pstr_len - read_len) ;
833                                                                 ubuf.scbuf [sizeof (ubuf.scbuf) - 1] = 0 ;
834                                                                 }
835
836                                                         psf_log_printf (psf, "   Name     : %s\n", ubuf.scbuf) ;
837
838                                                         psf_strlcpy (psf->cues->cue_points [n].name, sizeof (psf->cues->cue_points [n].name), ubuf.cbuf) ;
839
840                                                         paiff->markstr [n].markerID = mark_id ;
841                                                         paiff->markstr [n].position = position ;
842                                                         /*
843                                                         **      TODO if ubuf.scbuf is equal to
844                                                         **      either Beg_loop, Beg loop or beg loop and spam
845                                                         **      if (psf->instrument == NULL && (psf->instrument = psf_instrument_alloc ()) == NULL)
846                                                         **              return SFE_MALLOC_FAILED ;
847                                                         */
848                                                         } ;
849                                                 } ;
850                                         mark_found++ ;
851                                         psf_binheader_readf (psf, "j", chunk_size - bytesread) ;
852                                         break ;
853
854                         case FVER_MARKER :
855                                         found_chunk |= HAVE_FVER ;
856                                         /* Falls through. */
857
858                         case SFX_MARKER :
859                                         psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
860                                         psf_binheader_readf (psf, "j", chunk_size) ;
861                                         break ;
862
863                         case NONE_MARKER :
864                                         /* Fix for broken AIFC files with incorrect COMM chunk length. */
865                                         chunk_size = (chunk_size >> 24) - 3 ;
866                                         psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
867                                         psf_binheader_readf (psf, "j", make_size_t (chunk_size)) ;
868                                         break ;
869
870                         case CHAN_MARKER :
871                                         if (chunk_size < 12)
872                                         {       psf_log_printf (psf, " %M : %d (should be >= 12)\n", marker, chunk_size) ;
873                                                 psf_binheader_readf (psf, "j", chunk_size) ;
874                                                 break ;
875                                                 }
876
877                                         psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
878
879                                         if ((error = aiff_read_chanmap (psf, chunk_size)))
880                                                 return error ;
881                                         break ;
882
883                         default :
884                                         if (chunk_size >= 0xffff0000)
885                                         {       done = SF_TRUE ;
886                                                 psf_log_printf (psf, "*** Unknown chunk marker (%X) at position %D with length %u. Exiting parser.\n", marker, psf_ftell (psf) - 8, chunk_size) ;
887                                                 break ;
888                                                 } ;
889
890                                         if (psf_isprint ((marker >> 24) & 0xFF) && psf_isprint ((marker >> 16) & 0xFF)
891                                                 && psf_isprint ((marker >> 8) & 0xFF) && psf_isprint (marker & 0xFF))
892                                         {       psf_log_printf (psf, " %M : %u (unknown marker)\n", marker, chunk_size) ;
893
894                                                 psf_binheader_readf (psf, "j", chunk_size) ;
895                                                 break ;
896                                                 } ;
897
898                                         if (psf_ftell (psf) & 0x03)
899                                         {       psf_log_printf (psf, "  Unknown chunk marker at position %D. Resynching.\n", psf_ftell (psf) - 8) ;
900                                                 psf_binheader_readf (psf, "j", -3) ;
901                                                 break ;
902                                                 } ;
903                                         psf_log_printf (psf, "*** Unknown chunk marker %X at position %D. Exiting parser.\n", marker, psf_ftell (psf)) ;
904                                         done = SF_TRUE ;
905                                         break ;
906                         } ;     /* switch (marker) */
907
908                 if (chunk_size >= psf->filelength)
909                 {       psf_log_printf (psf, "*** Chunk size %u > file length %D. Exiting parser.\n", chunk_size, psf->filelength) ;
910                         break ;
911                         } ;
912
913                 if ((! psf->sf.seekable) && (found_chunk & HAVE_SSND))
914                         break ;
915
916                 if (psf_ftell (psf) >= psf->filelength - (2 * SIGNED_SIZEOF (int32_t)))
917                         break ;
918                 } ; /* while (1) */
919
920         if (instr_found && mark_found)
921         {       int ji, str_index ;
922                 /* Next loop will convert markers to loop positions for internal handling */
923                 for (ji = 0 ; ji < psf->instrument->loop_count ; ji ++)
924                 {       if (ji < ARRAY_LEN (psf->instrument->loops))
925                         {       psf->instrument->loops [ji].start = marker_to_position (paiff->markstr, psf->instrument->loops [ji].start, mark_count) ;
926                                 psf->instrument->loops [ji].end = marker_to_position (paiff->markstr, psf->instrument->loops [ji].end, mark_count) ;
927                                 psf->instrument->loops [ji].mode = SF_LOOP_FORWARD ;
928                                 } ;
929                         } ;
930
931                 /* The markers that correspond to loop positions can now be removed from cues struct */
932                 if (psf->cues->cue_count > (uint32_t) (psf->instrument->loop_count * 2))
933                 {       uint32_t j ;
934
935                         for (j = 0 ; j < psf->cues->cue_count - (uint32_t) (psf->instrument->loop_count * 2) ; j ++)
936                         {       /* This simply copies the information in cues above loop positions and writes it at current count instead */
937                                 psf->cues->cue_points [j].indx = psf->cues->cue_points [j + psf->instrument->loop_count * 2].indx ;
938                                 psf->cues->cue_points [j].position = psf->cues->cue_points [j + psf->instrument->loop_count * 2].position ;
939                                 psf->cues->cue_points [j].fcc_chunk = psf->cues->cue_points [j + psf->instrument->loop_count * 2].fcc_chunk ;
940                                 psf->cues->cue_points [j].chunk_start = psf->cues->cue_points [j + psf->instrument->loop_count * 2].chunk_start ;
941                                 psf->cues->cue_points [j].block_start = psf->cues->cue_points [j + psf->instrument->loop_count * 2].block_start ;
942                                 psf->cues->cue_points [j].sample_offset = psf->cues->cue_points [j + psf->instrument->loop_count * 2].sample_offset ;
943                                 for (str_index = 0 ; str_index < 256 ; str_index++)
944                                         psf->cues->cue_points [j].name [str_index] = psf->cues->cue_points [j + psf->instrument->loop_count * 2].name [str_index] ;
945                                 } ;
946                         psf->cues->cue_count -= psf->instrument->loop_count * 2 ;
947                         } else
948                         {       /* All the cues were in fact loop positions so we can actually remove the cues altogether */
949                                 free (psf->cues) ;
950                                 psf->cues = NULL ;
951                                 }
952                 } ;
953
954         if (psf->sf.channels < 1)
955                 return SFE_CHANNEL_COUNT_ZERO ;
956
957         if (psf->sf.channels > SF_MAX_CHANNELS)
958                 return SFE_CHANNEL_COUNT ;
959
960         if (! (found_chunk & HAVE_FORM))
961                 return SFE_AIFF_NO_FORM ;
962
963         if (! (found_chunk & HAVE_AIFF))
964                 return SFE_AIFF_COMM_NO_FORM ;
965
966         if (! (found_chunk & HAVE_COMM))
967                 return SFE_AIFF_SSND_NO_COMM ;
968
969         if (! psf->dataoffset)
970                 return SFE_AIFF_NO_DATA ;
971
972         return 0 ;
973 } /* aiff_read_header */
974
975 static int
976 aiff_close (SF_PRIVATE *psf)
977 {       AIFF_PRIVATE *paiff = psf->container_data ;
978
979         if (paiff != NULL && paiff->markstr != NULL)
980         {       free (paiff->markstr) ;
981                 paiff->markstr = NULL ;
982                 } ;
983
984         if (psf->file.mode == SFM_WRITE || psf->file.mode == SFM_RDWR)
985         {       aiff_write_tailer (psf) ;
986                 aiff_write_header (psf, SF_TRUE) ;
987                 } ;
988
989         return 0 ;
990 } /* aiff_close */
991
992 static int
993 aiff_read_comm_chunk (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
994 {       BUF_UNION       ubuf ;
995         int subformat, samplerate ;
996
997         ubuf.scbuf [0] = 0 ;
998
999         /* The COMM chunk has an int aligned to an odd word boundary. Some
1000         ** procesors are not able to deal with this (ie bus fault) so we have
1001         ** to take special care.
1002         */
1003
1004         psf_binheader_readf (psf, "E242b", &(comm_fmt->numChannels), &(comm_fmt->numSampleFrames),
1005                                 &(comm_fmt->sampleSize), &(comm_fmt->sampleRate), SIGNED_SIZEOF (comm_fmt->sampleRate)) ;
1006
1007         if (comm_fmt->size > 0x10000 && (comm_fmt->size & 0xffff) == 0)
1008         {       psf_log_printf (psf, " COMM : %d (0x%x) *** should be ", comm_fmt->size, comm_fmt->size) ;
1009                 comm_fmt->size = ENDSWAP_32 (comm_fmt->size) ;
1010                 psf_log_printf (psf, "%d (0x%x)\n", comm_fmt->size, comm_fmt->size) ;
1011                 }
1012         else
1013                 psf_log_printf (psf, " COMM : %d\n", comm_fmt->size) ;
1014
1015         if (comm_fmt->size == SIZEOF_AIFF_COMM)
1016                 comm_fmt->encoding = NONE_MARKER ;
1017         else if (comm_fmt->size == SIZEOF_AIFC_COMM_MIN)
1018                 psf_binheader_readf (psf, "Em", &(comm_fmt->encoding)) ;
1019         else if (comm_fmt->size >= SIZEOF_AIFC_COMM)
1020         {       uint8_t encoding_len ;
1021                 unsigned read_len ;
1022
1023                 psf_binheader_readf (psf, "Em1", &(comm_fmt->encoding), &encoding_len) ;
1024
1025                 comm_fmt->size = SF_MIN (sizeof (ubuf.scbuf), make_size_t (comm_fmt->size)) ;
1026                 memset (ubuf.scbuf, 0, comm_fmt->size) ;
1027                 read_len = comm_fmt->size - SIZEOF_AIFC_COMM + 1 ;
1028                 psf_binheader_readf (psf, "b", ubuf.scbuf, read_len) ;
1029                 ubuf.scbuf [read_len + 1] = 0 ;
1030                 } ;
1031
1032         samplerate = tenbytefloat2int (comm_fmt->sampleRate) ;
1033
1034         psf_log_printf (psf, "  Sample Rate : %d\n", samplerate) ;
1035         psf_log_printf (psf, "  Frames      : %u%s\n", comm_fmt->numSampleFrames, (comm_fmt->numSampleFrames == 0 && psf->filelength > 104) ? " (Should not be 0)" : "") ;
1036
1037         if (comm_fmt->numChannels < 1 || comm_fmt->numChannels > SF_MAX_CHANNELS)
1038         {       psf_log_printf (psf, "  Channels    : %d (should be >= 1 and < %d)\n", comm_fmt->numChannels, SF_MAX_CHANNELS) ;
1039                 return SFE_CHANNEL_COUNT_BAD ;
1040                 } ;
1041
1042         psf_log_printf (psf, "  Channels    : %d\n", comm_fmt->numChannels) ;
1043
1044         /* Found some broken 'fl32' files with comm.samplesize == 16. Fix it here. */
1045         if ((comm_fmt->encoding == fl32_MARKER || comm_fmt->encoding == FL32_MARKER) && comm_fmt->sampleSize != 32)
1046         {       psf_log_printf (psf, "  Sample Size : %d (should be 32)\n", comm_fmt->sampleSize) ;
1047                 comm_fmt->sampleSize = 32 ;
1048                 }
1049         else if ((comm_fmt->encoding == fl64_MARKER || comm_fmt->encoding == FL64_MARKER) && comm_fmt->sampleSize != 64)
1050         {       psf_log_printf (psf, "  Sample Size : %d (should be 64)\n", comm_fmt->sampleSize) ;
1051                 comm_fmt->sampleSize = 64 ;
1052                 }
1053         else
1054                 psf_log_printf (psf, "  Sample Size : %d\n", comm_fmt->sampleSize) ;
1055
1056         subformat = s_bitwidth_to_subformat (comm_fmt->sampleSize) ;
1057
1058         psf->sf.samplerate = samplerate ;
1059         psf->sf.frames = comm_fmt->numSampleFrames ;
1060         psf->sf.channels = comm_fmt->numChannels ;
1061         psf->bytewidth = BITWIDTH2BYTES (comm_fmt->sampleSize) ;
1062
1063         psf->endian = SF_ENDIAN_BIG ;
1064
1065         switch (comm_fmt->encoding)
1066         {       case NONE_MARKER :
1067                                 psf->sf.format = (SF_FORMAT_AIFF | subformat) ;
1068                                 break ;
1069
1070                 case twos_MARKER :
1071                 case in24_MARKER :
1072                 case in32_MARKER :
1073                                 psf->sf.format = (SF_ENDIAN_BIG | SF_FORMAT_AIFF | subformat) ;
1074                                 break ;
1075
1076                 case sowt_MARKER :
1077                 case ni24_MARKER :
1078                 case ni32_MARKER :
1079                                 psf->endian = SF_ENDIAN_LITTLE ;
1080                                 psf->sf.format = (SF_ENDIAN_LITTLE | SF_FORMAT_AIFF | subformat) ;
1081                                 break ;
1082
1083                 case fl32_MARKER :
1084                 case FL32_MARKER :
1085                                 psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_FLOAT) ;
1086                                 break ;
1087
1088                 case ulaw_MARKER :
1089                 case ULAW_MARKER :
1090                                 psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_ULAW) ;
1091                                 break ;
1092
1093                 case alaw_MARKER :
1094                 case ALAW_MARKER :
1095                                 psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_ALAW) ;
1096                                 break ;
1097
1098                 case fl64_MARKER :
1099                 case FL64_MARKER :
1100                                 psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_DOUBLE) ;
1101                                 break ;
1102
1103                 case raw_MARKER :
1104                                 psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_PCM_U8) ;
1105                                 break ;
1106
1107                 case DWVW_MARKER :
1108                                 psf->sf.format = SF_FORMAT_AIFF ;
1109                                 switch (comm_fmt->sampleSize)
1110                                 {       case 12 :
1111                                                 psf->sf.format |= SF_FORMAT_DWVW_12 ;
1112                                                 break ;
1113                                         case 16 :
1114                                                 psf->sf.format |= SF_FORMAT_DWVW_16 ;
1115                                                 break ;
1116                                         case 24 :
1117                                                 psf->sf.format |= SF_FORMAT_DWVW_24 ;
1118                                                 break ;
1119
1120                                         default :
1121                                                 psf->sf.format |= SF_FORMAT_DWVW_N ;
1122                                                 break ;
1123                                         } ;
1124                                 break ;
1125
1126                 case GSM_MARKER :
1127                                 psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_GSM610) ;
1128                                 break ;
1129
1130
1131                 case ima4_MARKER :
1132                                 psf->endian = SF_ENDIAN_BIG ;
1133                                 psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_IMA_ADPCM) ;
1134                                 break ;
1135
1136                 default :
1137                         psf_log_printf (psf, "AIFC : Unimplemented format : %M\n", comm_fmt->encoding) ;
1138                         return SFE_UNIMPLEMENTED ;
1139                 } ;
1140
1141         if (! ubuf.scbuf [0])
1142                 psf_log_printf (psf, "  Encoding    : %M\n", comm_fmt->encoding) ;
1143         else
1144                 psf_log_printf (psf, "  Encoding    : %M => %s\n", comm_fmt->encoding, ubuf.scbuf) ;
1145
1146         return 0 ;
1147 } /* aiff_read_comm_chunk */
1148
1149
1150 /*==========================================================================================
1151 */
1152
1153 static void
1154 aiff_rewrite_header (SF_PRIVATE *psf)
1155 {
1156         /* Assuming here that the header has already been written and just
1157         ** needs to be corrected for new data length. That means that we
1158         ** only change the length fields of the FORM and SSND chunks ;
1159         ** everything else can be skipped over.
1160         */
1161         int k, ch, comm_size, comm_frames ;
1162
1163         psf_fseek (psf, 0, SEEK_SET) ;
1164         psf_fread (psf->header.ptr, psf->dataoffset, 1, psf) ;
1165
1166         psf->header.indx = 0 ;
1167
1168         /* FORM chunk. */
1169         psf_binheader_writef (psf, "Etm8", BHWm (FORM_MARKER), BHW8 (psf->filelength - 8)) ;
1170
1171         /* COMM chunk. */
1172         if ((k = psf_find_read_chunk_m32 (&psf->rchunks, COMM_MARKER)) >= 0)
1173         {       psf->header.indx = psf->rchunks.chunks [k].offset - 8 ;
1174                 comm_frames = psf->sf.frames ;
1175                 comm_size = psf->rchunks.chunks [k].len ;
1176                 psf_binheader_writef (psf, "Em42t4", BHWm (COMM_MARKER), BHW4 (comm_size), BHW2 (psf->sf.channels), BHW4 (comm_frames)) ;
1177                 } ;
1178
1179         /* PEAK chunk. */
1180         if ((k = psf_find_read_chunk_m32 (&psf->rchunks, PEAK_MARKER)) >= 0)
1181         {       psf->header.indx = psf->rchunks.chunks [k].offset - 8 ;
1182                 psf_binheader_writef (psf, "Em4", BHWm (PEAK_MARKER), BHW4 (AIFF_PEAK_CHUNK_SIZE (psf->sf.channels))) ;
1183                 psf_binheader_writef (psf, "E44", BHW4 (1), BHW4 (time (NULL))) ;
1184                 for (ch = 0 ; ch < psf->sf.channels ; ch++)
1185                         psf_binheader_writef (psf, "Eft8", BHWf ((float) psf->peak_info->peaks [ch].value), BHW8 (psf->peak_info->peaks [ch].position)) ;
1186                 } ;
1187
1188
1189         /* SSND chunk. */
1190         if ((k = psf_find_read_chunk_m32 (&psf->rchunks, SSND_MARKER)) >= 0)
1191         {       psf->header.indx = psf->rchunks.chunks [k].offset - 8 ;
1192                 psf_binheader_writef (psf, "Etm8", BHWm (SSND_MARKER), BHW8 (psf->datalength + SIZEOF_SSND_CHUNK)) ;
1193                 } ;
1194
1195         /* Header mangling complete so write it out. */
1196         psf_fseek (psf, 0, SEEK_SET) ;
1197         psf_fwrite (psf->header.ptr, psf->header.indx, 1, psf) ;
1198
1199         return ;
1200 } /* aiff_rewrite_header */
1201
1202 static int
1203 aiff_write_header (SF_PRIVATE *psf, int calc_length)
1204 {       sf_count_t              current ;
1205         AIFF_PRIVATE    *paiff ;
1206         uint8_t comm_sample_rate [10], comm_zero_bytes [2] = { 0, 0 } ;
1207         uint32_t        comm_type, comm_size, comm_encoding, comm_frames = 0, uk ;
1208         int                             k, endian, has_data = SF_FALSE ;
1209         int16_t                 bit_width ;
1210
1211         if ((paiff = psf->container_data) == NULL)
1212                 return SFE_INTERNAL ;
1213
1214         current = psf_ftell (psf) ;
1215
1216         if (current > psf->dataoffset)
1217                 has_data = SF_TRUE ;
1218
1219         if (calc_length)
1220         {       psf->filelength = psf_get_filelen (psf) ;
1221
1222                 psf->datalength = psf->filelength - psf->dataoffset ;
1223                 if (psf->dataend)
1224                         psf->datalength -= psf->filelength - psf->dataend ;
1225
1226                 if (psf->bytewidth > 0)
1227                         psf->sf.frames = psf->datalength / (psf->bytewidth * psf->sf.channels) ;
1228                 } ;
1229
1230         if (psf->file.mode == SFM_RDWR && psf->dataoffset > 0 && psf->rchunks.count > 0)
1231         {       aiff_rewrite_header (psf) ;
1232                 if (current > 0)
1233                         psf_fseek (psf, current, SEEK_SET) ;
1234                 return 0 ;
1235                 } ;
1236
1237         endian = SF_ENDIAN (psf->sf.format) ;
1238         if (CPU_IS_LITTLE_ENDIAN && endian == SF_ENDIAN_CPU)
1239                 endian = SF_ENDIAN_LITTLE ;
1240
1241         /* Standard value here. */
1242         bit_width = psf->bytewidth * 8 ;
1243         comm_frames = (psf->sf.frames > 0xFFFFFFFF) ? 0xFFFFFFFF : psf->sf.frames ;
1244
1245         switch (SF_CODEC (psf->sf.format) | endian)
1246         {       case SF_FORMAT_PCM_S8 | SF_ENDIAN_BIG :
1247                         psf->endian = SF_ENDIAN_BIG ;
1248                         comm_type = AIFC_MARKER ;
1249                         comm_size = SIZEOF_AIFC_COMM ;
1250                         comm_encoding = twos_MARKER ;
1251                         break ;
1252
1253                 case SF_FORMAT_PCM_S8 | SF_ENDIAN_LITTLE :
1254                         psf->endian = SF_ENDIAN_LITTLE ;
1255                         comm_type = AIFC_MARKER ;
1256                         comm_size = SIZEOF_AIFC_COMM ;
1257                         comm_encoding = sowt_MARKER ;
1258                         break ;
1259
1260                 case SF_FORMAT_PCM_16 | SF_ENDIAN_BIG :
1261                         psf->endian = SF_ENDIAN_BIG ;
1262                         comm_type = AIFC_MARKER ;
1263                         comm_size = SIZEOF_AIFC_COMM ;
1264                         comm_encoding = twos_MARKER ;
1265                         break ;
1266
1267                 case SF_FORMAT_PCM_16 | SF_ENDIAN_LITTLE :
1268                         psf->endian = SF_ENDIAN_LITTLE ;
1269                         comm_type = AIFC_MARKER ;
1270                         comm_size = SIZEOF_AIFC_COMM ;
1271                         comm_encoding = sowt_MARKER ;
1272                         break ;
1273
1274                 case SF_FORMAT_PCM_24 | SF_ENDIAN_BIG :
1275                         psf->endian = SF_ENDIAN_BIG ;
1276                         comm_type = AIFC_MARKER ;
1277                         comm_size = SIZEOF_AIFC_COMM ;
1278                         comm_encoding = in24_MARKER ;
1279                         break ;
1280
1281                 case SF_FORMAT_PCM_24 | SF_ENDIAN_LITTLE :
1282                         psf->endian = SF_ENDIAN_LITTLE ;
1283                         comm_type = AIFC_MARKER ;
1284                         comm_size = SIZEOF_AIFC_COMM ;
1285                         comm_encoding = ni24_MARKER ;
1286                         break ;
1287
1288                 case SF_FORMAT_PCM_32 | SF_ENDIAN_BIG :
1289                         psf->endian = SF_ENDIAN_BIG ;
1290                         comm_type = AIFC_MARKER ;
1291                         comm_size = SIZEOF_AIFC_COMM ;
1292                         comm_encoding = in32_MARKER ;
1293                         break ;
1294
1295                 case SF_FORMAT_PCM_32 | SF_ENDIAN_LITTLE :
1296                         psf->endian = SF_ENDIAN_LITTLE ;
1297                         comm_type = AIFC_MARKER ;
1298                         comm_size = SIZEOF_AIFC_COMM ;
1299                         comm_encoding = ni32_MARKER ;
1300                         break ;
1301
1302                 case SF_FORMAT_PCM_S8 :                 /* SF_ENDIAN_FILE */
1303                 case SF_FORMAT_PCM_16 :
1304                 case SF_FORMAT_PCM_24 :
1305                 case SF_FORMAT_PCM_32 :
1306                         psf->endian = SF_ENDIAN_BIG ;
1307                         comm_type = AIFF_MARKER ;
1308                         comm_size = SIZEOF_AIFF_COMM ;
1309                         comm_encoding = 0 ;
1310                         break ;
1311
1312                 case SF_FORMAT_FLOAT :                                  /* Big endian floating point. */
1313                                 psf->endian = SF_ENDIAN_BIG ;
1314                                 comm_type = AIFC_MARKER ;
1315                                 comm_size = SIZEOF_AIFC_COMM ;
1316                                 comm_encoding = FL32_MARKER ;   /* Use 'FL32' because its easier to read. */
1317                                 break ;
1318
1319                 case SF_FORMAT_DOUBLE :                                 /* Big endian double precision floating point. */
1320                                 psf->endian = SF_ENDIAN_BIG ;
1321                                 comm_type = AIFC_MARKER ;
1322                                 comm_size = SIZEOF_AIFC_COMM ;
1323                                 comm_encoding = FL64_MARKER ;   /* Use 'FL64' because its easier to read. */
1324                                 break ;
1325
1326                 case SF_FORMAT_ULAW :
1327                                 psf->endian = SF_ENDIAN_BIG ;
1328                                 comm_type = AIFC_MARKER ;
1329                                 comm_size = SIZEOF_AIFC_COMM ;
1330                                 comm_encoding = ulaw_MARKER ;
1331                                 break ;
1332
1333                 case SF_FORMAT_ALAW :
1334                                 psf->endian = SF_ENDIAN_BIG ;
1335                                 comm_type = AIFC_MARKER ;
1336                                 comm_size = SIZEOF_AIFC_COMM ;
1337                                 comm_encoding = alaw_MARKER ;
1338                                 break ;
1339
1340                 case SF_FORMAT_PCM_U8 :
1341                                 psf->endian = SF_ENDIAN_BIG ;
1342                                 comm_type = AIFC_MARKER ;
1343                                 comm_size = SIZEOF_AIFC_COMM ;
1344                                 comm_encoding = raw_MARKER ;
1345                                 break ;
1346
1347                 case SF_FORMAT_DWVW_12 :
1348                                 psf->endian = SF_ENDIAN_BIG ;
1349                                 comm_type = AIFC_MARKER ;
1350                                 comm_size = SIZEOF_AIFC_COMM ;
1351                                 comm_encoding = DWVW_MARKER ;
1352
1353                                 /* Override standard value here.*/
1354                                 bit_width = 12 ;
1355                                 break ;
1356
1357                 case SF_FORMAT_DWVW_16 :
1358                                 psf->endian = SF_ENDIAN_BIG ;
1359                                 comm_type = AIFC_MARKER ;
1360                                 comm_size = SIZEOF_AIFC_COMM ;
1361                                 comm_encoding = DWVW_MARKER ;
1362
1363                                 /* Override standard value here.*/
1364                                 bit_width = 16 ;
1365                                 break ;
1366
1367                 case SF_FORMAT_DWVW_24 :
1368                                 psf->endian = SF_ENDIAN_BIG ;
1369                                 comm_type = AIFC_MARKER ;
1370                                 comm_size = SIZEOF_AIFC_COMM ;
1371                                 comm_encoding = DWVW_MARKER ;
1372
1373                                 /* Override standard value here.*/
1374                                 bit_width = 24 ;
1375                                 break ;
1376
1377                 case SF_FORMAT_GSM610 :
1378                                 psf->endian = SF_ENDIAN_BIG ;
1379                                 comm_type = AIFC_MARKER ;
1380                                 comm_size = SIZEOF_AIFC_COMM ;
1381                                 comm_encoding = GSM_MARKER ;
1382
1383                                 /* Override standard value here.*/
1384                                 bit_width = 16 ;
1385                                 break ;
1386
1387                 case SF_FORMAT_IMA_ADPCM :
1388                                 psf->endian = SF_ENDIAN_BIG ;
1389                                 comm_type = AIFC_MARKER ;
1390                                 comm_size = SIZEOF_AIFC_COMM ;
1391                                 comm_encoding = ima4_MARKER ;
1392
1393                                 /* Override standard value here.*/
1394                                 bit_width = 16 ;
1395                                 comm_frames = psf->sf.frames / AIFC_IMA4_SAMPLES_PER_BLOCK ;
1396                                 break ;
1397
1398                 default : return SFE_BAD_OPEN_FORMAT ;
1399                 } ;
1400
1401         /* Reset the current header length to zero. */
1402         psf->header.ptr [0] = 0 ;
1403         psf->header.indx = 0 ;
1404         psf_fseek (psf, 0, SEEK_SET) ;
1405
1406         psf_binheader_writef (psf, "Etm8", BHWm (FORM_MARKER), BHW8 (psf->filelength - 8)) ;
1407
1408         /* Write AIFF/AIFC marker and COM chunk. */
1409         if (comm_type == AIFC_MARKER)
1410                 /* AIFC must have an FVER chunk. */
1411                 psf_binheader_writef (psf, "Emm44", BHWm (comm_type), BHWm (FVER_MARKER), BHW4 (4), BHW4 (0xA2805140)) ;
1412         else
1413                 psf_binheader_writef (psf, "Em", BHWm (comm_type)) ;
1414
1415         paiff->comm_offset = psf->header.indx - 8 ;
1416
1417         memset (comm_sample_rate, 0, sizeof (comm_sample_rate)) ;
1418         uint2tenbytefloat (psf->sf.samplerate, comm_sample_rate) ;
1419
1420         psf_binheader_writef (psf, "Em42t42", BHWm (COMM_MARKER), BHW4 (comm_size), BHW2 (psf->sf.channels), BHW4 (comm_frames), BHW2 (bit_width)) ;
1421         psf_binheader_writef (psf, "b", BHWv (comm_sample_rate), BHWz (sizeof (comm_sample_rate))) ;
1422
1423         /* AIFC chunks have some extra data. */
1424         if (comm_type == AIFC_MARKER)
1425                 psf_binheader_writef (psf, "mb", BHWm (comm_encoding), BHWv (comm_zero_bytes), BHWz (sizeof (comm_zero_bytes))) ;
1426
1427         if (psf->channel_map && paiff->chanmap_tag)
1428                 psf_binheader_writef (psf, "Em4444", BHWm (CHAN_MARKER), BHW4 (12), BHW4 (paiff->chanmap_tag), BHW4 (0), BHW4 (0)) ;
1429
1430         /* Check if there's a INST chunk to write */
1431         if (psf->instrument != NULL && psf->cues != NULL)
1432         {       /* Huge chunk of code removed here because it had egregious errors that were
1433                 ** not detected by either the compiler or the tests. It was found when updating
1434                 ** the way psf_binheader_writef works.
1435                 */
1436                 }
1437         else if (psf->instrument == NULL && psf->cues != NULL)
1438         {       /* There are cues but no loops */
1439                 uint32_t idx ;
1440                 int totalStringLength = 0, stringLength ;
1441
1442                 /* Here we count how many bytes will the pascal strings need */
1443                 for (idx = 0 ; idx < psf->cues->cue_count ; idx++)
1444                 {       stringLength = strlen (psf->cues->cue_points [idx].name) + 1 ; /* We'll count the first byte also of every pascal string */
1445                         totalStringLength += stringLength + (stringLength % 2 == 0 ? 0 : 1) ;
1446                         } ;
1447
1448                 psf_binheader_writef (psf, "Em42",
1449                         BHWm (MARK_MARKER), BHW4 (2 + psf->cues->cue_count * (2 + 4) + totalStringLength), BHW2 (psf->cues->cue_count)) ;
1450
1451                 for (idx = 0 ; idx < psf->cues->cue_count ; idx++)
1452                         psf_binheader_writef (psf, "E24p", BHW2 (psf->cues->cue_points [idx].indx), BHW4 (psf->cues->cue_points [idx].sample_offset), BHWp (psf->cues->cue_points [idx].name)) ;
1453                 } ;
1454
1455         if (psf->strings.flags & SF_STR_LOCATE_START)
1456                 aiff_write_strings (psf, SF_STR_LOCATE_START) ;
1457
1458         if (psf->peak_info != NULL && psf->peak_info->peak_loc == SF_PEAK_START)
1459         {       psf_binheader_writef (psf, "Em4", BHWm (PEAK_MARKER), BHW4 (AIFF_PEAK_CHUNK_SIZE (psf->sf.channels))) ;
1460                 psf_binheader_writef (psf, "E44", BHW4 (1), BHW4 (time (NULL))) ;
1461                 for (k = 0 ; k < psf->sf.channels ; k++)
1462                         psf_binheader_writef (psf, "Eft8", BHWf ((float) psf->peak_info->peaks [k].value), BHW8 (psf->peak_info->peaks [k].position)) ;
1463                 } ;
1464
1465         /* Write custom headers. */
1466         for (uk = 0 ; uk < psf->wchunks.used ; uk++)
1467                 psf_binheader_writef (psf, "Em4b", BHWm (psf->wchunks.chunks [uk].mark32), BHW4 (psf->wchunks.chunks [uk].len), BHWv (psf->wchunks.chunks [uk].data), BHWz (psf->wchunks.chunks [uk].len)) ;
1468
1469         /* Write SSND chunk. */
1470         paiff->ssnd_offset = psf->header.indx ;
1471         psf_binheader_writef (psf, "Etm844", BHWm (SSND_MARKER), BHW8 (psf->datalength + SIZEOF_SSND_CHUNK), BHW4 (0), BHW4 (0)) ;
1472
1473         /* Header construction complete so write it out. */
1474         psf_fwrite (psf->header.ptr, psf->header.indx, 1, psf) ;
1475
1476         if (psf->error)
1477                 return psf->error ;
1478
1479         if (has_data && psf->dataoffset != psf->header.indx)
1480                 return psf->error = SFE_INTERNAL ;
1481
1482         psf->dataoffset = psf->header.indx ;
1483
1484         if (! has_data)
1485                 psf_fseek (psf, psf->dataoffset, SEEK_SET) ;
1486         else if (current > 0)
1487                 psf_fseek (psf, current, SEEK_SET) ;
1488
1489         return psf->error ;
1490 } /* aiff_write_header */
1491
1492 static int
1493 aiff_write_tailer (SF_PRIVATE *psf)
1494 {       int             k ;
1495
1496         /* Reset the current header length to zero. */
1497         psf->header.ptr [0] = 0 ;
1498         psf->header.indx = 0 ;
1499
1500         psf->dataend = psf_fseek (psf, 0, SEEK_END) ;
1501
1502         /* Make sure tailer data starts at even byte offset. Pad if necessary. */
1503         if (psf->dataend % 2 == 1)
1504         {       psf_fwrite (psf->header.ptr, 1, 1, psf) ;
1505                 psf->dataend ++ ;
1506                 } ;
1507
1508         if (psf->peak_info != NULL && psf->peak_info->peak_loc == SF_PEAK_END)
1509         {       psf_binheader_writef (psf, "Em4", BHWm (PEAK_MARKER), BHW4 (AIFF_PEAK_CHUNK_SIZE (psf->sf.channels))) ;
1510                 psf_binheader_writef (psf, "E44", BHW4 (1), BHW4 (time (NULL))) ;
1511                 for (k = 0 ; k < psf->sf.channels ; k++)
1512                         psf_binheader_writef (psf, "Eft8", BHWf ((float) psf->peak_info->peaks [k].value), BHW8 (psf->peak_info->peaks [k].position)) ;
1513                 } ;
1514
1515         if (psf->strings.flags & SF_STR_LOCATE_END)
1516                 aiff_write_strings (psf, SF_STR_LOCATE_END) ;
1517
1518         /* Write the tailer. */
1519         if (psf->header.indx > 0)
1520                 psf_fwrite (psf->header.ptr, psf->header.indx, 1, psf) ;
1521
1522         return 0 ;
1523 } /* aiff_write_tailer */
1524
1525 static void
1526 aiff_write_strings (SF_PRIVATE *psf, int location)
1527 {       int     k, slen ;
1528
1529         for (k = 0 ; k < SF_MAX_STRINGS ; k++)
1530         {       if (psf->strings.data [k].type == 0)
1531                         break ;
1532
1533                 if (psf->strings.data [k].flags != location)
1534                         continue ;
1535
1536                 switch (psf->strings.data [k].type)
1537                 {       case SF_STR_SOFTWARE :
1538                                 slen = strlen (psf->strings.storage + psf->strings.data [k].offset) ;
1539                                 psf_binheader_writef (psf, "Em4mb", BHWm (APPL_MARKER), BHW4 (slen + 4), BHWm (m3ga_MARKER), BHWv (psf->strings.storage + psf->strings.data [k].offset), BHWz (slen + (slen & 1))) ;
1540                                 break ;
1541
1542                         case SF_STR_TITLE :
1543                                 psf_binheader_writef (psf, "EmS", BHWm (NAME_MARKER), BHWS (psf->strings.storage + psf->strings.data [k].offset)) ;
1544                                 break ;
1545
1546                         case SF_STR_COPYRIGHT :
1547                                 psf_binheader_writef (psf, "EmS", BHWm (c_MARKER), BHWS (psf->strings.storage + psf->strings.data [k].offset)) ;
1548                                 break ;
1549
1550                         case SF_STR_ARTIST :
1551                                 psf_binheader_writef (psf, "EmS", BHWm (AUTH_MARKER), BHWS (psf->strings.storage + psf->strings.data [k].offset)) ;
1552                                 break ;
1553
1554                         case SF_STR_COMMENT :
1555                                 psf_binheader_writef (psf, "EmS", BHWm (ANNO_MARKER), BHWS (psf->strings.storage + psf->strings.data [k].offset)) ;
1556                                 break ;
1557
1558                         /*
1559                         case SF_STR_DATE :
1560                                 psf_binheader_writef (psf, "Ems", BHWm (ICRD_MARKER), BHWs (psf->strings.data [k].str)) ;
1561                                 break ;
1562                         */
1563                         } ;
1564                 } ;
1565
1566         return ;
1567 } /* aiff_write_strings */
1568
1569 static int
1570 aiff_command (SF_PRIVATE * psf, int command, void * UNUSED (data), int UNUSED (datasize))
1571 {       AIFF_PRIVATE    *paiff ;
1572
1573         if ((paiff = psf->container_data) == NULL)
1574                 return SFE_INTERNAL ;
1575
1576         switch (command)
1577         {       case SFC_SET_CHANNEL_MAP_INFO :
1578                         paiff->chanmap_tag = aiff_caf_find_channel_layout_tag (psf->channel_map, psf->sf.channels) ;
1579                         return (paiff->chanmap_tag != 0) ;
1580
1581                 default :
1582                         break ;
1583         } ;
1584
1585         return 0 ;
1586 } /* aiff_command */
1587
1588 static const char*
1589 get_loop_mode_str (int16_t mode)
1590 {       switch (mode)
1591         {       case 0 : return "none" ;
1592                 case 1 : return "forward" ;
1593                 case 2 : return "backward" ;
1594                 } ;
1595
1596         return "*** unknown" ;
1597 } /* get_loop_mode_str */
1598
1599 static int16_t
1600 get_loop_mode (int16_t mode)
1601 {       switch (mode)
1602         {       case 0 : return SF_LOOP_NONE ;
1603                 case 1 : return SF_LOOP_FORWARD ;
1604                 case 2 : return SF_LOOP_BACKWARD ;
1605                 } ;
1606
1607         return SF_LOOP_NONE ;
1608 } /* get_loop_mode */
1609
1610 /*==========================================================================================
1611 **      Rough hack at converting from 80 bit IEEE float in AIFF header to an int and
1612 **      back again. It assumes that all sample rates are between 1 and 800MHz, which
1613 **      should be OK as other sound file formats use a 32 bit integer to store sample
1614 **      rate.
1615 **      There is another (probably better) version in the source code to the SoX but it
1616 **      has a copyright which probably prevents it from being allowable as GPL/LGPL.
1617 */
1618
1619 static int
1620 tenbytefloat2int (uint8_t *bytes)
1621 {       int val = 3 ;
1622
1623         if (bytes [0] & 0x80)   /* Negative number. */
1624                 return 0 ;
1625
1626         if (bytes [0] <= 0x3F)  /* Less than 1. */
1627                 return 1 ;
1628
1629         if (bytes [0] > 0x40)   /* Way too big. */
1630                 return 0x4000000 ;
1631
1632         if (bytes [0] == 0x40 && bytes [1] > 0x1C) /* Too big. */
1633                 return 800000000 ;
1634
1635         /* Ok, can handle it. */
1636
1637         val = (bytes [2] << 23) | (bytes [3] << 15) | (bytes [4] << 7) | (bytes [5] >> 1) ;
1638
1639         val >>= (29 - bytes [1]) ;
1640
1641         return val ;
1642 } /* tenbytefloat2int */
1643
1644 static void
1645 uint2tenbytefloat (uint32_t num, uint8_t *bytes)
1646 {       uint32_t mask = 0x40000000 ;
1647         int     count ;
1648
1649         if (num <= 1)
1650         {       bytes [0] = 0x3F ;
1651                 bytes [1] = 0xFF ;
1652                 bytes [2] = 0x80 ;
1653                 return ;
1654                 } ;
1655
1656         bytes [0] = 0x40 ;
1657
1658         if (num >= mask)
1659         {       bytes [1] = 0x1D ;
1660                 return ;
1661                 } ;
1662
1663         for (count = 0 ; count < 32 ; count ++)
1664         {       if (num & mask)
1665                         break ;
1666                 mask >>= 1 ;
1667                 } ;
1668
1669         num = count < 31 ? num << (count + 1) : 0 ;
1670         bytes [1] = 29 - count ;
1671         bytes [2] = (num >> 24) & 0xFF ;
1672         bytes [3] = (num >> 16) & 0xFF ;
1673         bytes [4] = (num >> 8) & 0xFF ;
1674         bytes [5] = num & 0xFF ;
1675
1676 } /* uint2tenbytefloat */
1677
1678 static int
1679 aiff_read_basc_chunk (SF_PRIVATE * psf, int datasize)
1680 {       const char * type_str ;
1681         basc_CHUNK bc ;
1682         int count ;
1683
1684         count = psf_binheader_readf (psf, "E442", &bc.version, &bc.numBeats, &bc.rootNote) ;
1685         count += psf_binheader_readf (psf, "E222", &bc.scaleType, &bc.sigNumerator, &bc.sigDenominator) ;
1686         count += psf_binheader_readf (psf, "E2j", &bc.loopType, datasize - sizeof (bc)) ;
1687
1688         psf_log_printf (psf, "  Version ? : %u\n  Num Beats : %u\n  Root Note : 0x%x\n",
1689                                                 bc.version, bc.numBeats, bc.rootNote) ;
1690
1691         switch (bc.scaleType)
1692         {       case basc_SCALE_MINOR :
1693                                 type_str = "MINOR" ;
1694                                 break ;
1695                 case basc_SCALE_MAJOR :
1696                                 type_str = "MAJOR" ;
1697                                 break ;
1698                 case basc_SCALE_NEITHER :
1699                                 type_str = "NEITHER" ;
1700                                 break ;
1701                 case basc_SCALE_BOTH :
1702                                 type_str = "BOTH" ;
1703                                 break ;
1704                 default :
1705                                 type_str = "!!WRONG!!" ;
1706                                 break ;
1707                 } ;
1708
1709         psf_log_printf (psf, "  ScaleType : 0x%x (%s)\n", bc.scaleType, type_str) ;
1710         psf_log_printf (psf, "  Time Sig  : %d/%d\n", bc.sigNumerator, bc.sigDenominator) ;
1711
1712         switch (bc.loopType)
1713         {       case basc_TYPE_ONE_SHOT :
1714                                 type_str = "One Shot" ;
1715                                 break ;
1716                 case basc_TYPE_LOOP :
1717                                 type_str = "Loop" ;
1718                                 break ;
1719                 default:
1720                                 type_str = "!!WRONG!!" ;
1721                                 break ;
1722                 } ;
1723
1724         psf_log_printf (psf, "  Loop Type : 0x%x (%s)\n", bc.loopType, type_str) ;
1725
1726         if (psf->loop_info)
1727         {       psf_log_printf (psf, "  Found existing loop info, using last one.\n") ;
1728                 free (psf->loop_info) ;
1729                 psf->loop_info = NULL ;
1730                 } ;
1731         if ((psf->loop_info = calloc (1, sizeof (SF_LOOP_INFO))) == NULL)
1732                 return SFE_MALLOC_FAILED ;
1733
1734         psf->loop_info->time_sig_num    = bc.sigNumerator ;
1735         psf->loop_info->time_sig_den    = bc.sigDenominator ;
1736         psf->loop_info->loop_mode               = (bc.loopType == basc_TYPE_ONE_SHOT) ? SF_LOOP_NONE : SF_LOOP_FORWARD ;
1737         psf->loop_info->num_beats               = bc.numBeats ;
1738
1739         /* Can always be recalculated from other known fields. */
1740         psf->loop_info->bpm = (1.0 / psf->sf.frames) * psf->sf.samplerate
1741                                                         * ((bc.numBeats * 4.0) / bc.sigDenominator) * 60.0 ;
1742         psf->loop_info->root_key = bc.rootNote ;
1743
1744         if (count < datasize)
1745                 psf_binheader_readf (psf, "j", datasize - count) ;
1746
1747         return 0 ;
1748 } /* aiff_read_basc_chunk */
1749
1750
1751 static int
1752 aiff_read_chanmap (SF_PRIVATE * psf, unsigned dword)
1753 {       const AIFF_CAF_CHANNEL_MAP * map_info ;
1754         unsigned channel_bitmap, channel_decriptions, bytesread ;
1755         int layout_tag ;
1756
1757         bytesread = psf_binheader_readf (psf, "444", &layout_tag, &channel_bitmap, &channel_decriptions) ;
1758
1759         if ((map_info = aiff_caf_of_channel_layout_tag (layout_tag)) == NULL)
1760                 return 0 ;
1761
1762         psf_log_printf (psf, "  Tag    : %x\n", layout_tag) ;
1763         if (map_info)
1764                 psf_log_printf (psf, "  Layout : %s\n", map_info->name) ;
1765
1766         if (bytesread < dword)
1767                 psf_binheader_readf (psf, "j", dword - bytesread) ;
1768
1769         if (map_info->channel_map != NULL)
1770         {       size_t chanmap_size = SF_MIN (psf->sf.channels, layout_tag & 0xffff) * sizeof (psf->channel_map [0]) ;
1771
1772                 free (psf->channel_map) ;
1773
1774                 if ((psf->channel_map = malloc (chanmap_size)) == NULL)
1775                         return SFE_MALLOC_FAILED ;
1776
1777                 memcpy (psf->channel_map, map_info->channel_map, chanmap_size) ;
1778                 } ;
1779
1780         return 0 ;
1781 } /* aiff_read_chanmap */
1782
1783 /*==============================================================================
1784 */
1785
1786 static int
1787 aiff_set_chunk (SF_PRIVATE *psf, const SF_CHUNK_INFO * chunk_info)
1788 {       return psf_save_write_chunk (&psf->wchunks, chunk_info) ;
1789 } /* aiff_set_chunk */
1790
1791 static SF_CHUNK_ITERATOR *
1792 aiff_next_chunk_iterator (SF_PRIVATE *psf, SF_CHUNK_ITERATOR * iterator)
1793 {       return psf_next_chunk_iterator (&psf->rchunks, iterator) ;
1794 } /* aiff_next_chunk_iterator */
1795
1796 static int
1797 aiff_get_chunk_size (SF_PRIVATE *psf, const SF_CHUNK_ITERATOR * iterator, SF_CHUNK_INFO * chunk_info)
1798 {       int indx ;
1799
1800         if ((indx = psf_find_read_chunk_iterator (&psf->rchunks, iterator)) < 0)
1801                 return SFE_UNKNOWN_CHUNK ;
1802
1803         chunk_info->datalen = psf->rchunks.chunks [indx].len ;
1804
1805         return SFE_NO_ERROR ;
1806 } /* aiff_get_chunk_size */
1807
1808 static int
1809 aiff_get_chunk_data (SF_PRIVATE *psf, const SF_CHUNK_ITERATOR * iterator, SF_CHUNK_INFO * chunk_info)
1810 {       sf_count_t pos ;
1811         int indx ;
1812
1813         if ((indx = psf_find_read_chunk_iterator (&psf->rchunks, iterator)) < 0)
1814                 return SFE_UNKNOWN_CHUNK ;
1815
1816         if (chunk_info->data == NULL)
1817                 return SFE_BAD_CHUNK_DATA_PTR ;
1818
1819         chunk_info->id_size = psf->rchunks.chunks [indx].id_size ;
1820         memcpy (chunk_info->id, psf->rchunks.chunks [indx].id, sizeof (chunk_info->id) / sizeof (*chunk_info->id)) ;
1821
1822         pos = psf_ftell (psf) ;
1823         psf_fseek (psf, psf->rchunks.chunks [indx].offset, SEEK_SET) ;
1824         psf_fread (chunk_info->data, SF_MIN (chunk_info->datalen, psf->rchunks.chunks [indx].len), 1, psf) ;
1825         psf_fseek (psf, pos, SEEK_SET) ;
1826
1827         return SFE_NO_ERROR ;
1828 } /* aiff_get_chunk_data */