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