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