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