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