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