]> git.sesse.net Git - vlc/blob - modules/codec/quicktime.c
de073126c035f9068221ba02dc1f472a1342e7a6
[vlc] / modules / codec / quicktime.c
1 /*****************************************************************************
2  * quicktime.c: a quicktime decoder that uses the QT library/dll
3  *****************************************************************************
4  * Copyright (C) 2003 VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir at via.ecp.fr>
8  *          Derk-Jan Hartman <thedj at users.sf.net>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 #include <vlc/vlc.h>
30 #include <vlc/aout.h>
31 #include <vlc/vout.h>
32 #include <vlc/decoder.h>
33
34 #ifdef SYS_DARWIN
35 #include <QuickTime/QuickTimeComponents.h>
36 #include <QuickTime/Movies.h>
37 #include <QuickTime/ImageCodec.h>
38 #endif
39
40 /* for windows do we require Quicktime compents header? */
41 #ifdef LOADER
42 #include "w32dll/loader/qtx/qtxsdk/components.h"
43 #include "w32dll/loader/wine/windef.h"
44 #include "w32dll/loader/ldt_keeper.h"
45
46 HMODULE   WINAPI LoadLibraryA(LPCSTR);
47 FARPROC   WINAPI GetProcAddress(HMODULE,LPCSTR);
48 int       WINAPI FreeLibrary(HMODULE);
49
50 #endif
51
52 /*****************************************************************************
53  * Module descriptor
54  *****************************************************************************/
55 static int  Open ( vlc_object_t * );
56 static void Close( vlc_object_t * );
57
58 vlc_module_begin();
59     set_description( _("QuickTime library decoder") );
60     set_capability( "decoder", 10 );
61     set_callbacks( Open, Close );
62
63     /* create a mutex */
64     var_Create( p_module->p_libvlc, "qt_mutex", VLC_VAR_MUTEX );
65 vlc_module_end();
66
67
68 /*****************************************************************************
69  * Local prototypes
70  *****************************************************************************/
71 static int           OpenAudio( decoder_t * );
72 static int           OpenVideo( decoder_t * );
73
74 static aout_buffer_t *DecodeAudio( decoder_t *, block_t ** );
75 static picture_t     *DecodeVideo( decoder_t *, block_t ** );
76
77 #define FCC( a, b , c, d ) \
78     ((uint32_t)( ((a)<<24)|((b)<<16)|((c)<<8)|(d)))
79
80 #ifndef SYS_DARWIN
81 typedef struct OpaqueSoundConverter*    SoundConverter;
82 #ifndef LOADER
83 typedef long                            OSType;
84 typedef int                             OSErr;
85 #endif
86 typedef unsigned long                   UnsignedFixed;
87 typedef uint8_t                         Byte;
88
89 typedef struct SoundComponentData {
90     long                            flags;
91     OSType                          format;
92     short                           numChannels;
93     short                           sampleSize;
94     UnsignedFixed                   sampleRate;
95     long                            sampleCount;
96     Byte *                          buffer;
97     long                            reserved;
98 } SoundComponentData;
99
100 #endif /* SYS_DARWIN */
101
102 struct decoder_sys_t
103 {
104     /* library */
105 #ifndef SYS_DARWIN
106 #ifdef LOADER
107     ldt_fs_t    *ldt_fs;
108
109 #endif /* LOADER */
110     HMODULE qtml;
111     OSErr (*InitializeQTML)             ( long flags );
112     OSErr (*TerminateQTML)              ( void );
113 #endif /* SYS_DARWIN */
114
115     /* Audio */
116     int (*SoundConverterOpen)           ( const SoundComponentData *,
117                                           const SoundComponentData *,
118                                           SoundConverter* );
119     int (*SoundConverterClose)          ( SoundConverter );
120     int (*SoundConverterSetInfo)        ( SoundConverter , OSType, void * );
121     int (*SoundConverterGetBufferSizes) ( SoundConverter, unsigned long,
122                                           unsigned long*, unsigned long*,
123                                           unsigned long* );
124     int (*SoundConverterBeginConversion)( SoundConverter );
125     int (*SoundConverterEndConversion)  ( SoundConverter, void *,
126                                           unsigned long *, unsigned long *);
127     int (*SoundConverterConvertBuffer)  ( SoundConverter, const void *,
128                                           unsigned long, void *,
129                                           unsigned long *, unsigned long * );
130     SoundConverter      myConverter;
131     SoundComponentData  InputFormatInfo, OutputFormatInfo;
132
133     long            FramesToGet;
134     unsigned int    InFrameSize;
135     unsigned int    OutFrameSize;
136
137 #ifndef WIN32
138     /* Video */
139     Component         (*FindNextComponent)
140         ( Component prev, ComponentDescription* desc );
141
142     ComponentInstance (*OpenComponent)
143         ( Component c );
144
145     ComponentResult   (*ImageCodecInitialize)
146         ( ComponentInstance ci, ImageSubCodecDecompressCapabilities * cap);
147
148     ComponentResult   (*ImageCodecGetCodecInfo)
149         ( ComponentInstance ci, CodecInfo *info );
150
151     ComponentResult   (*ImageCodecPreDecompress)
152         ( ComponentInstance ci, CodecDecompressParams * params );
153
154     ComponentResult   (*ImageCodecBandDecompress)
155         ( ComponentInstance ci, CodecDecompressParams * params );
156
157     PixMapHandle      (*GetGWorldPixMap)
158         ( GWorldPtr offscreenGWorld );
159
160     OSErr             (*QTNewGWorldFromPtr)
161         ( GWorldPtr *gw, OSType pixelFormat, const Rect *boundsRect,
162           CTabHandle cTable, /*GDHandle*/ void *aGDevice, /*unused*/
163           GWorldFlags flags, void *baseAddr, long rowBytes );
164
165     OSErr             (*NewHandleClear)( Size byteCount );
166
167     ComponentInstance       ci;
168     Rect                    OutBufferRect;   /* the dimensions of our GWorld */
169     GWorldPtr               OutBufferGWorld; /* a GWorld is some kind of
170                                                 description for a drawing
171                                                 environment */
172     ImageDescriptionHandle  framedescHandle;
173
174     CodecDecompressParams   decpar;          /* for ImageCodecPreDecompress()*/
175     CodecCapabilities       codeccap;        /* for decpar */
176 #endif
177
178     /* Output properties */
179     uint8_t *           plane;
180     mtime_t             pts;
181     audio_date_t        date;
182
183     int                 i_late; /* video */
184
185     /* buffer */
186     unsigned int        i_buffer;
187     unsigned int        i_buffer_size;
188     uint8_t             *p_buffer;
189
190     /* Audio only */
191     uint8_t             out_buffer[1000000];    /* FIXME */
192     int                 i_out_frames;
193     int                 i_out;
194 };
195
196 static int pi_channels_maps[6] =
197 {
198     0,
199     AOUT_CHAN_CENTER,
200     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
201     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER,
202     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARLEFT,
203     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
204      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARLEFT
205 };
206
207 static int QTAudioInit( decoder_t * );
208 static int QTVideoInit( decoder_t * );
209
210 /*****************************************************************************
211  * Open: probe the decoder and return score
212  *****************************************************************************
213  * Tries to launch a decoder and return score so that the interface is able
214  * to choose.
215  *****************************************************************************/
216 static int Open( vlc_object_t *p_this )
217 {
218     decoder_t *p_dec = (decoder_t*)p_this;
219
220     switch( p_dec->fmt_in.i_codec )
221     {
222         case VLC_FOURCC('S','V','Q','3'): /* Sorenson v3 */
223     /*    case VLC_FOURCC('S','V','Q','1'):  Sorenson v1 
224         case VLC_FOURCC('Z','y','G','o'):
225         case VLC_FOURCC('V','P','3','1'):
226         case VLC_FOURCC('3','I','V','1'): */
227         case VLC_FOURCC('r','l','e',' '): /* QuickTime animation (RLE) */
228         case VLC_FOURCC('r','p','z','a'): /* QuickTime Apple Video */
229         case VLC_FOURCC('a','z','p','r'): /* QuickTime animation (RLE) */
230 #ifdef LOADER
231             p_dec->p_sys = NULL;
232             p_dec->pf_decode_video = DecodeVideo;
233             return VLC_SUCCESS;
234 #else
235             return OpenVideo( p_dec );
236 #endif
237
238         case VLC_FOURCC('s','a','m','r'): /* 3GPP AMR audio */
239         case VLC_FOURCC('m','p','4','a'): /* MPEG-4 audio */
240         case VLC_FOURCC('Q','D','M','C'): /* QDesign */
241         case VLC_FOURCC('Q','D','M','2'): /* QDesign* 2 */
242         case VLC_FOURCC('Q','c','l','p'): /* Qualcomm Purevoice Codec */
243         case VLC_FOURCC('Q','C','L','P'): /* Qualcomm Purevoice Codec */
244         case VLC_FOURCC('M','A','C','3'): /* MACE3 audio decoder */
245         case VLC_FOURCC('M','A','C','6'): /* MACE6 audio decoder */
246         case VLC_FOURCC('d','v','c','a'): /* DV Audio */
247         case VLC_FOURCC('s','o','w','t'): /* 16-bit Little Endian */
248         case VLC_FOURCC('t','w','o','s'): /* 16-bit Big Endian */
249         case VLC_FOURCC('a','l','a','w'): /* ALaw 2:1 */
250         case VLC_FOURCC('u','l','a','w'): /* mu-Law 2:1 */
251         case VLC_FOURCC('r','a','w',' '): /* 8-bit offset binaries */
252         case VLC_FOURCC('f','l','3','2'): /* 32-bit Floating Point */
253         case VLC_FOURCC('f','l','6','4'): /* 64-bit Floating Point */
254         case VLC_FOURCC('i','n','2','4'): /* 24-bit Interger */
255         case VLC_FOURCC('i','n','3','2'): /* 32-bit Integer */
256         case 0x0011:                            /* DVI IMA */
257         case 0x6D730002:                        /* Microsoft ADPCM-ACM */
258         case 0x6D730011:                        /* DVI Intel IMAADPCM-ACM */
259 #ifdef LOADER
260             p_dec->p_sys = NULL;
261             p_dec->pf_decode_audio = DecodeAudio;
262             return VLC_SUCCESS;
263 #else
264             return OpenAudio( p_dec );
265 #endif
266
267         default:
268             return VLC_EGENERIC;
269     }
270 }
271
272 /*****************************************************************************
273  * Close:
274  *****************************************************************************/
275 static void Close( vlc_object_t *p_this )
276 {
277     decoder_t     *p_dec = (decoder_t*)p_this;
278     decoder_sys_t *p_sys = p_dec->p_sys;
279     vlc_value_t   lockval;
280
281     /* get lock, avoid segfault */
282     var_Get( p_dec->p_libvlc, "qt_mutex", &lockval );
283     vlc_mutex_lock( lockval.p_address );
284 #ifdef SYS_DARWIN
285     /* on OS X QT is not threadsafe */
286     vlc_mutex_lock( &p_dec->p_vlc->quicktime_lock );
287 #endif
288
289     if( p_dec->fmt_out.i_cat == AUDIO_ES )
290     {
291         int i_error;
292         unsigned long ConvertedFrames=0;
293         unsigned long ConvertedBytes=0;
294
295         i_error = p_sys->SoundConverterEndConversion( p_sys->myConverter, NULL,
296                                                       &ConvertedFrames,
297                                                       &ConvertedBytes );
298         msg_Dbg( p_dec, "SoundConverterEndConversion => %d", i_error );
299
300         i_error = p_sys->SoundConverterClose( p_sys->myConverter );
301         msg_Dbg( p_dec, "SoundConverterClose => %d", i_error );
302
303         free( p_sys->p_buffer );
304     }
305     else if( p_dec->fmt_out.i_cat == VIDEO_ES )
306     {
307         free( p_sys->plane );
308     }
309
310 #ifndef SYS_DARWIN
311     FreeLibrary( p_sys->qtml );
312     msg_Dbg( p_dec, "FreeLibrary ok." );
313 #endif
314
315 #ifdef SYS_DARWIN
316     ExitMovies();
317 #endif
318
319 #if 0
320     /* Segfault */
321 #ifdef LOADER
322     Restore_LDT_Keeper( p_sys->ldt_fs );
323     msg_Dbg( p_dec, "Restore_LDT_Keeper" );
324 #endif
325 #endif
326
327 #ifdef SYS_DARWIN
328     vlc_mutex_unlock( &p_dec->p_vlc->quicktime_lock );
329 #endif
330     vlc_mutex_unlock( lockval.p_address );
331
332     free( p_sys );
333 }
334
335 /*****************************************************************************
336  * OpenAudio:
337  *****************************************************************************/
338 static int OpenAudio( decoder_t *p_dec )
339 {
340     decoder_sys_t *p_sys = malloc( sizeof( decoder_sys_t ) );
341
342     vlc_value_t     lockval;
343     int             i_error;
344     char            fcc[4];
345     unsigned long   WantedBufferSize;
346     unsigned long   InputBufferSize = 0;
347     unsigned long   OutputBufferSize = 0;
348
349     memset( p_sys, 0, sizeof( decoder_sys_t ) );
350
351     p_dec->p_sys = p_sys;
352     p_dec->pf_decode_audio = DecodeAudio;
353
354     memcpy( fcc, &p_dec->fmt_in.i_codec, 4 );
355
356     /* get lock, avoid segfault */
357     var_Get( p_dec->p_libvlc, "qt_mutex", &lockval );
358     vlc_mutex_lock( lockval.p_address );
359 #ifdef SYS_DARWIN
360     /* on OS X QT is not threadsafe */
361     vlc_mutex_lock( &p_dec->p_vlc->quicktime_lock );
362 #endif
363
364 #ifdef SYS_DARWIN
365     EnterMovies();
366 #endif
367
368     if( QTAudioInit( p_dec ) )
369     {
370         msg_Err( p_dec, "cannot initialize QT");
371         goto exit_error;
372     }
373
374 #ifndef SYS_DARWIN
375     if( ( i_error = p_sys->InitializeQTML( 6 + 16 ) ) )
376     {
377         msg_Dbg( p_dec, "error on InitializeQTML = %d", i_error );
378         goto exit_error;
379     }
380 #endif
381
382     /* input format settings */
383     p_sys->InputFormatInfo.flags       = 0;
384     p_sys->InputFormatInfo.sampleCount = 0;
385     p_sys->InputFormatInfo.buffer      = NULL;
386     p_sys->InputFormatInfo.reserved    = 0;
387     p_sys->InputFormatInfo.numChannels = p_dec->fmt_in.audio.i_channels;
388     p_sys->InputFormatInfo.sampleSize  = p_dec->fmt_in.audio.i_bitspersample;
389     p_sys->InputFormatInfo.sampleRate  = p_dec->fmt_in.audio.i_rate;
390     p_sys->InputFormatInfo.format      = FCC( fcc[0], fcc[1], fcc[2], fcc[3] );
391
392     /* output format settings */
393     p_sys->OutputFormatInfo.flags       = 0;
394     p_sys->OutputFormatInfo.sampleCount = 0;
395     p_sys->OutputFormatInfo.buffer      = NULL;
396     p_sys->OutputFormatInfo.reserved    = 0;
397     p_sys->OutputFormatInfo.numChannels = p_dec->fmt_in.audio.i_channels;
398     p_sys->OutputFormatInfo.sampleSize  = 16;
399     p_sys->OutputFormatInfo.sampleRate  = p_dec->fmt_in.audio.i_rate;
400     p_sys->OutputFormatInfo.format      = FCC( 'N', 'O', 'N', 'E' );
401
402
403     i_error = p_sys->SoundConverterOpen( &p_sys->InputFormatInfo,
404                                          &p_sys->OutputFormatInfo,
405                                          &p_sys->myConverter );
406     if( i_error )
407     {
408         msg_Err( p_dec, "error on SoundConverterOpen = %d", i_error );
409         goto exit_error;
410     }
411
412 #if 0
413     /* tell the sound converter we accept VBR formats */
414     i_error = SoundConverterSetInfo( p_dec->myConverter, siClientAcceptsVBR,
415                                      (void *)true );
416 #endif
417
418     if( p_dec->fmt_in.i_extra > 36 + 8 )
419     {
420         i_error = p_sys->SoundConverterSetInfo( p_sys->myConverter,
421                                                 FCC( 'w', 'a', 'v', 'e' ),
422                                                 ((uint8_t*)p_dec->fmt_in.p_extra) + 36 + 8 );
423
424         msg_Dbg( p_dec, "error on SoundConverterSetInfo = %d", i_error );
425     }
426
427     WantedBufferSize = p_sys->OutputFormatInfo.numChannels *
428                        p_sys->OutputFormatInfo.sampleRate * 2;
429     p_sys->FramesToGet = 0;
430
431     i_error = p_sys->SoundConverterGetBufferSizes( p_sys->myConverter,
432                                                    WantedBufferSize,
433                                                    &p_sys->FramesToGet,
434                                                    &InputBufferSize,
435                                                    &OutputBufferSize );
436
437     msg_Dbg( p_dec, "WantedBufferSize=%li InputBufferSize=%li "
438              "OutputBufferSize=%li FramesToGet=%li",
439              WantedBufferSize, InputBufferSize, OutputBufferSize,
440              p_sys->FramesToGet );
441
442     p_sys->InFrameSize  = (InputBufferSize + p_sys->FramesToGet - 1 ) /
443                             p_sys->FramesToGet;
444     p_sys->OutFrameSize = OutputBufferSize / p_sys->FramesToGet;
445
446     msg_Dbg( p_dec, "frame size %d -> %d",
447              p_sys->InFrameSize, p_sys->OutFrameSize );
448
449     if( (i_error = p_sys->SoundConverterBeginConversion(p_sys->myConverter)) )
450     {
451         msg_Err( p_dec,
452                  "error on SoundConverterBeginConversion = %d", i_error );
453         goto exit_error;
454     }
455
456
457     es_format_Init( &p_dec->fmt_out, AUDIO_ES, AOUT_FMT_S16_NE );
458     p_dec->fmt_out.audio.i_rate = p_sys->OutputFormatInfo.sampleRate;
459     p_dec->fmt_out.audio.i_channels = p_sys->OutputFormatInfo.numChannels;
460     p_dec->fmt_out.audio.i_physical_channels =
461     p_dec->fmt_out.audio.i_original_channels =
462         pi_channels_maps[p_sys->OutputFormatInfo.numChannels];
463
464     aout_DateInit( &p_sys->date, p_dec->fmt_out.audio.i_rate );
465
466     p_sys->i_buffer      = 0;
467     p_sys->i_buffer_size = 100*1000;
468     p_sys->p_buffer      = malloc( p_sys->i_buffer_size );
469
470     p_sys->i_out = 0;
471     p_sys->i_out_frames = 0;
472
473 #ifdef SYS_DARWIN
474     vlc_mutex_unlock( &p_dec->p_vlc->quicktime_lock );
475 #endif
476     vlc_mutex_unlock( lockval.p_address );
477     return VLC_SUCCESS;
478
479 exit_error:
480
481 #ifdef LOADER
482     Restore_LDT_Keeper( p_sys->ldt_fs );
483 #endif
484 #ifdef SYS_DARWIN
485     vlc_mutex_unlock( &p_dec->p_vlc->quicktime_lock );
486 #endif
487     vlc_mutex_unlock( lockval.p_address );
488
489     free( p_sys );
490     return VLC_EGENERIC;
491 }
492
493 /*****************************************************************************
494  * DecodeAudio:
495  *****************************************************************************/
496 static aout_buffer_t *DecodeAudio( decoder_t *p_dec, block_t **pp_block )
497 {
498     decoder_sys_t *p_sys = p_dec->p_sys;
499
500     vlc_value_t lockval;
501     block_t     *p_block;
502     int         i_error;
503
504 #ifdef LOADER
505     /* We must do open and close in the same thread (unless we do
506      * Setup_LDT_Keeper in the main thread before all others */
507     if( p_sys == NULL )
508     {
509         if( OpenAudio( p_dec ) )
510         {
511             /* Fatal */
512             p_dec->b_error = VLC_TRUE;
513             return NULL;
514         }
515
516         p_sys = p_dec->p_sys;
517     }
518 #endif
519
520     if( pp_block == NULL || *pp_block == NULL )
521     {
522         return NULL;
523     }
524     p_block = *pp_block;
525
526     if( p_sys->i_out_frames > 0 && p_sys->i_out >= p_sys->i_out_frames )
527     {
528         /* Ask new data */
529         p_sys->i_out = 0;
530         p_sys->i_out_frames = 0;
531
532         *pp_block = NULL;
533         return NULL;
534     }
535
536     if( p_sys->i_out_frames <= 0 )
537     {
538         if( ( p_sys->pts = p_block->i_pts ) < mdate() )
539         {
540             block_Release( p_block );
541             *pp_block = NULL;
542             return NULL;
543         }
544
545         /* Append data */
546         if( p_sys->i_buffer_size < p_sys->i_buffer + p_block->i_buffer )
547         {
548             p_sys->i_buffer_size = p_sys->i_buffer + p_block->i_buffer + 1024;
549             p_sys->p_buffer = realloc( p_sys->p_buffer, p_sys->i_buffer_size );
550         }
551         memcpy( &p_sys->p_buffer[p_sys->i_buffer], p_block->p_buffer,
552                 p_block->i_buffer );
553         p_sys->i_buffer += p_block->i_buffer;
554
555         if( p_sys->i_buffer > p_sys->InFrameSize )
556         {
557             int i_frames = p_sys->i_buffer / p_sys->InFrameSize;
558             long i_out_frames, i_out_bytes;
559
560             var_Get( p_dec->p_libvlc, "qt_mutex", &lockval );
561             vlc_mutex_lock( lockval.p_address );
562             i_error = p_sys->SoundConverterConvertBuffer( p_sys->myConverter,
563                                                           p_sys->p_buffer,
564                                                           i_frames,
565                                                           p_sys->out_buffer,
566                                                           &i_out_frames,
567                                                           &i_out_bytes );
568             vlc_mutex_unlock( lockval.p_address );
569
570             /*
571             msg_Dbg( p_dec, "decoded %d frames -> %ld frames (error=%d)",
572                      i_frames, i_out_frames, i_error );
573
574             msg_Dbg( p_dec, "decoded %ld frames = %ld bytes",
575                      i_out_frames, i_out_bytes );
576             */
577
578             p_sys->i_buffer -= i_frames * p_sys->InFrameSize;
579             if( p_sys->i_buffer > 0 )
580             {
581                 memmove( &p_sys->p_buffer[0],
582                          &p_sys->p_buffer[i_frames * p_sys->InFrameSize],
583                          p_sys->i_buffer );
584             }
585
586             if( p_sys->pts != 0 &&
587                 p_sys->pts != aout_DateGet( &p_sys->date ) )
588             {
589                 aout_DateSet( &p_sys->date, p_sys->pts );
590             }
591             else if( !aout_DateGet( &p_sys->date ) )
592             {
593                 return NULL;
594             }
595
596             if( !i_error && i_out_frames > 0 )
597             {
598                 /* we have others samples */
599                 p_sys->i_out_frames = i_out_frames;
600                 p_sys->i_out = 0;
601             }
602         }
603     }
604
605     if( p_sys->i_out < p_sys->i_out_frames )
606     {
607         aout_buffer_t *p_out;
608         int  i_frames = __MIN( p_sys->i_out_frames - p_sys->i_out, 1000 );
609
610         p_out = p_dec->pf_aout_buffer_new( p_dec, i_frames );
611
612         if( p_out )
613         {
614             p_out->start_date = aout_DateGet( &p_sys->date );
615             p_out->end_date = aout_DateIncrement( &p_sys->date, i_frames );
616
617             memcpy( p_out->p_buffer,
618                     &p_sys->out_buffer[2 * p_sys->i_out * p_dec->fmt_out.audio.i_channels],
619                     p_out->i_nb_bytes );
620
621             p_sys->i_out += i_frames;
622         }
623         return p_out;
624     }
625
626     return NULL;
627 }
628
629 /*****************************************************************************
630  * OpenVideo:
631  *****************************************************************************/
632 static int OpenVideo( decoder_t *p_dec )
633 {
634     decoder_sys_t *p_sys = malloc( sizeof( decoder_sys_t ) );
635
636 #ifndef WIN32
637     vlc_value_t                         lockval;
638     long                                i_result;
639     ComponentDescription                desc;
640     Component                           prev;
641     ComponentResult                     cres;
642     ImageSubCodecDecompressCapabilities icap;   /* for ImageCodecInitialize() */
643     CodecInfo                           cinfo;  /* for ImageCodecGetCodecInfo() */
644     ImageDescription                    *id;
645
646     char                fcc[4];
647     int     i_vide = p_dec->fmt_in.i_extra;
648     uint8_t *p_vide = p_dec->fmt_in.p_extra;
649
650     p_dec->p_sys = p_sys;
651     p_dec->pf_decode_video = DecodeVideo;
652     p_sys->i_late = 0;
653
654     if( i_vide <= 0 )
655     {
656         msg_Err( p_dec, "missing extra info" );
657         free( p_sys );
658         return VLC_EGENERIC;
659     }
660
661     memcpy( fcc, &p_dec->fmt_in.i_codec, 4 );
662     msg_Dbg( p_dec, "quicktime_video %4.4s %dx%d",
663              fcc, p_dec->fmt_in.video.i_width, p_dec->fmt_in.video.i_height );
664
665     /* get lock, avoid segfault */
666     var_Get( p_dec->p_libvlc, "qt_mutex", &lockval );
667     vlc_mutex_lock( lockval.p_address );
668
669 #ifdef SYS_DARWIN
670     EnterMovies();
671 #endif
672
673     if( QTVideoInit( p_dec ) )
674     {
675         msg_Err( p_dec, "cannot initialize QT");
676         goto exit_error;
677     }
678
679 #ifndef SYS_DARWIN
680     if( ( i_result = p_sys->InitializeQTML( 6 + 16 ) ) )
681     {
682         msg_Dbg( p_dec, "error on InitializeQTML = %d", (int)i_result );
683         goto exit_error;
684     }
685 #endif
686
687     /* init ComponentDescription */
688     memset( &desc, 0, sizeof( ComponentDescription ) );
689     desc.componentType      = FCC( 'i', 'm', 'd', 'c' );
690     desc.componentSubType   = FCC( fcc[0], fcc[1], fcc[2], fcc[3] );
691     desc.componentManufacturer = 0;
692     desc.componentFlags        = 0;
693     desc.componentFlagsMask    = 0;
694
695     if( !( prev = p_sys->FindNextComponent( NULL, &desc ) ) )
696     {
697         msg_Err( p_dec, "cannot find requested component" );
698         goto exit_error;
699     }
700     msg_Dbg( p_dec, "component id=0x%p", prev );
701
702     p_sys->ci =  p_sys->OpenComponent( prev );
703     msg_Dbg( p_dec, "component instance p=0x%p", p_sys->ci );
704
705     memset( &icap, 0, sizeof( ImageSubCodecDecompressCapabilities ) );
706     cres =  p_sys->ImageCodecInitialize( p_sys->ci, &icap );
707 /*    msg_Dbg( p_dec->p_fifo, "ImageCodecInitialize->%p  size=%d (%d)\n",cres,icap.recordSize,icap.decompressRecordSize); */
708
709     memset( &cinfo, 0, sizeof( CodecInfo ) );
710     cres =  p_sys->ImageCodecGetCodecInfo( p_sys->ci, &cinfo );
711     msg_Dbg( p_dec,
712              "Flags: compr: 0x%lx  decomp: 0x%lx format: 0x%lx\n",
713              cinfo.compressFlags, cinfo.decompressFlags, cinfo.formatFlags );
714     msg_Dbg( p_dec, "quicktime_video: Codec name: %.*s\n",
715              ((unsigned char*)&cinfo.typeName)[0],
716              ((unsigned char*)&cinfo.typeName)+1 );
717
718     /* make a yuy2 gworld */
719     p_sys->OutBufferRect.top    = 0;
720     p_sys->OutBufferRect.left   = 0;
721     p_sys->OutBufferRect.right  = p_dec->fmt_in.video.i_width;
722     p_sys->OutBufferRect.bottom = p_dec->fmt_in.video.i_height;
723
724
725     /* codec data FIXME use codec not SVQ3 */
726     msg_Dbg( p_dec, "vide = %d", i_vide  );
727     id = malloc( sizeof( ImageDescription ) + ( i_vide - 70 ) );
728     id->idSize          = sizeof( ImageDescription ) + ( i_vide - 70 );
729     id->cType           = FCC( fcc[0], fcc[1], fcc[2], fcc[3] );
730     id->version         = GetWBE ( p_vide +  0 );
731     id->revisionLevel   = GetWBE ( p_vide +  2 );
732     id->vendor          = GetDWBE( p_vide +  4 );
733     id->temporalQuality = GetDWBE( p_vide +  8 );
734     id->spatialQuality  = GetDWBE( p_vide + 12 );
735     id->width           = GetWBE ( p_vide + 16 );
736     id->height          = GetWBE ( p_vide + 18 );
737     id->hRes            = GetDWBE( p_vide + 20 );
738     id->vRes            = GetDWBE( p_vide + 24 );
739     id->dataSize        = GetDWBE( p_vide + 28 );
740     id->frameCount      = GetWBE ( p_vide + 32 );
741     memcpy( &id->name, p_vide + 34, 32 );
742     id->depth           = GetWBE ( p_vide + 66 );
743     id->clutID          = GetWBE ( p_vide + 68 );
744     if( i_vide > 70 )
745     {
746         memcpy( ((char*)&id->clutID) + 2, p_vide + 70, i_vide - 70 );
747     }
748
749     msg_Dbg( p_dec, "idSize=%ld ver=%d rev=%d vendor=%ld tempQ=%d "
750              "spaQ=%d w=%d h=%d dpi=%d%d dataSize=%d frameCount=%d clutID=%d",
751              id->idSize, id->version, id->revisionLevel, id->vendor,
752              (int)id->temporalQuality, (int)id->spatialQuality,
753              id->width, id->height,
754              (int)id->hRes, (int)id->vRes,
755              (int)id->dataSize,
756              id->frameCount,
757              id->clutID );
758
759     p_sys->framedescHandle =
760         (ImageDescriptionHandle) p_sys->NewHandleClear( id->idSize );
761     memcpy( *p_sys->framedescHandle, id, id->idSize );
762
763     p_sys->plane = malloc( p_dec->fmt_in.video.i_width * p_dec->fmt_in.video.i_height * 3 );
764
765     i_result = p_sys->QTNewGWorldFromPtr( &p_sys->OutBufferGWorld,
766                                           /*pixel format of new GWorld==YUY2 */
767                                           kYUVSPixelFormat,
768                                           /* we should benchmark if yvu9 is
769                                            * faster for svq3, too */
770                                           &p_sys->OutBufferRect,
771                                           0, 0, 0,
772                                           p_sys->plane,
773                                           p_dec->fmt_in.video.i_width * 2 );
774
775     msg_Dbg( p_dec, "NewGWorldFromPtr returned:%ld\n",
776              65536 - ( i_result&0xffff ) );
777
778     memset( &p_sys->decpar, 0, sizeof( CodecDecompressParams ) );
779     p_sys->decpar.imageDescription = p_sys->framedescHandle;
780     p_sys->decpar.startLine        = 0;
781     p_sys->decpar.stopLine         = ( **p_sys->framedescHandle ).height;
782     p_sys->decpar.frameNumber      = 1;
783     p_sys->decpar.matrixFlags      = 0;
784     p_sys->decpar.matrixType       = 0;
785     p_sys->decpar.matrix           = 0;
786     p_sys->decpar.capabilities     = &p_sys->codeccap;
787     p_sys->decpar.accuracy         = codecNormalQuality;
788     p_sys->decpar.srcRect          = p_sys->OutBufferRect;
789     p_sys->decpar.transferMode     = srcCopy;
790     p_sys->decpar.dstPixMap        = **p_sys->GetGWorldPixMap( p_sys->OutBufferGWorld );/*destPixmap;  */
791
792     cres =  p_sys->ImageCodecPreDecompress( p_sys->ci, &p_sys->decpar );
793     msg_Dbg( p_dec, "quicktime_video: ImageCodecPreDecompress cres=0x%X\n",
794              (int)cres );
795
796     p_dec->fmt_out.i_codec = VLC_FOURCC( 'Y', 'U', 'Y', '2' );
797     p_dec->fmt_out.video.i_width = p_dec->fmt_in.video.i_width;
798     p_dec->fmt_out.video.i_height= p_dec->fmt_in.video.i_height;
799     p_dec->fmt_out.video.i_aspect = VOUT_ASPECT_FACTOR * p_dec->fmt_in.video.i_width / p_dec->fmt_in.video.i_height;
800
801
802     vlc_mutex_unlock( lockval.p_address );
803     return VLC_SUCCESS;
804
805 exit_error:
806 #ifdef LOADER
807     Restore_LDT_Keeper( p_sys->ldt_fs );
808 #endif
809     vlc_mutex_unlock( lockval.p_address );
810
811 #endif /* !WIN32 */
812
813     return VLC_EGENERIC;
814 }
815
816 #ifndef WIN32
817 /*****************************************************************************
818  * DecodeVideo:
819  *****************************************************************************/
820 static picture_t *DecodeVideo( decoder_t *p_dec, block_t **pp_block )
821 {
822     decoder_sys_t *p_sys = p_dec->p_sys;
823     block_t       *p_block;
824     picture_t     *p_pic;
825     mtime_t       i_pts;
826
827     ComponentResult cres;
828
829 #ifdef LOADER
830     /* We must do open and close in the same thread (unless we do
831      * Setup_LDT_Keeper in the main thread before all others */
832     if( p_sys == NULL )
833     {
834         if( OpenVideo( p_dec ) )
835         {
836             /* Fatal */
837             p_dec->b_error = VLC_TRUE;
838             return NULL;
839         }
840         p_sys = p_dec->p_sys;
841     }
842 #endif
843
844     if( pp_block == NULL || *pp_block == NULL )
845     {
846         return NULL;
847     }
848     p_block = *pp_block;
849     *pp_block = NULL;
850
851     i_pts = p_block->i_pts ? p_block->i_pts : p_block->i_dts;
852
853     if( i_pts < mdate() )
854     {
855         p_sys->i_late++;
856     }
857     else
858     {
859         p_sys->i_late = 0;
860     }
861
862     if( p_sys->i_late > 10 )
863     {
864         msg_Dbg( p_dec, "too late buffer -> dropped" );
865         block_Release( p_block );
866         return NULL;
867     }
868
869     if( ( p_pic = p_dec->pf_vout_buffer_new( p_dec ) ) )
870     {
871         vlc_value_t     lockval;
872
873         p_sys->decpar.data                  = p_block->p_buffer;
874         p_sys->decpar.bufferSize            = p_block->i_buffer;
875         (**p_sys->framedescHandle).dataSize = p_block->i_buffer;
876
877         var_Get( p_dec->p_libvlc, "qt_mutex", &lockval );
878         vlc_mutex_lock( lockval.p_address );
879         cres = p_sys->ImageCodecBandDecompress( p_sys->ci, &p_sys->decpar );
880         vlc_mutex_unlock( lockval.p_address );
881
882         ++p_sys->decpar.frameNumber;
883
884         if( cres &0xFFFF )
885         {
886             msg_Dbg( p_dec, "quicktime_video: ImageCodecBandDecompress"
887                      " cres=0x%X (-0x%X) %d :(\n",
888                      (int)cres,(int)-cres, (int)cres );
889         }
890
891         memcpy( p_pic->p[0].p_pixels, p_sys->plane,
892                 p_dec->fmt_in.video.i_width * p_dec->fmt_in.video.i_height * 2 );
893         p_pic->date = i_pts;
894     }
895     block_Release( p_block );
896
897     return p_pic;
898 }
899 #endif /* !WIN32 */
900
901 /*****************************************************************************
902  * QTAudioInit:
903  *****************************************************************************/
904 static int QTAudioInit( decoder_t *p_dec )
905 {
906     decoder_sys_t *p_sys = p_dec->p_sys;
907
908 #ifdef SYS_DARWIN
909     p_sys->SoundConverterOpen       = (void*)SoundConverterOpen;
910     p_sys->SoundConverterClose      = (void*)SoundConverterClose;
911     p_sys->SoundConverterSetInfo    = (void*)SoundConverterSetInfo;
912     p_sys->SoundConverterGetBufferSizes = (void*)SoundConverterGetBufferSizes;
913     p_sys->SoundConverterConvertBuffer  = (void*)SoundConverterConvertBuffer;
914     p_sys->SoundConverterBeginConversion= (void*)SoundConverterBeginConversion;
915     p_sys->SoundConverterEndConversion  = (void*)SoundConverterEndConversion;
916 #else
917
918 #ifdef LOADER
919     p_sys->ldt_fs = Setup_LDT_Keeper();
920 #endif /* LOADER */
921
922     p_sys->qtml = LoadLibraryA( "qtmlClient.dll" );
923     if( p_sys->qtml == NULL )
924     {
925         msg_Dbg( p_dec, "failed loading qtmlClient.dll" );
926         return VLC_EGENERIC;
927     }
928
929     p_sys->InitializeQTML               = (void *)GetProcAddress( p_sys->qtml, "InitializeQTML" );
930     p_sys->TerminateQTML                = (void *)GetProcAddress( p_sys->qtml, "TerminateQTML" );
931     p_sys->SoundConverterOpen           = (void *)GetProcAddress( p_sys->qtml, "SoundConverterOpen" );
932     p_sys->SoundConverterClose          = (void *)GetProcAddress( p_sys->qtml, "SoundConverterClose" );
933     p_sys->SoundConverterSetInfo        = (void *)GetProcAddress( p_sys->qtml, "SoundConverterSetInfo" );
934     p_sys->SoundConverterGetBufferSizes = (void *)GetProcAddress( p_sys->qtml, "SoundConverterGetBufferSizes" );
935     p_sys->SoundConverterConvertBuffer  = (void *)GetProcAddress( p_sys->qtml, "SoundConverterConvertBuffer" );
936     p_sys->SoundConverterEndConversion  = (void *)GetProcAddress( p_sys->qtml, "SoundConverterEndConversion" );
937     p_sys->SoundConverterBeginConversion= (void *)GetProcAddress( p_sys->qtml, "SoundConverterBeginConversion");
938
939     if( p_sys->InitializeQTML == NULL )
940     {
941         msg_Err( p_dec, "failed getting proc address InitializeQTML" );
942         return VLC_EGENERIC;
943     }
944     if( p_sys->SoundConverterOpen == NULL ||
945         p_sys->SoundConverterClose == NULL ||
946         p_sys->SoundConverterSetInfo == NULL ||
947         p_sys->SoundConverterGetBufferSizes == NULL ||
948         p_sys->SoundConverterConvertBuffer == NULL ||
949         p_sys->SoundConverterEndConversion == NULL ||
950         p_sys->SoundConverterBeginConversion == NULL )
951     {
952         msg_Err( p_dec, "failed getting proc address" );
953         return VLC_EGENERIC;
954     }
955
956     msg_Dbg( p_dec, "Standard init done" );
957 #endif /* else SYS_DARWIN */
958
959     return VLC_SUCCESS;
960 }
961
962 #ifndef WIN32
963 /*****************************************************************************
964  * QTVideoInit:
965  *****************************************************************************/
966 static int QTVideoInit( decoder_t *p_dec )
967 {
968     decoder_sys_t *p_sys = p_dec->p_sys;
969
970 #ifdef SYS_DARWIN
971     p_sys->FindNextComponent        = (void*)FindNextComponent;
972     p_sys->OpenComponent            = (void*)OpenComponent;
973     p_sys->ImageCodecInitialize     = (void*)ImageCodecInitialize;
974     p_sys->ImageCodecGetCodecInfo   = (void*)ImageCodecGetCodecInfo;
975     p_sys->ImageCodecPreDecompress  = (void*)ImageCodecPreDecompress;
976     p_sys->ImageCodecBandDecompress = (void*)ImageCodecBandDecompress;
977     p_sys->GetGWorldPixMap          = (void*)GetGWorldPixMap;
978     p_sys->QTNewGWorldFromPtr       = (void*)QTNewGWorldFromPtr;
979     p_sys->NewHandleClear           = (void*)NewHandleClear;
980 #else
981
982 #ifdef LOADER
983     p_sys->ldt_fs = Setup_LDT_Keeper();
984 #endif /* LOADER */
985     p_sys->qtml = LoadLibraryA( "qtmlClient.dll" );
986     if( p_sys->qtml == NULL )
987     {
988         msg_Dbg( p_dec, "failed loading qtmlClient.dll" );
989         return VLC_EGENERIC;
990     }
991     msg_Dbg( p_dec, "qtmlClient.dll loaded" );
992
993     /* (void*) to shut up gcc */
994     p_sys->InitializeQTML           = (void*)GetProcAddress( p_sys->qtml, "InitializeQTML" );
995     p_sys->FindNextComponent        = (void*)GetProcAddress( p_sys->qtml, "FindNextComponent" );
996     p_sys->OpenComponent            = (void*)GetProcAddress( p_sys->qtml, "OpenComponent" );
997     p_sys->ImageCodecInitialize     = (void*)GetProcAddress( p_sys->qtml, "ImageCodecInitialize" );
998     p_sys->ImageCodecGetCodecInfo   = (void*)GetProcAddress( p_sys->qtml, "ImageCodecGetCodecInfo" );
999     p_sys->ImageCodecPreDecompress  = (void*)GetProcAddress( p_sys->qtml, "ImageCodecPreDecompress" );
1000     p_sys->ImageCodecBandDecompress = (void*)GetProcAddress( p_sys->qtml, "ImageCodecBandDecompress" );
1001     p_sys->GetGWorldPixMap          = (void*)GetProcAddress( p_sys->qtml, "GetGWorldPixMap" );
1002     p_sys->QTNewGWorldFromPtr       = (void*)GetProcAddress( p_sys->qtml, "QTNewGWorldFromPtr" );
1003     p_sys->NewHandleClear           = (void*)GetProcAddress( p_sys->qtml, "NewHandleClear" );
1004
1005     if( p_sys->InitializeQTML == NULL )
1006     {
1007         msg_Dbg( p_dec, "failed getting proc address InitializeQTML" );
1008         return VLC_EGENERIC;
1009     }
1010     if( p_sys->FindNextComponent == NULL ||
1011         p_sys->OpenComponent == NULL ||
1012         p_sys->ImageCodecInitialize == NULL ||
1013         p_sys->ImageCodecGetCodecInfo == NULL ||
1014         p_sys->ImageCodecPreDecompress == NULL ||
1015         p_sys->ImageCodecBandDecompress == NULL ||
1016         p_sys->GetGWorldPixMap == NULL ||
1017         p_sys->QTNewGWorldFromPtr == NULL ||
1018         p_sys->NewHandleClear == NULL )
1019     {
1020         msg_Err( p_dec, "failed getting proc address" );
1021         return VLC_EGENERIC;
1022     }
1023 #endif /* SYS_DARWIN */
1024
1025     return VLC_SUCCESS;
1026 }
1027 #endif /* !WIN32 */