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