• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 ** Copyright (C) 2005-2017 Erik de Castro Lopo <erikd@mega-nerd.com>
3 **
4 ** This program is free software; you can redistribute it and/or modify
5 ** it under the terms of the GNU Lesser General Public License as published by
6 ** the Free Software Foundation; either version 2.1 of the License, or
7 ** (at your option) any later version.
8 **
9 ** This program is distributed in the hope that it will be useful,
10 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
11 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 ** GNU Lesser General Public License for more details.
13 **
14 ** You should have received a copy of the GNU Lesser General Public License
15 ** along with this program; if not, write to the Free Software
16 ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17 */
18 
19 #include	"sfconfig.h"
20 
21 #include	<stdio.h>
22 #include	<stdlib.h>
23 #include	<string.h>
24 #include	<ctype.h>
25 #include	<math.h>
26 #include	<inttypes.h>
27 
28 #include	"sndfile.h"
29 #include	"sfendian.h"
30 #include	"common.h"
31 #include	"chanmap.h"
32 
33 /*------------------------------------------------------------------------------
34 ** Macros to handle big/little endian issues.
35 */
36 
37 #define aac_MARKER		MAKE_MARKER ('a', 'a', 'c', ' ')
38 #define alac_MARKER		MAKE_MARKER ('a', 'l', 'a', 'c')
39 #define alaw_MARKER		MAKE_MARKER ('a', 'l', 'a', 'w')
40 #define caff_MARKER		MAKE_MARKER ('c', 'a', 'f', 'f')
41 #define chan_MARKER		MAKE_MARKER ('c', 'h', 'a', 'n')
42 #define data_MARKER		MAKE_MARKER ('d', 'a', 't', 'a')
43 #define desc_MARKER		MAKE_MARKER ('d', 'e', 's', 'c')
44 #define edct_MARKER		MAKE_MARKER ('e', 'd', 'c', 't')
45 #define free_MARKER		MAKE_MARKER ('f', 'r', 'e', 'e')
46 #define ima4_MARKER		MAKE_MARKER ('i', 'm', 'a', '4')
47 #define info_MARKER		MAKE_MARKER ('i', 'n', 'f', 'o')
48 #define inst_MARKER		MAKE_MARKER ('i', 'n', 's', 't')
49 #define kuki_MARKER		MAKE_MARKER ('k', 'u', 'k', 'i')
50 #define lpcm_MARKER		MAKE_MARKER ('l', 'p', 'c', 'm')
51 #define mark_MARKER		MAKE_MARKER ('m', 'a', 'r', 'k')
52 #define midi_MARKER		MAKE_MARKER ('m', 'i', 'd', 'i')
53 #define mp1_MARKER		MAKE_MARKER ('.', 'm', 'p', '1')
54 #define mp2_MARKER		MAKE_MARKER ('.', 'm', 'p', '2')
55 #define mp3_MARKER		MAKE_MARKER ('.', 'm', 'p', '3')
56 #define ovvw_MARKER		MAKE_MARKER ('o', 'v', 'v', 'w')
57 #define pakt_MARKER		MAKE_MARKER ('p', 'a', 'k', 't')
58 #define peak_MARKER		MAKE_MARKER ('p', 'e', 'a', 'k')
59 #define regn_MARKER		MAKE_MARKER ('r', 'e', 'g', 'n')
60 #define strg_MARKER		MAKE_MARKER ('s', 't', 'r', 'g')
61 #define umid_MARKER		MAKE_MARKER ('u', 'm', 'i', 'd')
62 #define uuid_MARKER		MAKE_MARKER ('u', 'u', 'i', 'd')
63 #define ulaw_MARKER		MAKE_MARKER ('u', 'l', 'a', 'w')
64 #define MAC3_MARKER		MAKE_MARKER ('M', 'A', 'C', '3')
65 #define MAC6_MARKER		MAKE_MARKER ('M', 'A', 'C', '6')
66 
67 #define CAF_PEAK_CHUNK_SIZE(ch) 	((int) (sizeof (int) + ch * (sizeof (float) + 8)))
68 
69 #define SFE_CAF_NOT_CAF	666
70 #define SFE_CAF_NO_DESC	667
71 #define SFE_CAF_BAD_PEAK 668
72 
73 /*------------------------------------------------------------------------------
74 ** Typedefs.
75 */
76 
77 typedef struct
78 {	uint8_t		srate [8] ;
79 	uint32_t	fmt_id ;
80 	uint32_t	fmt_flags ;
81 	uint32_t	pkt_bytes ;
82 	uint32_t	frames_per_packet ;
83 	uint32_t	channels_per_frame ;
84 	uint32_t	bits_per_chan ;
85 } DESC_CHUNK ;
86 
87 typedef struct
88 {	int			chanmap_tag ;
89 
90 	ALAC_DECODER_INFO	alac ;
91 } CAF_PRIVATE ;
92 
93 /*------------------------------------------------------------------------------
94 ** Private static functions.
95 */
96 
97 static int	caf_close (SF_PRIVATE *psf) ;
98 static int	caf_read_header (SF_PRIVATE *psf) ;
99 static int	caf_write_header (SF_PRIVATE *psf, int calc_length) ;
100 static int	caf_write_tailer (SF_PRIVATE *psf) ;
101 static int	caf_command (SF_PRIVATE *psf, int command, void *data, int datasize) ;
102 static int	caf_read_chanmap (SF_PRIVATE * psf, sf_count_t chunk_size) ;
103 static int	caf_read_strings (SF_PRIVATE * psf, sf_count_t chunk_size) ;
104 static void	caf_write_strings (SF_PRIVATE * psf, int location) ;
105 
106 
107 static int caf_set_chunk (SF_PRIVATE *psf, const SF_CHUNK_INFO * chunk_info) ;
108 static SF_CHUNK_ITERATOR * caf_next_chunk_iterator (SF_PRIVATE *psf, SF_CHUNK_ITERATOR * iterator) ;
109 static int caf_get_chunk_size (SF_PRIVATE *psf, const SF_CHUNK_ITERATOR * iterator, SF_CHUNK_INFO * chunk_info) ;
110 static int caf_get_chunk_data (SF_PRIVATE *psf, const SF_CHUNK_ITERATOR * iterator, SF_CHUNK_INFO * chunk_info) ;
111 
112 /*------------------------------------------------------------------------------
113 ** Public function.
114 */
115 
116 int
caf_open(SF_PRIVATE * psf)117 caf_open (SF_PRIVATE *psf)
118 {	CAF_PRIVATE * pcaf ;
119 	int	subformat, format, error = 0 ;
120 
121 	if ((psf->container_data = calloc (1, sizeof (CAF_PRIVATE))) == NULL)
122 		return SFE_MALLOC_FAILED ;
123 
124 	pcaf = psf->container_data ;
125 
126 	if (psf->file.mode == SFM_READ || (psf->file.mode == SFM_RDWR && psf->filelength > 0))
127 	{	if ((error = caf_read_header (psf)))
128 			return error ;
129 
130 		psf->next_chunk_iterator = caf_next_chunk_iterator ;
131 		psf->get_chunk_size = caf_get_chunk_size ;
132 		psf->get_chunk_data = caf_get_chunk_data ;
133 		} ;
134 
135 	subformat = SF_CODEC (psf->sf.format) ;
136 
137 	if (psf->file.mode == SFM_WRITE || psf->file.mode == SFM_RDWR)
138 	{	if (psf->is_pipe)
139 			return SFE_NO_PIPE_WRITE ;
140 
141 		format = SF_CONTAINER (psf->sf.format) ;
142 		if (format != SF_FORMAT_CAF)
143 			return	SFE_BAD_OPEN_FORMAT ;
144 
145 		psf->blockwidth = psf->bytewidth * psf->sf.channels ;
146 
147 		if (psf->file.mode != SFM_RDWR || psf->filelength < 44)
148 		{	psf->filelength = 0 ;
149 			psf->datalength = 0 ;
150 			psf->dataoffset = 0 ;
151 			psf->sf.frames = 0 ;
152 			} ;
153 
154 		psf->strings.flags = SF_STR_ALLOW_START | SF_STR_ALLOW_END ;
155 
156 		/*
157 		**	By default, add the peak chunk to floating point files. Default behaviour
158 		**	can be switched off using sf_command (SFC_SET_PEAK_CHUNK, SF_FALSE).
159 		*/
160 		if (psf->file.mode == SFM_WRITE && (subformat == SF_FORMAT_FLOAT || subformat == SF_FORMAT_DOUBLE))
161 		{	if ((psf->peak_info = peak_info_calloc (psf->sf.channels)) == NULL)
162 				return SFE_MALLOC_FAILED ;
163 			psf->peak_info->peak_loc = SF_PEAK_START ;
164 			} ;
165 
166 		if ((error = caf_write_header (psf, SF_FALSE)) != 0)
167 			return error ;
168 
169 		psf->write_header	= caf_write_header ;
170 		psf->set_chunk		= caf_set_chunk ;
171 		} ;
172 
173 	psf->container_close = caf_close ;
174 	psf->command = caf_command ;
175 
176 	switch (subformat)
177 	{	case SF_FORMAT_PCM_S8 :
178 		case SF_FORMAT_PCM_16 :
179 		case SF_FORMAT_PCM_24 :
180 		case SF_FORMAT_PCM_32 :
181 					error = pcm_init (psf) ;
182 					break ;
183 
184 		case SF_FORMAT_ULAW :
185 					error = ulaw_init (psf) ;
186 					break ;
187 
188 		case SF_FORMAT_ALAW :
189 					error = alaw_init (psf) ;
190 					break ;
191 
192 		/* Lite remove start */
193 		case SF_FORMAT_FLOAT :
194 					error = float32_init (psf) ;
195 					break ;
196 
197 		case SF_FORMAT_DOUBLE :
198 					error = double64_init (psf) ;
199 					break ;
200 
201 		case SF_FORMAT_ALAC_16 :
202 		case SF_FORMAT_ALAC_20 :
203 		case SF_FORMAT_ALAC_24 :
204 		case SF_FORMAT_ALAC_32 :
205 					if (psf->file.mode == SFM_READ)
206 						/* Only pass the ALAC_DECODER_INFO in read mode. */
207 						error = alac_init (psf, &pcaf->alac) ;
208 					else
209 						error = alac_init (psf, NULL) ;
210 					break ;
211 
212 		/* Lite remove end */
213 
214 		default :
215 			return SFE_UNSUPPORTED_ENCODING ;
216 		} ;
217 
218 	return error ;
219 } /* caf_open */
220 
221 static int
caf_close(SF_PRIVATE * psf)222 caf_close (SF_PRIVATE *psf)
223 {
224 	if (psf->file.mode == SFM_WRITE || psf->file.mode == SFM_RDWR)
225 	{	caf_write_tailer (psf) ;
226 		caf_write_header (psf, SF_TRUE) ;
227 		} ;
228 
229 	return 0 ;
230 } /* caf_close */
231 
232 static int
caf_command(SF_PRIVATE * psf,int command,void * UNUSED (data),int UNUSED (datasize))233 caf_command (SF_PRIVATE * psf, int command, void * UNUSED (data), int UNUSED (datasize))
234 {	CAF_PRIVATE	*pcaf ;
235 
236 	if ((pcaf = psf->container_data) == NULL)
237 		return SFE_INTERNAL ;
238 
239 	switch (command)
240 	{	case SFC_SET_CHANNEL_MAP_INFO :
241 			pcaf->chanmap_tag = aiff_caf_find_channel_layout_tag (psf->channel_map, psf->sf.channels) ;
242 			return (pcaf->chanmap_tag != 0) ;
243 
244 		default :
245 			break ;
246 	} ;
247 
248 	return 0 ;
249 } /* caf_command */
250 
251 /*------------------------------------------------------------------------------
252 */
253 
254 static int
decode_desc_chunk(SF_PRIVATE * psf,const DESC_CHUNK * desc)255 decode_desc_chunk (SF_PRIVATE *psf, const DESC_CHUNK *desc)
256 {	int format = SF_FORMAT_CAF ;
257 
258 	psf->sf.channels = desc->channels_per_frame ;
259 
260 	if (desc->fmt_id == alac_MARKER)
261 	{	CAF_PRIVATE	*pcaf ;
262 
263 		if ((pcaf = psf->container_data) != NULL)
264 		{	switch (desc->fmt_flags)
265 			{	case 1 :
266 					pcaf->alac.bits_per_sample = 16 ;
267 					format |= SF_FORMAT_ALAC_16 ;
268 					break ;
269 				case 2 :
270 					pcaf->alac.bits_per_sample = 20 ;
271 					format |= SF_FORMAT_ALAC_20 ;
272 					break ;
273 				case 3 :
274 					pcaf->alac.bits_per_sample = 24 ;
275 					format |= SF_FORMAT_ALAC_24 ;
276 					break ;
277 				case 4 :
278 					pcaf->alac.bits_per_sample = 32 ;
279 					format |= SF_FORMAT_ALAC_32 ;
280 					break ;
281 				default :
282 					psf_log_printf (psf, "Bad ALAC format flag value of %d\n", desc->fmt_flags) ;
283 				} ;
284 
285 			pcaf->alac.frames_per_packet = desc->frames_per_packet ;
286 			} ;
287 
288 		return format ;
289 		} ;
290 
291 	format |= psf->endian == SF_ENDIAN_LITTLE ? SF_ENDIAN_LITTLE : 0 ;
292 
293 	if (desc->fmt_id == lpcm_MARKER && desc->fmt_flags & 1)
294 	{	/* Floating point data. */
295 		if (desc->bits_per_chan == 32 && desc->pkt_bytes == 4 * desc->channels_per_frame)
296 		{	psf->bytewidth = 4 ;
297 			return format | SF_FORMAT_FLOAT ;
298 			} ;
299 		if (desc->bits_per_chan == 64 && desc->pkt_bytes == 8 * desc->channels_per_frame)
300 		{	psf->bytewidth = 8 ;
301 			return format | SF_FORMAT_DOUBLE ;
302 			} ;
303 		} ;
304 
305 	if (desc->fmt_id == lpcm_MARKER && (desc->fmt_flags & 1) == 0)
306 	{	/* Integer data. */
307 		if (desc->bits_per_chan == 32 && desc->pkt_bytes == 4 * desc->channels_per_frame)
308 		{	psf->bytewidth = 4 ;
309 			return format | SF_FORMAT_PCM_32 ;
310 			} ;
311 		if (desc->bits_per_chan == 24 && desc->pkt_bytes == 3 * desc->channels_per_frame)
312 		{	psf->bytewidth = 3 ;
313 			return format | SF_FORMAT_PCM_24 ;
314 			} ;
315 		if (desc->bits_per_chan == 16 && desc->pkt_bytes == 2 * desc->channels_per_frame)
316 		{	psf->bytewidth = 2 ;
317 			return format | SF_FORMAT_PCM_16 ;
318 			} ;
319 		if (desc->bits_per_chan == 8 && desc->pkt_bytes == 1 * desc->channels_per_frame)
320 		{	psf->bytewidth = 1 ;
321 			return format | SF_FORMAT_PCM_S8 ;
322 			} ;
323 		} ;
324 
325 	if (desc->fmt_id == alaw_MARKER && desc->bits_per_chan == 8)
326 	{	psf->bytewidth = 1 ;
327 		return format | SF_FORMAT_ALAW ;
328 		} ;
329 
330 	if (desc->fmt_id == ulaw_MARKER && desc->bits_per_chan == 8)
331 	{	psf->bytewidth = 1 ;
332 		return format | SF_FORMAT_ULAW ;
333 		} ;
334 
335 	psf_log_printf (psf, "**** Unknown format identifier.\n") ;
336 
337 	return 0 ;
338 } /* decode_desc_chunk */
339 
340 static int
caf_read_header(SF_PRIVATE * psf)341 caf_read_header (SF_PRIVATE *psf)
342 {	CAF_PRIVATE	*pcaf ;
343 	BUF_UNION	ubuf ;
344 	DESC_CHUNK desc ;
345 	sf_count_t chunk_size ;
346 	double srate ;
347 	short version, flags ;
348 	int marker, k, have_data = 0, error ;
349 
350 	if ((pcaf = psf->container_data) == NULL)
351 		return SFE_INTERNAL ;
352 
353 	memset (&desc, 0, sizeof (desc)) ;
354 
355 	/* Set position to start of file to begin reading header. */
356 	psf_binheader_readf (psf, "pmE2E2", 0, &marker, &version, &flags) ;
357 	psf_log_printf (psf, "%M\n  Version : %d\n  Flags   : %x\n", marker, version, flags) ;
358 	if (marker != caff_MARKER)
359 		return SFE_CAF_NOT_CAF ;
360 
361 	psf_binheader_readf (psf, "mE8b", &marker, &chunk_size, ubuf.ucbuf, 8) ;
362 	srate = double64_be_read (ubuf.ucbuf) ;
363 	snprintf (ubuf.cbuf, sizeof (ubuf.cbuf), "%5.3f", srate) ;
364 	psf_log_printf (psf, "%M : %D\n  Sample rate  : %s\n", marker, chunk_size, ubuf.cbuf) ;
365 	if (marker != desc_MARKER)
366 		return SFE_CAF_NO_DESC ;
367 
368 	if (chunk_size < SIGNED_SIZEOF (DESC_CHUNK))
369 	{	psf_log_printf (psf, "**** Chunk size too small. Should be > 32 bytes.\n") ;
370 		return SFE_MALFORMED_FILE ;
371 		} ;
372 
373 	psf->sf.samplerate = psf_lrint (srate) ;
374 
375 	psf_binheader_readf (psf, "mE44444", &desc.fmt_id, &desc.fmt_flags, &desc.pkt_bytes, &desc.frames_per_packet,
376 			&desc.channels_per_frame, &desc.bits_per_chan) ;
377 	psf_log_printf (psf, "  Format id    : %M\n  Format flags : %x\n  Bytes / packet   : %u\n"
378 			"  Frames / packet  : %u\n  Channels / frame : %u\n  Bits / channel   : %u\n",
379 			desc.fmt_id, desc.fmt_flags, desc.pkt_bytes, desc.frames_per_packet, desc.channels_per_frame, desc.bits_per_chan) ;
380 
381 	if (desc.channels_per_frame > SF_MAX_CHANNELS)
382 	{	psf_log_printf (psf, "**** Bad channels per frame value %u.\n", desc.channels_per_frame) ;
383 		return SFE_MALFORMED_FILE ;
384 		} ;
385 
386 	if (chunk_size > SIGNED_SIZEOF (DESC_CHUNK))
387 		psf_binheader_readf (psf, "j", (int) (chunk_size - sizeof (DESC_CHUNK))) ;
388 
389 	psf->sf.channels = desc.channels_per_frame ;
390 
391 	while (1)
392 	{	marker = 0 ;
393 		chunk_size = 0 ;
394 
395 		psf_binheader_readf (psf, "mE8", &marker, &chunk_size) ;
396 		if (marker == 0)
397 		{	sf_count_t pos = psf_ftell (psf) ;
398 			psf_log_printf (psf, "Have 0 marker at position %D (0x%x).\n", pos, pos) ;
399 			break ;
400 			} ;
401 		if (chunk_size < 0)
402 		{	psf_log_printf (psf, "%M : %D *** Should be >= 0 ***\n", marker, chunk_size) ;
403 			break ;
404 			} ;
405 		if (chunk_size > psf->filelength)
406 			break ;
407 
408 		psf_store_read_chunk_u32 (&psf->rchunks, marker, psf_ftell (psf), chunk_size) ;
409 
410 		switch (marker)
411 		{	case peak_MARKER :
412 				psf_log_printf (psf, "%M : %D\n", marker, chunk_size) ;
413 				if (chunk_size != CAF_PEAK_CHUNK_SIZE (psf->sf.channels))
414 				{	psf_binheader_readf (psf, "j", make_size_t (chunk_size)) ;
415 					psf_log_printf (psf, "*** File PEAK chunk %D should be %d.\n", chunk_size, CAF_PEAK_CHUNK_SIZE (psf->sf.channels)) ;
416 					return SFE_CAF_BAD_PEAK ;
417 					} ;
418 
419 				if ((psf->peak_info = peak_info_calloc (psf->sf.channels)) == NULL)
420 					return SFE_MALLOC_FAILED ;
421 
422 				/* read in rest of PEAK chunk. */
423 				psf_binheader_readf (psf, "E4", & (psf->peak_info->edit_number)) ;
424 				psf_log_printf (psf, "  edit count : %d\n", psf->peak_info->edit_number) ;
425 
426 				psf_log_printf (psf, "     Ch   Position       Value\n") ;
427 				for (k = 0 ; k < psf->sf.channels ; k++)
428 				{	sf_count_t position ;
429 					float value ;
430 
431 					psf_binheader_readf (psf, "Ef8", &value, &position) ;
432 					psf->peak_info->peaks [k].value = value ;
433 					psf->peak_info->peaks [k].position = position ;
434 
435 					snprintf (ubuf.cbuf, sizeof (ubuf.cbuf), "    %2d   %-12" PRId64 "   %g\n", k, position, value) ;
436 					psf_log_printf (psf, ubuf.cbuf) ;
437 					} ;
438 
439 				psf->peak_info->peak_loc = SF_PEAK_START ;
440 				break ;
441 
442 			case chan_MARKER :
443 				if (chunk_size < 12)
444 				{	psf_log_printf (psf, "%M : %D (should be >= 12)\n", marker, chunk_size) ;
445 					psf_binheader_readf (psf, "j", make_size_t (chunk_size)) ;
446 					break ;
447 					}
448 
449 				psf_log_printf (psf, "%M : %D\n", marker, chunk_size) ;
450 
451 				if ((error = caf_read_chanmap (psf, chunk_size)))
452 					return error ;
453 				break ;
454 
455 			case free_MARKER :
456 				psf_log_printf (psf, "%M : %D\n", marker, chunk_size) ;
457 				psf_binheader_readf (psf, "j", make_size_t (chunk_size)) ;
458 				break ;
459 
460 			case data_MARKER :
461 				psf_binheader_readf (psf, "E4", &k) ;
462 				if (chunk_size == -1)
463 				{	psf_log_printf (psf, "%M : -1\n") ;
464 					chunk_size = psf->filelength - psf->header.indx ;
465 					}
466 				else if (psf->filelength > 0 && chunk_size > psf->filelength - psf->header.indx + 10)
467 				{	psf_log_printf (psf, "%M : %D (should be %D)\n", marker, chunk_size, psf->filelength - psf->header.indx - 8) ;
468 					psf->datalength = psf->filelength - psf->header.indx - 8 ;
469 					}
470 				else
471 				{	psf_log_printf (psf, "%M : %D\n", marker, chunk_size) ;
472 					/* Subtract the 4 bytes of the 'edit' field above. */
473 					psf->datalength = chunk_size - 4 ;
474 					} ;
475 
476 				psf_log_printf (psf, "  edit : %u\n", k) ;
477 
478 				psf->dataoffset = psf->header.indx ;
479 				if (psf->datalength + psf->dataoffset < psf->filelength)
480 					psf->dataend = psf->datalength + psf->dataoffset ;
481 
482 				psf_binheader_readf (psf, "j", make_size_t (psf->datalength)) ;
483 				have_data = 1 ;
484 				break ;
485 
486 			case kuki_MARKER :
487 				psf_log_printf (psf, "%M : %D\n", marker, chunk_size) ;
488 				pcaf->alac.kuki_offset = psf_ftell (psf) - 12 ;
489 				psf_binheader_readf (psf, "j", make_size_t (chunk_size)) ;
490 				break ;
491 
492 			case pakt_MARKER :
493 				if (chunk_size < 24)
494 				{	psf_log_printf (psf, "%M : %D (should be > 24)\n", marker, chunk_size) ;
495 					return SFE_MALFORMED_FILE ;
496 					}
497 				else if (chunk_size > psf->filelength - psf->header.indx)
498 				{	psf_log_printf (psf, "%M : %D (should be < %D)\n", marker, chunk_size, psf->filelength - psf->header.indx) ;
499 					return SFE_MALFORMED_FILE ;
500 					}
501 				else
502 					psf_log_printf (psf, "%M : %D\n", marker, chunk_size) ;
503 
504 				psf_binheader_readf (psf, "E8844", &pcaf->alac.packets, &pcaf->alac.valid_frames,
505 									&pcaf->alac.priming_frames, &pcaf->alac.remainder_frames) ;
506 
507 				psf_log_printf (psf,
508 						"  Packets          : %D\n"
509 						"  Valid frames     : %D\n"
510 						"  Priming frames   : %d\n"
511 						"  Remainder frames : %d\n",
512 						pcaf->alac.packets, pcaf->alac.valid_frames, pcaf->alac.priming_frames,
513 						pcaf->alac.remainder_frames
514 						) ;
515 
516 				if (pcaf->alac.packets == 0 && pcaf->alac.valid_frames == 0
517 							&& pcaf->alac.priming_frames == 0 && pcaf->alac.remainder_frames == 0)
518 					psf_log_printf (psf, "*** 'pakt' chunk header is all zero.\n") ;
519 
520 				pcaf->alac.pakt_offset = psf_ftell (psf) - 12 ;
521 				psf_binheader_readf (psf, "j", make_size_t (chunk_size) - 24) ;
522 				break ;
523 
524 			case info_MARKER :
525 				if (chunk_size < 4)
526 				{	psf_log_printf (psf, "%M : %D (should be > 4)\n", marker, chunk_size) ;
527 					return SFE_MALFORMED_FILE ;
528 					}
529 				else if (chunk_size > psf->filelength - psf->header.indx)
530 				{	psf_log_printf (psf, "%M : %D (should be < %D)\n", marker, chunk_size, psf->filelength - psf->header.indx) ;
531 					return SFE_MALFORMED_FILE ;
532 					} ;
533 				psf_log_printf (psf, "%M : %D\n", marker, chunk_size) ;
534 				if (chunk_size > 4)
535 					caf_read_strings (psf, chunk_size - 4) ;
536 				break ;
537 
538 			default :
539 				psf_log_printf (psf, "%M : %D (skipped)\n", marker, chunk_size) ;
540 				psf_binheader_readf (psf, "j", make_size_t (chunk_size)) ;
541 				break ;
542 			} ;
543 
544 		if (marker != data_MARKER && chunk_size >= 0xffffff00)
545 			break ;
546 
547 		if (! psf->sf.seekable && have_data)
548 			break ;
549 
550 		if (psf_ftell (psf) >= psf->filelength - SIGNED_SIZEOF (chunk_size))
551 		{	psf_log_printf (psf, "End\n") ;
552 			break ;
553 			} ;
554 		} ;
555 
556 	if (have_data == 0)
557 	{	psf_log_printf (psf, "**** Error, could not find 'data' chunk.\n") ;
558 		return SFE_MALFORMED_FILE ;
559 		} ;
560 
561 	psf->endian = (desc.fmt_flags & 2) ? SF_ENDIAN_LITTLE : SF_ENDIAN_BIG ;
562 
563 	psf_fseek (psf, psf->dataoffset, SEEK_SET) ;
564 
565 	if ((psf->sf.format = decode_desc_chunk (psf, &desc)) == 0)
566 		return SFE_UNSUPPORTED_ENCODING ;
567 
568 	if (psf->bytewidth > 0)
569 		psf->sf.frames = psf->datalength / psf->bytewidth ;
570 
571 	return 0 ;
572 } /* caf_read_header */
573 
574 /*------------------------------------------------------------------------------
575 */
576 
577 static int
caf_write_header(SF_PRIVATE * psf,int calc_length)578 caf_write_header (SF_PRIVATE *psf, int calc_length)
579 {	BUF_UNION	ubuf ;
580 	CAF_PRIVATE	*pcaf ;
581 	DESC_CHUNK desc ;
582 	sf_count_t current ;
583 	uint32_t uk ;
584 	int subformat, append_free_block = SF_TRUE ;
585 
586 	if ((pcaf = psf->container_data) == NULL)
587 		return SFE_INTERNAL ;
588 
589 	memset (&desc, 0, sizeof (desc)) ;
590 
591 	current = psf_ftell (psf) ;
592 
593 	if (calc_length)
594 	{	psf->filelength = psf_get_filelen (psf) ;
595 
596 		psf->datalength = psf->filelength - psf->dataoffset ;
597 
598 		if (psf->dataend)
599 			psf->datalength -= psf->filelength - psf->dataend ;
600 
601 		if (psf->bytewidth > 0)
602 			psf->sf.frames = psf->datalength / (psf->bytewidth * psf->sf.channels) ;
603 		} ;
604 
605 	/* Reset the current header length to zero. */
606 	psf->header.ptr [0] = 0 ;
607 	psf->header.indx = 0 ;
608 	psf_fseek (psf, 0, SEEK_SET) ;
609 
610 	/* 'caff' marker, version and flags. */
611 	psf_binheader_writef (psf, "Em22", BHWm (caff_MARKER), BHW2 (1), BHW2 (0)) ;
612 
613 	/* 'desc' marker and chunk size. */
614 	psf_binheader_writef (psf, "Em8", BHWm (desc_MARKER), BHW8 ((sf_count_t) (sizeof (DESC_CHUNK)))) ;
615 
616  	double64_be_write (1.0 * psf->sf.samplerate, ubuf.ucbuf) ;
617 	psf_binheader_writef (psf, "b", BHWv (ubuf.ucbuf), BHWz (8)) ;
618 
619 	subformat = SF_CODEC (psf->sf.format) ;
620 
621 	psf->endian = SF_ENDIAN (psf->sf.format) ;
622 
623 	if (CPU_IS_BIG_ENDIAN && (psf->endian == 0 || psf->endian == SF_ENDIAN_CPU))
624 		psf->endian = SF_ENDIAN_BIG ;
625 	else if (CPU_IS_LITTLE_ENDIAN && (psf->endian == SF_ENDIAN_LITTLE || psf->endian == SF_ENDIAN_CPU))
626 		psf->endian = SF_ENDIAN_LITTLE ;
627 
628 	if (psf->endian == SF_ENDIAN_LITTLE)
629 		desc.fmt_flags = 2 ;
630 	else
631 		psf->endian = SF_ENDIAN_BIG ;
632 
633 	/* initial section (same for all, it appears) */
634 	switch (subformat)
635 	{	case SF_FORMAT_PCM_S8 :
636 			desc.fmt_id = lpcm_MARKER ;
637 			psf->bytewidth = 1 ;
638 			desc.pkt_bytes = psf->bytewidth * psf->sf.channels ;
639 			desc.frames_per_packet = 1 ;
640 			desc.channels_per_frame = psf->sf.channels ;
641 			desc.bits_per_chan = 8 ;
642 			break ;
643 
644 		case SF_FORMAT_PCM_16 :
645 			desc.fmt_id = lpcm_MARKER ;
646 			psf->bytewidth = 2 ;
647 			desc.pkt_bytes = psf->bytewidth * psf->sf.channels ;
648 			desc.frames_per_packet = 1 ;
649 			desc.channels_per_frame = psf->sf.channels ;
650 			desc.bits_per_chan = 16 ;
651 			break ;
652 
653 		case SF_FORMAT_PCM_24 :
654 			psf->bytewidth = 3 ;
655 			desc.pkt_bytes = psf->bytewidth * psf->sf.channels ;
656 			desc.frames_per_packet = 1 ;
657 			desc.channels_per_frame = psf->sf.channels ;
658 			desc.bits_per_chan = 24 ;
659 			desc.fmt_id = lpcm_MARKER ;
660 			break ;
661 
662 		case SF_FORMAT_PCM_32 :
663 			desc.fmt_id = lpcm_MARKER ;
664 			psf->bytewidth = 4 ;
665 			desc.pkt_bytes = psf->bytewidth * psf->sf.channels ;
666 			desc.frames_per_packet = 1 ;
667 			desc.channels_per_frame = psf->sf.channels ;
668 			desc.bits_per_chan = 32 ;
669 			break ;
670 
671 		case SF_FORMAT_FLOAT :
672 			desc.fmt_id = lpcm_MARKER ;
673 			desc.fmt_flags |= 1 ;
674 			psf->bytewidth = 4 ;
675 			desc.pkt_bytes = psf->bytewidth * psf->sf.channels ;
676 			desc.frames_per_packet = 1 ;
677 			desc.channels_per_frame = psf->sf.channels ;
678 			desc.bits_per_chan = 32 ;
679 			break ;
680 
681 		case SF_FORMAT_DOUBLE :
682 			desc.fmt_id = lpcm_MARKER ;
683 			desc.fmt_flags |= 1 ;
684 			psf->bytewidth = 8 ;
685 			desc.pkt_bytes = psf->bytewidth * psf->sf.channels ;
686 			desc.frames_per_packet = 1 ;
687 			desc.channels_per_frame = psf->sf.channels ;
688 			desc.bits_per_chan = 64 ;
689 			break ;
690 
691 		case SF_FORMAT_ALAW :
692 			desc.fmt_id = alaw_MARKER ;
693 			psf->bytewidth = 1 ;
694 			desc.pkt_bytes = psf->bytewidth * psf->sf.channels ;
695 			desc.frames_per_packet = 1 ;
696 			desc.channels_per_frame = psf->sf.channels ;
697 			desc.bits_per_chan = 8 ;
698 			break ;
699 
700 		case SF_FORMAT_ULAW :
701 			desc.fmt_id = ulaw_MARKER ;
702 			psf->bytewidth = 1 ;
703 			desc.pkt_bytes = psf->bytewidth * psf->sf.channels ;
704 			desc.frames_per_packet = 1 ;
705 			desc.channels_per_frame = psf->sf.channels ;
706 			desc.bits_per_chan = 8 ;
707 			break ;
708 
709 		case SF_FORMAT_ALAC_16 :
710 		case SF_FORMAT_ALAC_20 :
711 		case SF_FORMAT_ALAC_24 :
712 		case SF_FORMAT_ALAC_32 :
713 			desc.fmt_id = alac_MARKER ;
714 			desc.pkt_bytes = psf->bytewidth * psf->sf.channels ;
715 			desc.channels_per_frame = psf->sf.channels ;
716 			alac_get_desc_chunk_items (subformat, &desc.fmt_flags, &desc.frames_per_packet) ;
717 			append_free_block = SF_FALSE ;
718 			break ;
719 
720 		default :
721 			return SFE_UNIMPLEMENTED ;
722 		} ;
723 
724 	psf_binheader_writef (psf, "mE44444", BHWm (desc.fmt_id), BHW4 (desc.fmt_flags), BHW4 (desc.pkt_bytes), BHW4 (desc.frames_per_packet), BHW4 (desc.channels_per_frame), BHW4 (desc.bits_per_chan)) ;
725 
726 	caf_write_strings (psf, SF_STR_LOCATE_START) ;
727 
728 	if (psf->peak_info != NULL)
729 	{	int k ;
730 		psf_binheader_writef (psf, "Em84", BHWm (peak_MARKER), BHW8 ((sf_count_t) CAF_PEAK_CHUNK_SIZE (psf->sf.channels)), BHW4 (psf->peak_info->edit_number)) ;
731 		for (k = 0 ; k < psf->sf.channels ; k++)
732 			psf_binheader_writef (psf, "Ef8", BHWf ((float) psf->peak_info->peaks [k].value), BHW8 (psf->peak_info->peaks [k].position)) ;
733 		} ;
734 
735 	if (psf->channel_map && pcaf->chanmap_tag)
736 		psf_binheader_writef (psf, "Em8444", BHWm (chan_MARKER), BHW8 ((sf_count_t) 12), BHW4 (pcaf->chanmap_tag), BHW4 (0), BHW4 (0)) ;
737 
738 	/* Write custom headers. */
739 	for (uk = 0 ; uk < psf->wchunks.used ; uk++)
740 		psf_binheader_writef (psf, "m44b", BHWm ((int) psf->wchunks.chunks [uk].mark32), BHW4 (0), BHW4 (psf->wchunks.chunks [uk].len), BHWv (psf->wchunks.chunks [uk].data), BHWz (psf->wchunks.chunks [uk].len)) ;
741 
742 	if (append_free_block)
743 	{	/* Add free chunk so that the actual audio data starts at a multiple 0x1000. */
744 		sf_count_t free_len = 0x1000 - psf->header.indx - 16 - 12 ;
745 		while (free_len < 0)
746 			free_len += 0x1000 ;
747 		psf_binheader_writef (psf, "Em8z", BHWm (free_MARKER), BHW8 (free_len), BHWz (free_len)) ;
748 		} ;
749 
750 	psf_binheader_writef (psf, "Em84", BHWm (data_MARKER), BHW8 (psf->datalength + 4), BHW4 (0)) ;
751 
752 	psf_fwrite (psf->header.ptr, psf->header.indx, 1, psf) ;
753 	if (psf->error)
754 		return psf->error ;
755 
756 	psf->dataoffset = psf->header.indx ;
757 	if (current < psf->dataoffset)
758 		psf_fseek (psf, psf->dataoffset, SEEK_SET) ;
759 	else if (current > 0)
760 		psf_fseek (psf, current, SEEK_SET) ;
761 
762 	return psf->error ;
763 } /* caf_write_header */
764 
765 static int
caf_write_tailer(SF_PRIVATE * psf)766 caf_write_tailer (SF_PRIVATE *psf)
767 {
768 	/* Reset the current header buffer length to zero. */
769 	psf->header.ptr [0] = 0 ;
770 	psf->header.indx = 0 ;
771 
772 	if (psf->bytewidth > 0 && psf->sf.seekable == SF_TRUE)
773 	{	psf->datalength = psf->sf.frames * psf->bytewidth * psf->sf.channels ;
774 		psf->dataend = psf->dataoffset + psf->datalength ;
775 		} ;
776 
777 	if (psf->dataend > 0)
778 		psf_fseek (psf, psf->dataend, SEEK_SET) ;
779 	else
780 		psf->dataend = psf_fseek (psf, 0, SEEK_END) ;
781 
782 	if (psf->dataend & 1)
783 		psf_binheader_writef (psf, "z", BHWz (1)) ;
784 
785 	if (psf->strings.flags & SF_STR_LOCATE_END)
786 		caf_write_strings (psf, SF_STR_LOCATE_END) ;
787 
788 	/* Write the tailer. */
789 	if (psf->header.indx > 0)
790 		psf_fwrite (psf->header.ptr, psf->header.indx, 1, psf) ;
791 
792 	return 0 ;
793 } /* caf_write_tailer */
794 
795 static int
caf_read_chanmap(SF_PRIVATE * psf,sf_count_t chunk_size)796 caf_read_chanmap (SF_PRIVATE * psf, sf_count_t chunk_size)
797 {	const AIFF_CAF_CHANNEL_MAP * map_info ;
798 	unsigned channel_bitmap, channel_decriptions, bytesread ;
799 	int layout_tag ;
800 
801 	bytesread = psf_binheader_readf (psf, "E444", &layout_tag, &channel_bitmap, &channel_decriptions) ;
802 
803 	map_info = aiff_caf_of_channel_layout_tag (layout_tag) ;
804 
805 	psf_log_printf (psf, "  Tag    : %x\n", layout_tag) ;
806 	if (map_info)
807 		psf_log_printf (psf, "  Layout : %s\n", map_info->name) ;
808 
809 	if (bytesread < chunk_size)
810 		psf_binheader_readf (psf, "j", chunk_size - bytesread) ;
811 
812 	if (map_info && map_info->channel_map != NULL)
813 	{	size_t chanmap_size = SF_MIN (psf->sf.channels, layout_tag & 0xff) * sizeof (psf->channel_map [0]) ;
814 
815 		free (psf->channel_map) ;
816 
817 		if ((psf->channel_map = malloc (chanmap_size)) == NULL)
818 			return SFE_MALLOC_FAILED ;
819 
820 		memcpy (psf->channel_map, map_info->channel_map, chanmap_size) ;
821 		} ;
822 
823 	return 0 ;
824 } /* caf_read_chanmap */
825 
826 
827 static uint32_t
string_hash32(const char * str)828 string_hash32 (const char * str)
829 {	uint32_t hash = 0x87654321 ;
830 
831 	while (str [0])
832 	{	hash = hash * 333 + str [0] ;
833 		str ++ ;
834 		} ;
835 
836 	return hash ;
837 } /* string_hash32 */
838 
839 static int
caf_read_strings(SF_PRIVATE * psf,sf_count_t chunk_size)840 caf_read_strings (SF_PRIVATE * psf, sf_count_t chunk_size)
841 {	char *buf ;
842 	char *key, *value ;
843 	uint32_t count, hash ;
844 
845 	if ((buf = malloc (chunk_size + 1)) == NULL)
846 		return (psf->error = SFE_MALLOC_FAILED) ;
847 
848 	psf_binheader_readf (psf, "E4b", &count, buf, make_size_t (chunk_size)) ;
849 	psf_log_printf (psf, " count: %u\n", count) ;
850 
851 	/* Force terminate `buf` to make sure. */
852 	buf [chunk_size] = 0 ;
853 
854 	for (key = buf ; key < buf + chunk_size ; )
855 	{	value = key + strlen (key) + 1 ;
856 		if (value > buf + chunk_size)
857 			break ;
858 		psf_log_printf (psf, "   %-12s : %s\n", key, value) ;
859 
860 		hash = string_hash32 (key) ;
861 		switch (hash)
862 		{	case 0xC4861943 : /* 'title' */
863 				psf_store_string (psf, SF_STR_TITLE, value) ;
864 				break ;
865 			case 0xAD47A394 : /* 'software' */
866 				psf_store_string (psf, SF_STR_SOFTWARE, value) ;
867 				break ;
868 			case 0x5D178E2A : /* 'copyright' */
869 				psf_store_string (psf, SF_STR_COPYRIGHT, value) ;
870 				break ;
871 			case 0x60E4D0C8 : /* 'artist' */
872 				psf_store_string (psf, SF_STR_ARTIST, value) ;
873 				break ;
874 			case 0x83B5D16A : /* 'genre' */
875 				psf_store_string (psf, SF_STR_GENRE, value) ;
876 				break ;
877 			case 0x15E5FC88 : /* 'comment' */
878 			case 0x7C297D5B : /* 'comments' */
879 				psf_store_string (psf, SF_STR_COMMENT, value) ;
880 				break ;
881 			case 0x24A7C347 : /* 'tracknumber' */
882 				psf_store_string (psf, SF_STR_TRACKNUMBER, value) ;
883 				break ;
884 			case 0x50A31EB7 : /* 'date' */
885 				psf_store_string (psf, SF_STR_DATE, value) ;
886 				break ;
887 			case 0x6583545A : /* 'album' */
888 				psf_store_string (psf, SF_STR_ALBUM, value) ;
889 				break ;
890 			case 0xE7C64B6C : /* 'license' */
891 				psf_store_string (psf, SF_STR_LICENSE, value) ;
892 				break ;
893 			default :
894 				psf_log_printf (psf, " Unhandled hash 0x%x : /* '%s' */\n", hash, key) ;
895 				break ;
896 			} ;
897 
898 		key = value + strlen (value) + 1 ;
899 		} ;
900 
901 	free (buf) ;
902 
903 	return 0 ;
904 } /* caf_read_strings */
905 
906 struct put_buffer
907 {	uint32_t index ;
908 	char s [16 * 1024] ;
909 } ;
910 
911 static uint32_t
put_key_value(struct put_buffer * buf,const char * key,const char * value)912 put_key_value (struct put_buffer * buf, const char * key, const char * value)
913 {	uint32_t written ;
914 
915 	if (buf->index + strlen (key) + strlen (value) + 2 > sizeof (buf->s))
916 		return 0 ;
917 
918 	written = snprintf (buf->s + buf->index, sizeof (buf->s) - buf->index, "%s%c%s%c", key, 0, value, 0) ;
919 
920 	if (buf->index + written >= sizeof (buf->s))
921 		return 0 ;
922 
923 	buf->index += written ;
924 	return 1 ;
925 } /* put_key_value */
926 
927 static void
caf_write_strings(SF_PRIVATE * psf,int location)928 caf_write_strings (SF_PRIVATE * psf, int location)
929 {	struct put_buffer buf ;
930  	const char * cptr ;
931 	uint32_t k, string_count = 0 ;
932 
933 	memset (&buf, 0, sizeof (buf)) ;
934 
935 	for (k = 0 ; k < SF_MAX_STRINGS ; k++)
936 	{	if (psf->strings.data [k].type == 0)
937 			break ;
938 
939 		if (psf->strings.data [k].flags != location)
940 			continue ;
941 
942 		if ((cptr = psf_get_string (psf, psf->strings.data [k].type)) == NULL)
943 			continue ;
944 
945 		switch (psf->strings.data [k].type)
946 		{	case SF_STR_TITLE :
947 				string_count += put_key_value (&buf, "title", cptr) ;
948 				break ;
949 			case SF_STR_COPYRIGHT :
950 				string_count += put_key_value (&buf, "copyright", cptr) ;
951 				break ;
952 			case SF_STR_SOFTWARE :
953 				string_count += put_key_value (&buf, "software", cptr) ;
954 				break ;
955 			case SF_STR_ARTIST :
956 				string_count += put_key_value (&buf, "artist", cptr) ;
957 				break ;
958 			case SF_STR_COMMENT :
959 				string_count += put_key_value (&buf, "comment", cptr) ;
960 				break ;
961 			case SF_STR_DATE :
962 				string_count += put_key_value (&buf, "date", cptr) ;
963 				break ;
964 			case SF_STR_ALBUM :
965 				string_count += put_key_value (&buf, "album", cptr) ;
966 				break ;
967 			case SF_STR_LICENSE :
968 				string_count += put_key_value (&buf, "license", cptr) ;
969 				break ;
970 			case SF_STR_TRACKNUMBER :
971 				string_count += put_key_value (&buf, "tracknumber", cptr) ;
972 				break ;
973 			case SF_STR_GENRE :
974 				string_count += put_key_value (&buf, "genre", cptr) ;
975 				break ;
976 
977 			default :
978 				break ;
979 			} ;
980 		} ;
981 
982 	if (string_count == 0 || buf.index == 0)
983 		return ;
984 
985 	psf_binheader_writef (psf, "Em84b", BHWm (info_MARKER), BHW8 (buf.index + 4), BHW4 (string_count), BHWv (buf.s), BHWz (buf.index)) ;
986 } /* caf_write_strings */
987 
988 /*==============================================================================
989 */
990 
991 static int
caf_set_chunk(SF_PRIVATE * psf,const SF_CHUNK_INFO * chunk_info)992 caf_set_chunk (SF_PRIVATE *psf, const SF_CHUNK_INFO * chunk_info)
993 {	return psf_save_write_chunk (&psf->wchunks, chunk_info) ;
994 } /* caf_set_chunk */
995 
996 static SF_CHUNK_ITERATOR *
caf_next_chunk_iterator(SF_PRIVATE * psf,SF_CHUNK_ITERATOR * iterator)997 caf_next_chunk_iterator (SF_PRIVATE *psf, SF_CHUNK_ITERATOR * iterator)
998 {	return psf_next_chunk_iterator (&psf->rchunks, iterator) ;
999 } /* caf_next_chunk_iterator */
1000 
1001 static int
caf_get_chunk_size(SF_PRIVATE * psf,const SF_CHUNK_ITERATOR * iterator,SF_CHUNK_INFO * chunk_info)1002 caf_get_chunk_size (SF_PRIVATE *psf, const SF_CHUNK_ITERATOR * iterator, SF_CHUNK_INFO * chunk_info)
1003 {	int indx ;
1004 
1005 	if ((indx = psf_find_read_chunk_iterator (&psf->rchunks, iterator)) < 0)
1006 		return SFE_UNKNOWN_CHUNK ;
1007 
1008 	chunk_info->datalen = psf->rchunks.chunks [indx].len ;
1009 
1010 	return SFE_NO_ERROR ;
1011 } /* caf_get_chunk_size */
1012 
1013 static int
caf_get_chunk_data(SF_PRIVATE * psf,const SF_CHUNK_ITERATOR * iterator,SF_CHUNK_INFO * chunk_info)1014 caf_get_chunk_data (SF_PRIVATE *psf, const SF_CHUNK_ITERATOR * iterator, SF_CHUNK_INFO * chunk_info)
1015 {	int indx ;
1016 	sf_count_t pos ;
1017 
1018 	if ((indx = psf_find_read_chunk_iterator (&psf->rchunks, iterator)) < 0)
1019 		return SFE_UNKNOWN_CHUNK ;
1020 
1021 	if (chunk_info->data == NULL)
1022 		return SFE_BAD_CHUNK_DATA_PTR ;
1023 
1024 	chunk_info->id_size = psf->rchunks.chunks [indx].id_size ;
1025 	memcpy (chunk_info->id, psf->rchunks.chunks [indx].id, sizeof (chunk_info->id) / sizeof (*chunk_info->id)) ;
1026 
1027 	pos = psf_ftell (psf) ;
1028 	psf_fseek (psf, psf->rchunks.chunks [indx].offset, SEEK_SET) ;
1029 	psf_fread (chunk_info->data, SF_MIN (chunk_info->datalen, psf->rchunks.chunks [indx].len), 1, psf) ;
1030 	psf_fseek (psf, pos, SEEK_SET) ;
1031 
1032 	return SFE_NO_ERROR ;
1033 } /* caf_get_chunk_data */
1034