]> git.sesse.net Git - vlc/blob - modules/demux/caf.c
macosx: Update progress dialog on the main thread, make check thread safe
[vlc] / modules / demux / caf.c
1 /*****************************************************************************
2  * caf.c: Core Audio File Format demuxer
3  *****************************************************************************
4  * Copyright (C) 2013 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Matthias Keiser <matthias@tristan-inc.com>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31 #include <math.h>
32 #include <limits.h>
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35 #include <vlc_demux.h>
36 #include <vlc_codecs.h>
37
38 /* TODO:
39  *
40  * - handle channel layout
41  * - 64 bit float LPCM is broken (sound has artifacts with little endian, only silence plays for big endian).
42  */
43
44 /*****************************************************************************
45  * Module descriptor
46  *****************************************************************************/
47 static int  Open    ( vlc_object_t * );
48 static void Close  ( vlc_object_t * );
49
50 vlc_module_begin ()
51 set_category( CAT_INPUT )
52 set_subcategory( SUBCAT_INPUT_DEMUX )
53 set_description( N_( "CAF demuxer" ))
54 set_capability( "demux", 140 )
55 set_callbacks( Open, Close )
56 add_shortcut( "caf" )
57 vlc_module_end ()
58
59 /*****************************************************************************
60  * Local prototypes
61  *****************************************************************************/
62 static int Demux  ( demux_t * );
63 static int Control( demux_t *, int i_query, va_list args );
64
65 typedef struct frame_span_t
66 {
67     uint64_t i_frames;
68     uint64_t i_samples;
69     uint64_t i_bytes;
70     uint64_t i_desc_bytes;
71 } frame_span_t;
72
73 typedef struct packet_table_t
74 {
75     uint64_t i_num_packets;
76     uint64_t i_num_valid_frames;
77     uint32_t i_num_priming_frames;
78     uint32_t i_num_remainder_frames;
79     uint64_t i_descriptions_start;
80 } packet_table_t;
81
82 struct demux_sys_t
83 {
84     es_format_t  fmt;
85     es_out_id_t *es;
86
87     uint64_t i_data_offset;
88     uint64_t i_data_size;
89
90     frame_span_t position;
91     packet_table_t packet_table;
92 };
93
94 /*
95  We use this value to indicate that the data section extends until the end of the file.
96 */
97 static const uint64_t kCHUNK_SIZE_EOF = UINT64_C( 0xffffffffffffffff );
98
99 /*****************************************************************************
100  * Various Utility Functions
101  *****************************************************************************/
102
103 /* ParseVarLenInteger parses a var length integer as found in the packet descriptions
104  (and in the aac magic cookie). In theorie a var length integer could be bigger than
105  an uint64_t, but I think it's unlikely to ever be a problem... */
106
107 static int ParseVarLenInteger( const uint8_t *p_buff, size_t i_buff_len, uint64_t *pi_value_out, uint32_t *i_len_out )
108 {
109     *i_len_out = 0;
110
111     uint64_t i_value = 0;
112     bool finished = false;
113
114     for( uint32_t i = 0; i < i_buff_len; i++ )
115     {
116         if( (( i_value >> 32 ) << 7 ) > UINT32_MAX )
117         {
118             return VLC_EGENERIC; /* overflow */
119         }
120         uint8_t i_byte = p_buff[i];
121         i_value = ( i_value << 7 ) | ( i_byte & 0x7f );
122
123         ( *i_len_out )++;
124
125         if( !( i_byte & 0x80 ))
126         {
127             finished = true;
128             break;
129         }
130     }
131
132     if( !finished )
133     {
134         return VLC_EGENERIC;
135     }
136
137     *pi_value_out = i_value;
138
139     return VLC_SUCCESS;
140 }
141
142 /* Utility function that reads a big endian double from the input buffer. */
143
144 static inline double GetDBLBE( const uint8_t *p )
145 {
146     union
147     {
148         uint64_t uint64;
149         double dbl;
150     } u_64;
151
152     u_64.uint64 = GetQWBE( p );
153     return u_64.dbl;
154 }
155
156 /* Utility function that reads a big endian signed 32 bit integer into an unsigned 32 bit variable.
157    If the read value is negative, this function returns an error.
158  */
159
160 static inline int ReadBEInt32ToUInt32( const uint8_t *p, uint32_t *i_out )
161 {
162     uint32_t i_value = GetDWBE( p );
163
164     if( i_value > INT32_MAX ) return VLC_EGENERIC;
165
166     *i_out = i_value;
167     return VLC_SUCCESS;
168 }
169
170 /* Utility function that reads a big endian signed 64 bit integer into an unsigned 64 bit variable.
171    If the read value is negative, this function returns an error.
172 */
173
174 static inline int ReadBEInt64ToUInt64( const uint8_t *p, uint64_t *i_out )
175 {
176     uint64_t i_value = GetQWBE( p );
177
178     if( i_value > INT64_MAX ) return VLC_EGENERIC;
179
180     *i_out = i_value;
181     return VLC_SUCCESS;
182 }
183
184 static inline bool NeedsPacketTable( demux_sys_t *p_sys )
185 {
186     return ( !p_sys->fmt.audio.i_bytes_per_frame || !p_sys->fmt.audio.i_frame_length );
187 }
188
189 static uint64_t TotalNumFrames( demux_t *p_demux )
190 {
191     demux_sys_t *p_sys = p_demux->p_sys;
192
193     if( !NeedsPacketTable( p_sys ))
194     {
195         uint64_t i_data_size;
196
197         if( p_sys->i_data_size != kCHUNK_SIZE_EOF)
198         {
199             i_data_size = p_sys->i_data_size;
200         }
201         else
202         {
203             int64_t i_stream_size = stream_Size( p_demux->s );
204             if(i_stream_size >= 0 && (uint64_t)i_stream_size >= p_sys->i_data_offset)
205                 i_data_size = i_stream_size - p_sys->i_data_offset;
206             else
207                 i_data_size = 0;
208         }
209
210         return i_data_size / p_sys->fmt.audio.i_bytes_per_frame;
211     }
212     else
213     {
214         return p_sys->packet_table.i_num_packets;
215     }
216 }
217
218 static uint64_t TotalNumSamples( demux_t *p_demux )
219 {
220     demux_sys_t *p_sys = p_demux->p_sys;
221
222     if( !NeedsPacketTable( p_sys ))
223     {
224         return TotalNumFrames( p_demux ) * p_sys->fmt.audio.i_frame_length;
225     }
226     else
227     {
228         return p_sys->packet_table.i_num_valid_frames + p_sys->packet_table.i_num_priming_frames +
229                 p_sys->packet_table.i_num_remainder_frames;
230     }
231 }
232
233 static inline vlc_fourcc_t ReadFOURCC( const uint8_t *p )
234 {
235     return VLC_FOURCC( p[0], p[1], p[2], p[3] );
236 }
237
238 /*****************************************************************************
239  * FrameSpan Functions
240  *****************************************************************************
241  *  A FrameSpan structure contains the relationship between a number of
242  frames, the number of samples they contain, the amount of data they
243  use, and the length of their packet descriptions (if any).
244  *****************************************************************************/
245
246 /* FrameSpanAddSpan adds span2 to span1 */
247
248 static inline void FrameSpanAddSpan( frame_span_t *span1, frame_span_t *span2 )
249 {
250     span1->i_frames += span2->i_frames;
251     span1->i_samples += span2->i_samples;
252     span1->i_bytes += span2->i_bytes;
253     span1->i_desc_bytes += span2->i_desc_bytes;
254 }
255
256 /* Adds the frame that is described at i_desc_offset to span */
257
258 static int FrameSpanAddDescription( demux_t *p_demux, uint64_t i_desc_offset, frame_span_t *span )
259 {
260     demux_sys_t *p_sys  = p_demux->p_sys;
261
262     /* Avoid seeking + peeking for simple case (PCM) */
263     if( p_sys->fmt.audio.i_bytes_per_frame && p_sys->fmt.audio.i_frame_length )
264     {
265         span->i_bytes += p_sys->fmt.audio.i_bytes_per_frame;
266         span->i_samples += p_sys->fmt.audio.i_frame_length;
267         span->i_frames++;
268         return VLC_SUCCESS;
269     }
270
271     uint32_t i_desc_size = 0;
272
273     if( stream_Seek( p_demux->s, p_sys->packet_table.i_descriptions_start + i_desc_offset ))
274     {
275         msg_Err( p_demux, "Couldn't seek packet description." );
276         return VLC_EGENERIC;
277     }
278
279     const uint8_t *p_peek;
280     uint32_t i_peek_len = stream_Peek( p_demux->s, &p_peek, 2 * 10 ); /* Peeking the maximum number of bytes that two 64 bit numbers could use (( 64 + 6 ) / 7 = 10 ). */
281
282     if( p_sys->fmt.audio.i_bytes_per_frame )
283     {
284         span->i_bytes += p_sys->fmt.audio.i_bytes_per_frame;
285     }
286     else
287     {
288         uint64_t i_size;
289         uint32_t i_this_int;
290         if( ParseVarLenInteger( p_peek, i_peek_len, &i_size, &i_this_int ))
291         {
292             return VLC_EGENERIC;
293         }
294
295         i_desc_size += i_this_int;
296         span->i_bytes += i_size;
297     }
298
299     if( p_sys->fmt.audio.i_frame_length )
300     {
301         span->i_samples += p_sys->fmt.audio.i_frame_length;
302     }
303     else
304     {
305         if( i_desc_size >= i_peek_len )
306         {
307             return VLC_EGENERIC;
308         }
309
310         uint64_t i_num_samples;
311         uint32_t i_this_int;
312         if( ParseVarLenInteger( p_peek + i_desc_size, i_peek_len - i_desc_size, &i_num_samples, &i_this_int ))
313         {
314             return VLC_EGENERIC;
315         }
316
317         i_desc_size += i_this_int;
318         span->i_samples += i_num_samples;
319     }
320     span->i_desc_bytes += i_desc_size;
321     span->i_frames++;
322
323     return VLC_SUCCESS;
324 }
325
326 /* FrameSpanGetTime returns the time span represented by the frame span. */
327
328 static inline mtime_t FrameSpanGetTime( frame_span_t *span, uint32_t i_sample_rate )
329 {
330     if( !i_sample_rate )
331         return 0;
332
333     return ( span->i_samples * CLOCK_FREQ ) / i_sample_rate + 1;
334 }
335
336 /* SetSpanWithSample returns the span from the beginning of the file up to and
337  including the specified sample. This works at frame granularity, so the
338  returned span may not represent the exact target sample.
339  Since we might have to lineraly search the packet descriptions, this is a
340  potentially slow operation! */
341
342 static int SetSpanWithSample( demux_t *p_demux, frame_span_t *p_span, uint64_t i_target_sample )
343 {
344     demux_sys_t *p_sys = p_demux->p_sys;
345
346     uint64_t i_num_frames = TotalNumFrames( p_demux );
347
348     if( !NeedsPacketTable( p_sys ))
349     {
350         uint64_t i_frame = i_target_sample / p_sys->fmt.audio.i_frame_length;
351         uint64_t i_remaining = i_target_sample - i_frame * p_sys->fmt.audio.i_frame_length;
352         if( i_remaining > ( p_sys->fmt.audio.i_frame_length / 2 ))
353             i_frame++;
354
355         if( i_frame > i_num_frames )
356             i_frame = i_num_frames;
357
358         p_span->i_frames = i_frame;
359         p_span->i_samples = i_frame * p_sys->fmt.audio.i_frame_length;
360         p_span->i_bytes = i_frame * p_sys->fmt.audio.i_bytes_per_frame;
361         p_span->i_desc_bytes = 0;
362     }
363     else
364     {
365         *p_span = (frame_span_t){0};
366         frame_span_t prev_span;
367
368         while( p_span->i_samples < i_target_sample && p_span->i_frames < i_num_frames )
369         {
370             prev_span = *p_span;
371
372             if( FrameSpanAddDescription( p_demux, p_span->i_desc_bytes, p_span ))
373                 return VLC_EGENERIC;
374
375             if( p_span->i_samples >= i_target_sample )
376             {
377                 uint64_t i_this_samples = p_span->i_samples - prev_span.i_samples;
378
379                 if( i_target_sample - prev_span.i_samples < i_this_samples / 2 )
380                     *p_span = prev_span;
381
382                 break;
383             }
384         }
385     }
386
387     return VLC_SUCCESS;
388 }
389
390 /*****************************************************************************
391  * CAF Parsing Functions
392  *****************************************************************************/
393
394 /* The NextChunk function returns the four char code and the (sanitized) size at the current file position.
395    Upon return the file position points to the start of the chunk payload.
396    Note that the ReadXXXChunk functions expect the chunk to size to be sanitized
397    (i.e. they don't check if it is bigger than INT64_MAX, but note the special case of the 'data' chunk, which can be kCHUNK_SIZE_EOF).
398  */
399
400 static int NextChunk( demux_t *p_demux, vlc_fourcc_t *p_fcc, uint64_t *pi_size )
401 {
402     uint8_t p_read[12];
403
404     if( stream_Read( p_demux->s, p_read, 12 ) < 12 )
405         return VLC_EGENERIC;
406
407     *p_fcc = ReadFOURCC( p_read );
408     uint64_t i_size = GetQWBE( p_read + 4 );
409
410     /* We accept no negativ sizes for chunks, except -1 for the data chunk. */
411
412     if( i_size > INT64_MAX )
413     {
414         if( *p_fcc == VLC_FOURCC( 'd', 'a', 't', 'a' ) && i_size == UINT64_C( -1 ))
415             i_size = kCHUNK_SIZE_EOF;
416         else
417             return VLC_EGENERIC;
418     }
419
420     *pi_size = i_size;
421
422     return VLC_SUCCESS;
423 }
424
425 static int ReadDescChunk( demux_t *p_demux )
426 {
427     demux_sys_t *p_sys = p_demux->p_sys;
428
429     const uint8_t *p_peek;
430
431     if ( stream_Peek( p_demux->s, &p_peek, 8 + 6 * 4 ) < ( 8 + 6 * 4 ))
432     {
433         return VLC_EGENERIC;
434     }
435
436     vlc_fourcc_t i_fmt = ReadFOURCC( p_peek + 8 );
437     uint32_t i_fmt_flags = GetDWBE( p_peek + 12 );
438
439     uint32_t i_bits_per_channel = GetDWBE( p_peek + 28 );
440     uint32_t i_bytes_per_packet = GetDWBE( p_peek + 16 );
441     uint32_t i_frames_per_packet = GetDWBE( p_peek + 20 );
442     uint32_t i_channels_per_frame = GetDWBE( p_peek + 24 );
443
444     if( i_fmt == VLC_CODEC_DVD_LPCM )
445     {
446         if( !i_frames_per_packet || !i_channels_per_frame )
447         {
448             msg_Err( p_demux, "Absurd LPCM parameters (frames_per_packet: %u, channels_per_frame: %u).", i_frames_per_packet, i_channels_per_frame );
449             return VLC_EGENERIC;
450         }
451
452         uint32_t i_unpacked_bits_per_sample = ( i_bytes_per_packet / i_frames_per_packet / i_channels_per_frame ) * 8;
453
454         bool b_is_float = !!( i_fmt_flags & ( 1 << 0 ) );
455         bool b_is_be = !( i_fmt_flags & ( 1 << 1 ) );
456
457         vlc_fourcc_t i_basic_codec = 0;
458
459         if( !b_is_float )
460         {
461             i_basic_codec = b_is_be ? VLC_FOURCC( 't', 'w', 'o', 's' ) : VLC_FOURCC( 's', 'o', 'w', 't' );
462             es_format_Init( &p_sys->fmt, AUDIO_ES, vlc_fourcc_GetCodecAudio( i_basic_codec, i_unpacked_bits_per_sample ));
463         }
464         else
465         {
466             if( i_bits_per_channel == 32 )
467                 i_basic_codec = b_is_be ? VLC_CODEC_F32B : VLC_CODEC_F32L;
468             else if( i_bits_per_channel == 64 )
469                 i_basic_codec = b_is_be ? VLC_CODEC_F64B : VLC_CODEC_F64L;
470
471             if( i_basic_codec )
472                 es_format_Init( &p_sys->fmt, AUDIO_ES, vlc_fourcc_GetCodecAudio( i_basic_codec, i_bits_per_channel ));
473         }
474     }
475     else if( i_fmt == VLC_FOURCC( 'a', 'a', 'c', ' ' ))
476     {
477         const uint32_t kMP4Audio_AAC_LC_ObjectType = 2;
478
479         if( i_fmt_flags != kMP4Audio_AAC_LC_ObjectType )
480         {
481             msg_Warn( p_demux, "The only documented format flag for aac is 2 (kMP4Audio_AAC_LC_ObjectType), but is %i. Continuing anyways.", i_fmt_flags );
482         }
483
484         es_format_Init( &p_sys->fmt, AUDIO_ES, vlc_fourcc_GetCodecAudio( VLC_CODEC_MP4A, 0 ));
485
486     }
487     else
488     {
489         es_format_Init( &p_sys->fmt, AUDIO_ES, vlc_fourcc_GetCodecAudio( i_fmt, 0 ));
490     }
491
492     if( !p_sys->fmt.i_codec )
493     {
494         msg_Err( p_demux, "could not determine codec" );
495         return VLC_EGENERIC;
496     }
497
498     double d_rate = round( GetDBLBE( p_peek ));
499
500     if( d_rate <= 0 || d_rate > UINT_MAX )
501         return VLC_EGENERIC;
502
503     p_sys->fmt.audio.i_rate = (unsigned int)lround( d_rate );
504     p_sys->fmt.audio.i_channels = i_channels_per_frame;
505     p_sys->fmt.audio.i_bytes_per_frame = i_bytes_per_packet; /* "mBytesPerPacket" in Apple parlance */
506     p_sys->fmt.audio.i_frame_length = i_frames_per_packet; /* "mFramesPerPacket" in Apple parlance */
507     p_sys->fmt.audio.i_bitspersample = i_bits_per_channel; /* mBitsPerChannel */
508     p_sys->fmt.audio.i_blockalign = i_bytes_per_packet;
509     p_sys->fmt.i_bitrate = i_bits_per_channel * p_sys->fmt.audio.i_rate * i_channels_per_frame;
510
511     return VLC_SUCCESS;
512 }
513
514 /*  This is lifted from cafdec.c in libavformat (function read_kuki_chunk). Appearantly the
515     alac library expects the cookie to be of length 36, but current alac files
516     have a cookie length of 24.
517  */
518 static int ProcessALACCookie( demux_t *p_demux, const uint8_t *p, uint64_t i_size )
519 {
520     demux_sys_t *p_sys = p_demux->p_sys;
521
522     const unsigned int kALAC_NEW_KUKI_SIZE = 24;
523     const unsigned int kALAC_LIB_REQ_KUKI_SIZE = 36;
524     int i_extra;
525
526     if( i_size == kALAC_NEW_KUKI_SIZE || i_size == kALAC_LIB_REQ_KUKI_SIZE )
527     {
528         i_extra = kALAC_LIB_REQ_KUKI_SIZE;
529     }
530     else
531     {
532         msg_Warn( p_demux, "Unknown alac magic cookie. Passing it on to the decoder as is and hoping for the best." );
533         i_extra = ( int )i_size;
534     }
535
536     p_sys->fmt.i_extra = i_extra;
537     p_sys->fmt.p_extra = malloc( i_extra );
538
539     if( !p_sys->fmt.p_extra )
540         return VLC_ENOMEM;
541
542     uint8_t *p_extra = ( uint8_t * )p_sys->fmt.p_extra;
543
544     if( i_size == kALAC_NEW_KUKI_SIZE )
545     {
546         SetDWBE( p_extra, 36 );
547         memcpy( p_extra + 4, "alac", 4 );
548         SetDWBE( p_extra + 8, 0 );
549         memcpy( p_extra + 12, p, 24 );
550     }
551     else
552     {
553         memcpy( p_sys->fmt.p_extra, p, i_size );
554     }
555
556     return VLC_SUCCESS;
557 }
558
559 /* Helper functions for AAC cookie processing. */
560
561 static inline bool AACCookieGetTag( uint8_t *p_tag, const uint8_t *p, uint64_t *p_offset, uint64_t i_size )
562 {
563     if( *p_offset + 1 > i_size )
564         return false;
565
566     *p_tag = *( p + *p_offset );
567     *p_offset += 1;
568
569     return true;
570 }
571
572 static inline bool AACCookieTagLen( uint64_t *p_tag_len, const uint8_t *p, uint64_t *p_offset, uint64_t i_size )
573 {
574     uint32_t i_int_size;
575
576     if( ParseVarLenInteger( p + *p_offset, i_size - *p_offset, p_tag_len, &i_int_size ))
577         return false;
578
579     *p_offset += i_int_size;
580
581     return true;
582 }
583
584 static inline bool AACCookieChkLen( int64_t i_length, uint64_t i_size, uint64_t i_offset )
585 {
586     return ( i_offset + i_length <= i_size );
587 }
588
589 /*  This is lifted from libmp4.c in the mp4 demuxer module (function MP4_ReadBox_esds). The aac
590     library only want a subset of the magic cookie ("decoder specific info"), so we have to parse it.
591  */
592 static int ProcessAACCookie( demux_t *p_demux, const uint8_t *p, uint64_t i_size )
593 {
594     const uint8_t kAAC_ES_DESCR_TAG = 3;
595     const uint8_t kAAC_DEC_CONFIG_DESCR_TAG = 4;
596     const uint8_t kAAC_DEC_SPEC_INFO_TAG = 5;
597
598     demux_sys_t *p_sys = p_demux->p_sys;
599
600     uint64_t i_offset = 0;
601     uint64_t i_kuki_size = 0;
602     uint64_t i_tag_len;
603     uint8_t i_tag;
604
605     if( !AACCookieGetTag( &i_tag, p, &i_offset, i_size )) goto aac_kuki_finish;
606
607     if( i_tag == kAAC_ES_DESCR_TAG )
608     {
609
610         if( !AACCookieTagLen( &i_tag_len, p, &i_offset, i_size )) goto aac_kuki_finish;
611
612         if( !AACCookieChkLen( 3, i_size, i_offset )) goto aac_kuki_finish;
613         i_offset += 2; /* don't care (ES ID) */
614         uint8_t i_flags = *( p + i_offset++ );
615
616         if( i_flags&0x80 )
617         {
618             if( !AACCookieChkLen( 2, i_size, i_offset )) goto aac_kuki_finish;
619             i_offset += 2; /* don't care (dependance) */
620         }
621         if( i_flags&0x40 )
622         {
623             if( !AACCookieChkLen( 1, i_size, i_offset )) goto aac_kuki_finish;
624             uint8_t i_url_len = *( p + i_offset++ );
625             i_offset += i_url_len; /* don't care (url) */
626         }
627         if( i_flags&0x20 )
628         {
629             if( !AACCookieChkLen( 2, i_size, i_offset )) goto aac_kuki_finish;
630             i_offset += 2; /* don't care (OCR) */
631         }
632
633         if( !AACCookieGetTag( &i_tag, p, &i_offset, i_size )) goto aac_kuki_finish;
634     }
635
636     if( i_tag != kAAC_DEC_CONFIG_DESCR_TAG )
637         goto aac_kuki_finish;
638
639     if( !AACCookieTagLen( &i_tag_len, p, &i_offset, i_size )) goto aac_kuki_finish;
640
641     if( !AACCookieChkLen( 1 + 1 + 3 + 4 + 4, i_size, i_offset )) goto aac_kuki_finish;
642     i_offset += ( 1 + 1 + 3 + 4 + 4 ); /* don't care */
643
644     if( !AACCookieGetTag( &i_tag, p, &i_offset, i_size )) goto aac_kuki_finish;
645
646     if( i_tag != kAAC_DEC_SPEC_INFO_TAG ) /* this is the one we need */
647         goto aac_kuki_finish;
648
649     if( !AACCookieTagLen( &i_tag_len, p, &i_offset, i_size )) goto aac_kuki_finish;
650
651     if( i_offset + i_tag_len > i_size )
652         goto aac_kuki_finish;
653
654     i_kuki_size = i_tag_len;
655
656 aac_kuki_finish:
657
658     if( !i_kuki_size )
659     {
660         msg_Warn( p_demux, "Error parsing aac cookie. Passing it on to the decoder as is and hoping for the best." );
661         i_kuki_size = i_size;
662         i_offset = 0;
663     }
664
665     p_sys->fmt.i_extra = (int)i_kuki_size;
666     p_sys->fmt.p_extra = malloc( i_kuki_size );
667
668     if( !p_sys->fmt.p_extra )
669     {
670         return VLC_ENOMEM;
671     }
672
673     memcpy( p_sys->fmt.p_extra, p + i_offset, i_kuki_size );
674
675     return VLC_SUCCESS;
676 }
677
678 static int ReadKukiChunk( demux_t *p_demux, uint64_t i_size )
679 {
680     demux_sys_t *p_sys = p_demux->p_sys;
681     const uint8_t *p_peek;
682
683     /* stream_Peek can't handle sizes bigger than INT32_MAX, and also p_sys->fmt.i_extra is of type 'int'*/
684     if( i_size > INT32_MAX )
685     {
686         msg_Err( p_demux, "Magic Cookie chunk too big" );
687         return VLC_EGENERIC;
688     }
689
690     if( (unsigned int)stream_Peek( p_demux->s, &p_peek, (int)i_size ) < i_size )
691     {
692         msg_Err( p_demux, "Couldn't peek extra data" );
693         return VLC_EGENERIC;
694     }
695
696     if( p_sys->fmt.i_codec  == VLC_CODEC_ALAC )
697     {
698         int error = ProcessALACCookie( p_demux, p_peek, i_size );
699         if( error ) return error;
700     }
701     else if( p_sys->fmt.i_codec == VLC_CODEC_MP4A )
702     {
703         int error = ProcessAACCookie( p_demux, p_peek, i_size );
704         if( error ) return error;
705     }
706     else
707     {
708         p_sys->fmt.i_extra = (int)i_size;
709         p_sys->fmt.p_extra = malloc( i_size );
710
711         if( !p_sys->fmt.p_extra )
712         {
713             return VLC_ENOMEM;
714         }
715         memcpy( p_sys->fmt.p_extra, p_peek, p_sys->fmt.i_extra );
716     }
717
718     return VLC_SUCCESS;
719 }
720
721 static int ReadDataChunk( demux_t *p_demux, uint64_t i_size )
722 {
723     if( i_size < 4 )
724         return VLC_EGENERIC;
725
726     demux_sys_t *p_sys = p_demux->p_sys;
727
728     p_sys->i_data_offset = stream_Tell( p_demux->s ) + 4; /* skip edit count */
729     p_sys->i_data_size = i_size == kCHUNK_SIZE_EOF ? kCHUNK_SIZE_EOF : ( i_size - 4 );
730
731     return VLC_SUCCESS;
732 }
733
734 static int ReadPaktChunk( demux_t *p_demux )
735 {
736     demux_sys_t *p_sys = p_demux->p_sys;
737
738     const uint8_t *p_peek;
739
740     if ( stream_Peek( p_demux->s, &p_peek, 8 + 8 + 4 + 4 ) < ( 8 + 8 + 4 + 4 ))
741     {
742         msg_Err( p_demux, "Couldn't peek packet descriptions" );
743         return VLC_EGENERIC;
744     }
745
746     if( ReadBEInt64ToUInt64( p_peek, &p_sys->packet_table.i_num_packets ))
747     {
748         msg_Err( p_demux, "Invalid packet table: i_num_packets is negative.");
749         return VLC_EGENERIC;
750     }
751     if( ReadBEInt64ToUInt64( p_peek + 8, &p_sys->packet_table.i_num_valid_frames ))
752     {
753         msg_Err( p_demux, "Invalid packet table: i_num_valid_frames is negative.");
754         return VLC_EGENERIC;
755     }
756     if( ReadBEInt32ToUInt32( p_peek + 16, &p_sys->packet_table.i_num_priming_frames ))
757     {
758         msg_Err( p_demux, "Invalid packet table: i_num_priming_frames is negative.");
759         return VLC_EGENERIC;
760     }
761     if( ReadBEInt32ToUInt32( p_peek + 20, &p_sys->packet_table.i_num_remainder_frames ))
762     {
763         msg_Err( p_demux, "Invalid packet table: i_num_remainder_frames is negative.");
764         return VLC_EGENERIC;
765     }
766
767     p_sys->packet_table.i_descriptions_start = stream_Tell( p_demux->s ) + 24;
768
769     return VLC_SUCCESS;
770 }
771
772 /*****************************************************************************
773  * Open
774  *****************************************************************************/
775 static int Open( vlc_object_t *p_this )
776 {
777     int i_error = VLC_SUCCESS;
778
779     demux_t     *p_demux = (demux_t*)p_this;
780     demux_sys_t *p_sys;
781
782     const uint8_t *p_peek;
783
784     if( stream_Peek( p_demux->s, &p_peek, 8 ) < 8 )
785         return VLC_EGENERIC;
786
787     /* Is it a caf file? */
788     if( memcmp( p_peek, "caff", 4 ))
789         return VLC_EGENERIC;
790
791     /* check file version (we only handle version 1) */
792     uint16_t i_version = GetWBE( p_peek + 4 );
793     if( i_version != 1 )
794     {
795         msg_Dbg( p_demux, "Unknown caf file version %d.", i_version );
796         return VLC_EGENERIC;
797     }
798
799     /* check file flags (must be 0) */
800     uint16_t i_flags = GetWBE( p_peek + 6 );
801     if( i_flags != 0 )
802     {
803         msg_Dbg( p_demux, "Unknown caf file flags %d.", i_flags );
804         return VLC_EGENERIC;
805     }
806
807     if( stream_Read( p_demux->s, NULL, 8 ) < 8 )
808         return VLC_EGENERIC; /* This would be very strange since we justed peeked at these bytes. */
809
810     p_demux->p_sys = calloc( 1, sizeof( demux_sys_t ));
811     if( !p_demux->p_sys ) return VLC_ENOMEM;
812
813     /* From this point on, we have to free p_sys if we return an error (e.g. "goto caf_open_end") */
814
815     p_sys = p_demux->p_sys;
816     es_format_Init( &p_sys->fmt, UNKNOWN_ES, 0 );
817
818     vlc_fourcc_t i_fcc;
819     uint64_t i_size;
820     uint64_t i_idx = 0;
821
822     while( NextChunk( p_demux, &i_fcc, &i_size ) == VLC_SUCCESS )
823     {
824         bool b_handled = true;
825
826         switch ( i_fcc )
827         {
828             case VLC_FOURCC( 'd', 'e', 's', 'c' ):
829
830                 if( i_idx != 0 )
831                 {
832                     msg_Err( p_demux, "The audio description chunk must be the first chunk in a caf file." );
833                     i_error = VLC_EGENERIC;
834                     goto caf_open_end;
835                 }
836
837                 i_error = ReadDescChunk( p_demux );
838                 break;
839
840             case VLC_FOURCC( 'd', 'a', 't', 'a' ):
841
842                 i_error = ReadDataChunk( p_demux, i_size );
843                 break;
844
845             case VLC_FOURCC( 'p', 'a', 'k', 't' ):
846
847                 i_error = ReadPaktChunk( p_demux );
848                 break;
849
850             case VLC_FOURCC( 'k', 'u', 'k', 'i' ):
851
852                 i_error = ReadKukiChunk( p_demux, i_size );
853                 break;
854
855             default:
856
857                 b_handled = false;
858                 break;
859         }
860
861         if( i_error )
862             goto caf_open_end;
863
864         if( b_handled )
865             msg_Dbg( p_demux, "Found '%4.4s' chunk.", ( char * )&i_fcc );
866         else
867             msg_Dbg( p_demux, "Ignoring '%4.4s' chunk.", ( char * )&i_fcc );
868
869         if( i_size == kCHUNK_SIZE_EOF )
870             break;
871
872         if( stream_Seek( p_demux->s, stream_Tell( p_demux->s ) + i_size ) != VLC_SUCCESS )
873             break;
874
875         i_idx++;
876     }
877
878     if ( !p_sys->i_data_offset || p_sys->fmt.i_cat != AUDIO_ES ||
879         ( NeedsPacketTable( p_sys ) && !p_sys->packet_table.i_descriptions_start ))
880     {
881         msg_Err( p_demux, "Did not find all necessary chunks." );
882         i_error = VLC_EGENERIC;
883         goto caf_open_end;
884     }
885
886     p_sys->es = es_out_Add( p_demux->out, &p_sys->fmt );
887
888     if( !p_sys->es )
889     {
890         msg_Err( p_demux, "Could not add elementary stream." );
891         i_error = VLC_EGENERIC;
892         goto caf_open_end;
893     }
894
895 caf_open_end:
896
897     if( i_error )
898     {
899         free( p_sys->fmt.p_extra );
900         free( p_sys  );
901
902         if( stream_Seek( p_demux->s, 0 ))
903         {
904             msg_Warn(p_demux, "Could not reset stream position to 0.");
905         }
906     }
907     else
908     {
909         p_demux->pf_control = Control;
910         p_demux->pf_demux = Demux;
911     }
912
913     return i_error;
914 }
915
916 /*****************************************************************************
917  * Demux:
918  *****************************************************************************/
919 static int Demux( demux_t *p_demux )
920 {
921     demux_sys_t *p_sys = p_demux->p_sys;
922     block_t     *p_block;
923
924     if( p_sys->i_data_size != kCHUNK_SIZE_EOF && p_sys->position.i_bytes >= p_sys->i_data_size )
925     {
926         /* EOF */
927         return 0;
928     }
929
930     frame_span_t advance = (frame_span_t){0};
931
932     /* we will read 50ms at once */
933     uint64_t i_req_samples = __MAX( p_sys->fmt.audio.i_rate / 20, 1 );
934
935     if( !NeedsPacketTable( p_sys )) /* PCM/IMA4 */
936     {
937         int64_t i_req_frames = ( i_req_samples + ( p_sys->fmt.audio.i_frame_length - 1 )) / p_sys->fmt.audio.i_frame_length;
938
939         if( p_sys->i_data_size != kCHUNK_SIZE_EOF && ( p_sys->position.i_bytes + i_req_frames * p_sys->fmt.audio.i_bytes_per_frame ) > p_sys->i_data_size )
940         {
941             i_req_frames = ( p_sys->i_data_size - p_sys->position.i_frames * p_sys->fmt.audio.i_bytes_per_frame ) / p_sys->fmt.audio.i_bytes_per_frame;
942         }
943
944         advance.i_frames = i_req_frames;
945         advance.i_samples = i_req_frames * p_sys->fmt.audio.i_frame_length;
946         advance.i_bytes = p_sys->fmt.audio.i_bytes_per_frame * advance.i_frames;
947     }
948     else /* use packet table */
949     {
950         do
951         {
952             if( FrameSpanAddDescription( p_demux, p_sys->position.i_desc_bytes + advance.i_desc_bytes, &advance ))
953                 break;
954         }
955         while (( i_req_samples > advance.i_samples ) && ( p_sys->position.i_frames + advance.i_frames ) < p_sys->packet_table.i_num_packets );
956     }
957
958     if( !advance.i_frames )
959     {
960         msg_Err( p_demux, "Unexpected end of file" );
961         return -1;
962     }
963
964     if( stream_Seek( p_demux->s, p_sys->i_data_offset + p_sys->position.i_bytes ))
965     {
966         if( p_sys->i_data_size == kCHUNK_SIZE_EOF)
967             return 0;
968
969         msg_Err( p_demux, "cannot seek data" );
970         return -1;
971     }
972
973     if(( p_block = stream_Block( p_demux->s, (int)advance.i_bytes )) == NULL )
974     {
975         msg_Err( p_demux, "cannot read data" );
976         return -1;
977     }
978
979     p_block->i_dts =
980     p_block->i_pts = VLC_TS_0 + FrameSpanGetTime( &p_sys->position, p_sys->fmt.audio.i_rate );
981
982     FrameSpanAddSpan( &p_sys->position, &advance );
983
984     /* set PCR */
985     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block->i_pts );
986
987     es_out_Send( p_demux->out, p_sys->es, p_block );
988
989     return 1;
990 }
991
992 /*****************************************************************************
993  * Control:
994  *****************************************************************************/
995 static int Control( demux_t *p_demux, int i_query, va_list args )
996 {
997     int64_t i64, *pi64, i_sample;
998     double f, *pf;
999     frame_span_t position;
1000
1001     demux_sys_t *p_sys  = p_demux->p_sys;
1002     uint64_t i_num_samples = TotalNumSamples( p_demux );
1003
1004     switch( i_query )
1005     {
1006         case DEMUX_GET_LENGTH:
1007             pi64 = ( int64_t* )va_arg( args, int64_t * );
1008             *pi64 = CLOCK_FREQ * ( i_num_samples / p_sys->fmt.audio.i_rate );
1009             return VLC_SUCCESS;
1010
1011         case DEMUX_GET_TIME:
1012             pi64 = ( int64_t* )va_arg( args, int64_t * );
1013             *pi64 = CLOCK_FREQ * ( p_sys->position.i_samples / p_sys->fmt.audio.i_rate );
1014             return VLC_SUCCESS;
1015
1016         case DEMUX_GET_POSITION:
1017             pf = (double*)va_arg( args, double * );
1018             *pf = i_num_samples ? (double)p_sys->position.i_samples / (double)i_num_samples : 0.0;
1019             return VLC_SUCCESS;
1020
1021         case DEMUX_SET_POSITION:
1022             f = (double)va_arg( args, double );
1023             i_sample = f * i_num_samples;
1024             if( SetSpanWithSample( p_demux, &position, i_sample ))
1025                 return VLC_EGENERIC;
1026             p_sys->position = position;
1027             return VLC_SUCCESS;
1028
1029         case DEMUX_SET_TIME:
1030             i64 = (int64_t)va_arg( args, int64_t );
1031             i_sample = i64 * p_sys->fmt.audio.i_rate / INT64_C( 1000000 );
1032             if( SetSpanWithSample( p_demux, &position, i_sample ))
1033                 return VLC_EGENERIC;
1034             p_sys->position = position;
1035             return VLC_SUCCESS;
1036
1037         case DEMUX_GET_META:
1038             return stream_Control( p_demux->s, STREAM_GET_META, args );
1039
1040         default:
1041             return VLC_EGENERIC;
1042     }
1043
1044     return VLC_EGENERIC;
1045 }
1046
1047 /*****************************************************************************
1048  * Close
1049  *****************************************************************************/
1050 static void Close( vlc_object_t *p_this )
1051 {
1052     demux_t     *p_demux = (demux_t*)p_this;
1053     demux_sys_t *p_sys = p_demux->p_sys;
1054
1055     es_out_Del( p_demux->out, p_sys->es );
1056
1057     free( p_sys->fmt.p_extra );
1058     free( p_sys );
1059 }