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