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