]> git.sesse.net Git - vlc/blob - modules/codec/dmo/dmo.c
For consistency, remove references to vlc from libvlc
[vlc] / modules / codec / dmo / dmo.c
1 /*****************************************************************************
2  * dmo.c : DirectMedia Object decoder module for vlc
3  *****************************************************************************
4  * Copyright (C) 2002, 2003 the VideoLAN team
5  * $Id$
6  *
7  * Author: Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <string.h>
30
31 #include <vlc/vlc.h>
32 #include <vlc/decoder.h>
33 #include <vlc/vout.h>
34
35 #ifndef WIN32
36 #    define LOADER
37 #else
38 #   include <objbase.h>
39 #endif
40
41 #ifdef LOADER
42 /* Need the w32dll loader from mplayer */
43 #   include <wine/winerror.h>
44 #   include <ldt_keeper.h>
45 #   include <wine/windef.h>
46 #endif
47
48 #include "codecs.h"
49 #include "dmo.h"
50
51 //#define DMO_DEBUG 1
52
53 #ifdef LOADER
54 /* Not Needed */
55 long CoInitialize( void *pvReserved ) { return -1; }
56 void CoUninitialize( void ) { }
57
58 /* A few prototypes */
59 HMODULE WINAPI LoadLibraryA(LPCSTR);
60 #define LoadLibrary LoadLibraryA
61 FARPROC WINAPI GetProcAddress(HMODULE,LPCSTR);
62 int     WINAPI FreeLibrary(HMODULE);
63 #endif /* LOADER */
64
65 typedef long (STDCALL *GETCLASS) ( const GUID*, const GUID*, void** );
66
67 static int pi_channels_maps[7] =
68 {
69     0,
70     AOUT_CHAN_CENTER,
71     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
72     AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
73     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
74      | AOUT_CHAN_REARRIGHT,
75     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
76      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT,
77     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
78      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE
79 };
80
81 /*****************************************************************************
82  * Module descriptor
83  *****************************************************************************/
84 static int  DecoderOpen  ( vlc_object_t * );
85 static int  DecOpen      ( vlc_object_t * );
86 static void DecoderClose ( vlc_object_t * );
87 static void *DecodeBlock ( decoder_t *, block_t ** );
88
89 static int  EncoderOpen  ( vlc_object_t * );
90 static int  EncOpen      ( vlc_object_t * );
91 static void EncoderClose ( vlc_object_t * );
92 static block_t *EncodeBlock( encoder_t *, void * );
93
94 static int LoadDMO( vlc_object_t *, HINSTANCE *, IMediaObject **,
95                     es_format_t *, vlc_bool_t );
96 static void CopyPicture( decoder_t *, picture_t *, uint8_t * );
97
98 vlc_module_begin();
99     set_description( _("DirectMedia Object decoder") );
100     add_shortcut( "dmo" );
101     set_capability( "decoder", 1 );
102     set_callbacks( DecoderOpen, DecoderClose );
103     set_category( CAT_INPUT );
104     set_subcategory( SUBCAT_INPUT_SCODEC );
105
106 #   define ENC_CFG_PREFIX "sout-dmo-"
107     add_submodule();
108     set_description( _("DirectMedia Object encoder") );
109     set_capability( "encoder", 10 );
110     set_callbacks( EncoderOpen, EncoderClose );
111
112 vlc_module_end();
113
114 /*****************************************************************************
115  * Local prototypes
116  *****************************************************************************/
117
118 /****************************************************************************
119  * Decoder descriptor declaration
120  ****************************************************************************/
121 struct decoder_sys_t
122 {
123     HINSTANCE hmsdmo_dll;
124     IMediaObject *p_dmo;
125
126     int i_min_output;
127     uint8_t *p_buffer;
128
129     date_t end_date;
130
131 #ifdef LOADER
132     ldt_fs_t    *ldt_fs;
133 #endif
134 };
135
136 static const GUID guid_wvc1 = { 0xc9bfbccf, 0xe60e, 0x4588, { 0xa3, 0xdf, 0x5a, 0x03, 0xb1, 0xfd, 0x95, 0x85 } };
137
138 static const GUID guid_wmv9 = { 0x724bb6a4, 0xe526, 0x450f, { 0xaf, 0xfa, 0xab, 0x9b, 0x45, 0x12, 0x91, 0x11 } };
139 static const GUID guid_wma9 = { 0x27ca0808, 0x01f5, 0x4e7a, { 0x8b, 0x05, 0x87, 0xf8, 0x07, 0xa2, 0x33, 0xd1 } };
140
141 static const GUID guid_wmv = { 0x82d353df, 0x90bd, 0x4382, { 0x8b, 0xc2, 0x3f, 0x61, 0x92, 0xb7, 0x6e, 0x34 } };
142 static const GUID guid_wma = { 0x874131cb, 0x4ecc, 0x443b, { 0x89, 0x48, 0x74, 0x6b, 0x89, 0x59, 0x5d, 0x20 } };
143
144 static const GUID guid_wmv_enc = { 0x3181343b, 0x94a2, 0x4feb, { 0xad, 0xef, 0x30, 0xa1, 0xdd, 0xe6, 0x17, 0xb4 } };
145 static const GUID guid_wma_enc = { 0x70f598e9, 0xf4ab, 0x495a, { 0x99, 0xe2, 0xa7, 0xc4, 0xd3, 0xd8, 0x9a, 0xbf } };
146
147 typedef struct
148 {
149     vlc_fourcc_t i_fourcc;
150     const char   *psz_dll;
151     const GUID   *p_guid;
152
153 } codec_dll;
154
155 static const codec_dll decoders_table[] =
156 {
157     /* WVC1 */
158     { VLC_FOURCC('W','V','C','1'), "wvc1dmod.dll", &guid_wvc1 },
159     { VLC_FOURCC('w','v','c','1'), "wvc1dmod.dll", &guid_wvc1 },
160     /* WMV3 */
161     { VLC_FOURCC('W','M','V','3'), "wmv9dmod.dll", &guid_wmv9 },
162     { VLC_FOURCC('w','m','v','3'), "wmv9dmod.dll", &guid_wmv9 },
163     /* WMV2 */
164     { VLC_FOURCC('W','M','V','2'), "wmvdmod.dll", &guid_wmv },
165     { VLC_FOURCC('w','m','v','2'), "wmvdmod.dll", &guid_wmv },
166     /* WMV1 */
167     { VLC_FOURCC('W','M','V','1'), "wmvdmod.dll", &guid_wmv },
168     { VLC_FOURCC('w','m','v','1'), "wmvdmod.dll", &guid_wmv },
169
170     /* WMA 3 */
171     { VLC_FOURCC('W','M','A','3'), "wma9dmod.dll", &guid_wma9 },
172     { VLC_FOURCC('w','m','a','3'), "wma9dmod.dll", &guid_wma9 },
173     { VLC_FOURCC('w','m','a','p'), "wma9dmod.dll", &guid_wma9 },
174     /* WMA 2 */
175     { VLC_FOURCC('W','M','A','2'), "wma9dmod.dll", &guid_wma9 },
176     { VLC_FOURCC('w','m','a','2'), "wma9dmod.dll", &guid_wma9 },
177
178     /* WMA Speech */
179     { VLC_FOURCC('w','m','a','s'), "wmspdmod.dll", &guid_wma },
180
181     /* */
182     { 0, NULL, NULL }
183 };
184
185 static const codec_dll encoders_table[] =
186 {
187     /* WMV2 */
188     { VLC_FOURCC('W','M','V','2'), "wmvdmoe.dll", &guid_wmv_enc },
189     { VLC_FOURCC('w','m','v','2'), "wmvdmoe.dll", &guid_wmv_enc },
190     /* WMV1 */
191     { VLC_FOURCC('W','M','V','1'), "wmvdmoe.dll", &guid_wmv_enc },
192     { VLC_FOURCC('w','m','v','1'), "wmvdmoe.dll", &guid_wmv_enc },
193
194     /* WMA 3 */
195     { VLC_FOURCC('W','M','A','3'), "wmadmoe.dll", &guid_wma_enc },
196     { VLC_FOURCC('w','m','a','3'), "wmadmoe.dll", &guid_wma_enc },
197     /* WMA 2 */
198     { VLC_FOURCC('W','M','A','2'), "wmadmoe.dll", &guid_wma_enc },
199     { VLC_FOURCC('w','m','a','2'), "wmadmoe.dll", &guid_wma_enc },
200
201     /* */
202     { 0, NULL, NULL }
203 };
204
205 static void WINAPI DMOFreeMediaType( DMO_MEDIA_TYPE *mt )
206 {
207     if( mt->cbFormat != 0 ) CoTaskMemFree( (PVOID)mt->pbFormat );
208     if( mt->pUnk != NULL ) mt->pUnk->vt->Release( (IUnknown *)mt->pUnk );
209     mt->cbFormat = 0;
210     mt->pbFormat = NULL;
211     mt->pUnk = NULL;
212 }
213
214 /*****************************************************************************
215  * DecoderOpen: open dmo codec
216  *****************************************************************************/
217 static int DecoderOpen( vlc_object_t *p_this )
218 {
219     decoder_t *p_dec = (decoder_t*)p_this;
220
221 #ifndef LOADER
222     int i_ret = DecOpen( p_this );
223     if( i_ret != VLC_SUCCESS ) return i_ret;
224
225
226 #else
227     /* We can't open it now, because of ldt_keeper or something
228      * Open/Decode/Close has to be done in the same thread */
229     int i;
230
231     p_dec->p_sys = NULL;
232
233     /* Probe if we support it */
234     for( i = 0; decoders_table[i].i_fourcc != 0; i++ )
235     {
236         if( decoders_table[i].i_fourcc == p_dec->fmt_in.i_codec )
237         {
238             msg_Dbg( p_dec, "DMO codec for %4.4s may work with dll=%s",
239                      (char*)&p_dec->fmt_in.i_codec,
240                      decoders_table[i].psz_dll );
241             break;
242         }
243     }
244
245     p_dec->p_sys = NULL;
246     if( !decoders_table[i].i_fourcc ) return VLC_EGENERIC;
247 #endif /* LOADER */
248
249     /* Set callbacks */
250     p_dec->pf_decode_video = (picture_t *(*)(decoder_t *, block_t **))
251         DecodeBlock;
252     p_dec->pf_decode_audio = (aout_buffer_t *(*)(decoder_t *, block_t **))
253         DecodeBlock;
254
255     return VLC_SUCCESS;
256 }
257
258 /*****************************************************************************
259  * DecOpen: open dmo codec
260  *****************************************************************************/
261 static int DecOpen( vlc_object_t *p_this )
262 {
263     decoder_t *p_dec = (decoder_t*)p_this;
264     decoder_sys_t *p_sys = NULL;
265
266     DMO_MEDIA_TYPE dmo_input_type, dmo_output_type;
267     IMediaObject *p_dmo = NULL;
268     HINSTANCE hmsdmo_dll = NULL;
269
270     VIDEOINFOHEADER *p_vih = NULL;
271     WAVEFORMATEX *p_wf = NULL;
272
273 #ifdef LOADER
274     ldt_fs_t *ldt_fs = Setup_LDT_Keeper();
275 #else
276     /* Initialize OLE/COM */
277     CoInitialize( 0 );
278 #endif /* LOADER */
279
280     if( LoadDMO( p_this, &hmsdmo_dll, &p_dmo, &p_dec->fmt_in, VLC_FALSE )
281         != VLC_SUCCESS )
282     {
283         hmsdmo_dll = 0;
284         p_dmo = 0;
285         goto error;
286     }
287
288     /* Setup input format */
289     memset( &dmo_input_type, 0, sizeof(dmo_input_type) );
290     dmo_input_type.pUnk = 0;
291
292     if( p_dec->fmt_in.i_cat == AUDIO_ES )
293     {
294         uint16_t i_tag;
295         int i_size = sizeof(WAVEFORMATEX) + p_dec->fmt_in.i_extra;
296         p_wf = malloc( i_size );
297
298         memset( p_wf, 0, sizeof(WAVEFORMATEX) );
299         if( p_dec->fmt_in.i_extra )
300             memcpy( &p_wf[1], p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra );
301
302         dmo_input_type.majortype  = MEDIATYPE_Audio;
303         dmo_input_type.subtype    = dmo_input_type.majortype;
304         dmo_input_type.subtype.Data1 = p_dec->fmt_in.i_codec;
305         fourcc_to_wf_tag( p_dec->fmt_in.i_codec, &i_tag );
306         if( i_tag ) dmo_input_type.subtype.Data1 = i_tag;
307
308         p_wf->wFormatTag = dmo_input_type.subtype.Data1;
309         p_wf->nSamplesPerSec = p_dec->fmt_in.audio.i_rate;
310         p_wf->nChannels = p_dec->fmt_in.audio.i_channels;
311         p_wf->wBitsPerSample = p_dec->fmt_in.audio.i_bitspersample;
312         p_wf->nBlockAlign = p_dec->fmt_in.audio.i_blockalign;
313         p_wf->nAvgBytesPerSec = p_dec->fmt_in.i_bitrate / 8;
314         p_wf->cbSize = p_dec->fmt_in.i_extra;
315
316         dmo_input_type.formattype = FORMAT_WaveFormatEx;
317         dmo_input_type.cbFormat   = i_size;
318         dmo_input_type.pbFormat   = (char *)p_wf;
319         dmo_input_type.bFixedSizeSamples = 1;
320         dmo_input_type.bTemporalCompression = 0;
321         dmo_input_type.lSampleSize = p_wf->nBlockAlign;
322     }
323     else
324     {
325         BITMAPINFOHEADER *p_bih;
326
327         int i_size = sizeof(VIDEOINFOHEADER) + p_dec->fmt_in.i_extra;
328         p_vih = malloc( i_size );
329
330         memset( p_vih, 0, sizeof(VIDEOINFOHEADER) );
331         if( p_dec->fmt_in.i_extra )
332             memcpy( &p_vih[1], p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra );
333
334         p_bih = &p_vih->bmiHeader;
335         p_bih->biCompression = p_dec->fmt_in.i_codec;
336         p_bih->biWidth = p_dec->fmt_in.video.i_width;
337         p_bih->biHeight = p_dec->fmt_in.video.i_height;
338         p_bih->biBitCount = p_dec->fmt_in.video.i_bits_per_pixel;
339         p_bih->biPlanes = 1;
340         p_bih->biSize = i_size - sizeof(VIDEOINFOHEADER) +
341             sizeof(BITMAPINFOHEADER);
342
343         p_vih->rcSource.left = p_vih->rcSource.top = 0;
344         p_vih->rcSource.right = p_dec->fmt_in.video.i_width;
345         p_vih->rcSource.bottom = p_dec->fmt_in.video.i_height;
346         p_vih->rcTarget = p_vih->rcSource;
347
348         dmo_input_type.majortype  = MEDIATYPE_Video;
349         dmo_input_type.subtype    = dmo_input_type.majortype;
350         dmo_input_type.subtype.Data1 = p_dec->fmt_in.i_codec;
351         dmo_input_type.formattype = FORMAT_VideoInfo;
352         dmo_input_type.bFixedSizeSamples = 0;
353         dmo_input_type.bTemporalCompression = 1;
354         dmo_input_type.cbFormat = i_size;
355         dmo_input_type.pbFormat = (char *)p_vih;
356     }
357
358     if( p_dmo->vt->SetInputType( p_dmo, 0, &dmo_input_type, 0 ) )
359     {
360         msg_Err( p_dec, "can't set DMO input type" );
361         goto error;
362     }
363     msg_Dbg( p_dec, "DMO input type set" );
364
365     /* Setup output format */
366     memset( &dmo_output_type, 0, sizeof(dmo_output_type) );
367     dmo_output_type.pUnk = 0;
368
369     if( p_dec->fmt_in.i_cat == AUDIO_ES )
370     {
371         /* Setup the format */
372         p_dec->fmt_out.i_codec = AOUT_FMT_S16_NE;
373         p_dec->fmt_out.audio.i_rate     = p_dec->fmt_in.audio.i_rate;
374         p_dec->fmt_out.audio.i_channels = p_dec->fmt_in.audio.i_channels;
375         p_dec->fmt_out.audio.i_bitspersample = 16;//p_dec->fmt_in.audio.i_bitspersample; We request 16
376         p_dec->fmt_out.audio.i_physical_channels =
377             p_dec->fmt_out.audio.i_original_channels =
378                 pi_channels_maps[p_dec->fmt_out.audio.i_channels];
379
380         p_wf->wFormatTag = WAVE_FORMAT_PCM;
381         p_wf->nSamplesPerSec = p_dec->fmt_out.audio.i_rate;
382         p_wf->nChannels = p_dec->fmt_out.audio.i_channels;
383         p_wf->wBitsPerSample = p_dec->fmt_out.audio.i_bitspersample;
384         p_wf->nBlockAlign =
385             p_wf->wBitsPerSample / 8 * p_wf->nChannels;
386         p_wf->nAvgBytesPerSec =
387             p_wf->nSamplesPerSec * p_wf->nBlockAlign;
388         p_wf->cbSize = 0;
389
390         dmo_output_type.majortype  = MEDIATYPE_Audio;
391         dmo_output_type.formattype = FORMAT_WaveFormatEx;
392         dmo_output_type.subtype    = MEDIASUBTYPE_PCM;
393         dmo_output_type.cbFormat   = sizeof(WAVEFORMATEX);
394         dmo_output_type.pbFormat   = (char *)p_wf;
395         dmo_output_type.bFixedSizeSamples = 1;
396         dmo_output_type.bTemporalCompression = 0;
397         dmo_output_type.lSampleSize = p_wf->nBlockAlign;
398     }
399     else
400     {
401         BITMAPINFOHEADER *p_bih;
402         DMO_MEDIA_TYPE mt;
403         unsigned i_chroma = VLC_FOURCC('Y','U','Y','2');
404         int i_planes = 1, i_bpp = 16;
405         int i = 0;
406
407         /* Find out which chroma to use */
408         while( !p_dmo->vt->GetOutputType( p_dmo, 0, i++, &mt ) )
409         {
410             if( mt.subtype.Data1 == VLC_FOURCC('Y','V','1','2') )
411             {
412                 i_chroma = mt.subtype.Data1;
413                 i_planes = 3; i_bpp = 12;
414             }
415
416             DMOFreeMediaType( &mt );
417         }
418
419         p_dec->fmt_out.i_codec = i_chroma == VLC_FOURCC('Y','V','1','2') ?
420             VLC_FOURCC('I','4','2','0') : i_chroma;
421         p_dec->fmt_out.video.i_width = p_dec->fmt_in.video.i_width;
422         p_dec->fmt_out.video.i_height = p_dec->fmt_in.video.i_height;
423         p_dec->fmt_out.video.i_bits_per_pixel = i_bpp;
424
425         /* If an aspect-ratio was specified in the input format then force it */
426         if( p_dec->fmt_in.video.i_aspect )
427         {
428             p_dec->fmt_out.video.i_aspect = p_dec->fmt_in.video.i_aspect;
429         }
430         else
431         {
432             p_dec->fmt_out.video.i_aspect = VOUT_ASPECT_FACTOR *
433                 p_dec->fmt_out.video.i_width / p_dec->fmt_out.video.i_height;
434         }
435
436         p_bih = &p_vih->bmiHeader;
437         p_bih->biCompression = i_chroma;
438         p_bih->biHeight *= -1;
439         p_bih->biBitCount = p_dec->fmt_out.video.i_bits_per_pixel;
440         p_bih->biSizeImage = p_dec->fmt_in.video.i_width *
441             p_dec->fmt_in.video.i_height *
442             (p_dec->fmt_in.video.i_bits_per_pixel + 7) / 8;
443
444         p_bih->biPlanes = i_planes;
445         p_bih->biSize = sizeof(BITMAPINFOHEADER);
446
447         dmo_output_type.majortype = MEDIATYPE_Video;
448         dmo_output_type.formattype = FORMAT_VideoInfo;
449         dmo_output_type.subtype = dmo_output_type.majortype;
450         dmo_output_type.subtype.Data1 = p_bih->biCompression;
451         dmo_output_type.bFixedSizeSamples = VLC_TRUE;
452         dmo_output_type.bTemporalCompression = 0;
453         dmo_output_type.lSampleSize = p_bih->biSizeImage;
454         dmo_output_type.cbFormat = sizeof(VIDEOINFOHEADER);
455         dmo_output_type.pbFormat = (char *)p_vih;
456     }
457
458 #ifdef DMO_DEBUG
459     /* Enumerate output types */
460     if( p_dec->fmt_in.i_cat == VIDEO_ES )
461     {
462         int i = 0;
463         DMO_MEDIA_TYPE mt;
464
465         while( !p_dmo->vt->GetOutputType( p_dmo, 0, i++, &mt ) )
466         {
467             msg_Dbg( p_dec, "available output chroma: %4.4s",
468                      (char *)&mt.subtype.Data1 );
469             DMOFreeMediaType( &mt );
470         }
471     }
472 #endif
473
474     if( p_dmo->vt->SetOutputType( p_dmo, 0, &dmo_output_type, 0 ) )
475     {
476         msg_Err( p_dec, "can't set DMO output type" );
477         goto error;
478     }
479     msg_Dbg( p_dec, "DMO output type set" );
480
481     /* Allocate the memory needed to store the decoder's structure */
482     if( ( p_dec->p_sys = p_sys =
483           (decoder_sys_t *)malloc(sizeof(decoder_sys_t)) ) == NULL )
484     {
485         msg_Err( p_dec, "out of memory" );
486         goto error;
487     }
488
489     p_sys->hmsdmo_dll = hmsdmo_dll;
490     p_sys->p_dmo = p_dmo;
491 #ifdef LOADER
492     p_sys->ldt_fs = ldt_fs;
493 #endif
494
495     /* Find out some properties of the output */
496     {
497         uint32_t i_size, i_align;
498
499         p_sys->i_min_output = 0;
500         if( p_dmo->vt->GetOutputSizeInfo( p_dmo, 0, &i_size, &i_align ) )
501         {
502             msg_Err( p_dec, "GetOutputSizeInfo() failed" );
503             goto error;
504         }
505         else
506         {
507             msg_Dbg( p_dec, "GetOutputSizeInfo(): bytes %i, align %i",
508                      i_size, i_align );
509             p_sys->i_min_output = i_size;
510             p_sys->p_buffer = malloc( i_size );
511             if( !p_sys->p_buffer ) goto error;
512         }
513     }
514
515     /* Set output properties */
516     p_dec->fmt_out.i_cat = p_dec->fmt_in.i_cat;
517     if( p_dec->fmt_out.i_cat == AUDIO_ES )
518         date_Init( &p_sys->end_date, p_dec->fmt_in.audio.i_rate, 1 );
519     else
520         date_Init( &p_sys->end_date, 25 /* FIXME */, 1 );
521
522     if( p_vih ) free( p_vih );
523     if( p_wf ) free( p_wf );
524
525     return VLC_SUCCESS;
526
527  error:
528
529     if( p_dmo ) p_dmo->vt->Release( (IUnknown *)p_dmo );
530     if( hmsdmo_dll ) FreeLibrary( hmsdmo_dll );
531
532 #ifdef LOADER
533     Restore_LDT_Keeper( ldt_fs );
534 #else
535     /* Uninitialize OLE/COM */
536     CoUninitialize();
537 #endif /* LOADER */
538
539     if( p_vih ) free( p_vih );
540     if( p_wf )  free( p_wf );
541     if( p_sys ) free( p_sys );
542
543     return VLC_EGENERIC;
544 }
545
546 /*****************************************************************************
547  * LoadDMO: Load the DMO object
548  *****************************************************************************/
549 static int LoadDMO( vlc_object_t *p_this, HINSTANCE *p_hmsdmo_dll,
550                     IMediaObject **pp_dmo, es_format_t *p_fmt,
551                     vlc_bool_t b_out )
552 {
553     DMO_PARTIAL_MEDIATYPE dmo_partial_type;
554     int i_err;
555
556 #ifndef LOADER
557     long (STDCALL *OurDMOEnum)( const GUID *, uint32_t, uint32_t,
558                                const DMO_PARTIAL_MEDIATYPE *,
559                                uint32_t, const DMO_PARTIAL_MEDIATYPE *,
560                                IEnumDMO ** );
561
562     IEnumDMO *p_enum_dmo = NULL;
563     WCHAR *psz_dmo_name;
564     GUID clsid_dmo;
565     uint32_t i_dummy;
566 #endif
567
568     GETCLASS GetClass;
569     IClassFactory *cFactory = NULL;
570     IUnknown *cObject = NULL;
571     const codec_dll *codecs_table = b_out ? encoders_table : decoders_table;
572     int i_codec;
573
574     /* Look for a DMO which can handle the requested codec */
575     if( p_fmt->i_cat == AUDIO_ES )
576     {
577         uint16_t i_tag;
578         dmo_partial_type.type = MEDIATYPE_Audio;
579         dmo_partial_type.subtype = dmo_partial_type.type;
580         dmo_partial_type.subtype.Data1 = p_fmt->i_codec;
581         fourcc_to_wf_tag( p_fmt->i_codec, &i_tag );
582         if( i_tag ) dmo_partial_type.subtype.Data1 = i_tag;
583     }
584     else
585     {
586         dmo_partial_type.type = MEDIATYPE_Video;
587         dmo_partial_type.subtype = dmo_partial_type.type;
588         dmo_partial_type.subtype.Data1 = p_fmt->i_codec;
589     }
590
591 #ifndef LOADER
592     /* Load msdmo DLL */
593     *p_hmsdmo_dll = LoadLibrary( "msdmo.dll" );
594     if( *p_hmsdmo_dll == NULL )
595     {
596         msg_Dbg( p_this, "failed loading msdmo.dll" );
597         return VLC_EGENERIC;
598     }
599     OurDMOEnum = (void *)GetProcAddress( *p_hmsdmo_dll, "DMOEnum" );
600     if( OurDMOEnum == NULL )
601     {
602         msg_Dbg( p_this, "GetProcAddress failed to find DMOEnum()" );
603         FreeLibrary( *p_hmsdmo_dll );
604         return VLC_EGENERIC;
605     }
606
607     if( !b_out )
608     {
609         i_err = OurDMOEnum( &GUID_NULL, 1 /*DMO_ENUMF_INCLUDE_KEYED*/,
610                             1, &dmo_partial_type, 0, NULL, &p_enum_dmo );
611     }
612     else
613     {
614         i_err = OurDMOEnum( &GUID_NULL, 1 /*DMO_ENUMF_INCLUDE_KEYED*/,
615                             0, NULL, 1, &dmo_partial_type, &p_enum_dmo );
616     }
617     if( i_err )
618     {
619         FreeLibrary( *p_hmsdmo_dll );
620         /* return VLC_EGENERIC; */
621         /* Try loading the dll directly */
622         goto loader;
623     }
624
625     /* Pickup the first available codec */
626     *pp_dmo = 0;
627     while( ( S_OK == p_enum_dmo->vt->Next( p_enum_dmo, 1, &clsid_dmo,
628                      &psz_dmo_name, &i_dummy /* NULL doesn't work */ ) ) )
629     {
630         char psz_temp[MAX_PATH];
631         wcstombs( psz_temp, psz_dmo_name, MAX_PATH );
632         msg_Dbg( p_this, "found DMO: %s", psz_temp );
633         CoTaskMemFree( psz_dmo_name );
634
635         /* Create DMO */
636         if( CoCreateInstance( &clsid_dmo, NULL, CLSCTX_INPROC,
637                               &IID_IMediaObject, (void **)pp_dmo ) )
638         {
639             msg_Warn( p_this, "can't create DMO: %s", psz_temp );
640             *pp_dmo = 0;
641         }
642         else break;
643     }
644
645     p_enum_dmo->vt->Release( (IUnknown *)p_enum_dmo );
646
647     if( !*pp_dmo )
648     {
649         FreeLibrary( *p_hmsdmo_dll );
650         /* return VLC_EGENERIC; */
651         /* Try loading the dll directly */
652         goto loader;
653     }
654
655     return VLC_SUCCESS;
656
657 loader:
658 #endif   /* LOADER */
659
660     for( i_codec = 0; codecs_table[i_codec].i_fourcc != 0; i_codec++ )
661     {
662         if( codecs_table[i_codec].i_fourcc == p_fmt->i_codec )
663             break;
664     }
665     if( codecs_table[i_codec].i_fourcc == 0 )
666         return VLC_EGENERIC;    /* Can't happen */
667
668     *p_hmsdmo_dll = LoadLibrary( codecs_table[i_codec].psz_dll );
669     if( *p_hmsdmo_dll == NULL )
670     {
671         msg_Dbg( p_this, "failed loading '%s'",
672                  codecs_table[i_codec].psz_dll );
673         return VLC_EGENERIC;
674     }
675
676     GetClass = (GETCLASS)GetProcAddress( *p_hmsdmo_dll, "DllGetClassObject" );
677     if (!GetClass)
678     {
679         msg_Dbg( p_this, "GetProcAddress failed to find DllGetClassObject()" );
680         FreeLibrary( *p_hmsdmo_dll );
681         return VLC_EGENERIC;
682     }
683
684     i_err = GetClass( codecs_table[i_codec].p_guid, &IID_IClassFactory,
685                       (void**)&cFactory );
686     if( i_err || cFactory == NULL )
687     {
688         msg_Dbg( p_this, "no such class object" );
689         FreeLibrary( *p_hmsdmo_dll );
690         return VLC_EGENERIC;
691     }
692
693     i_err = cFactory->vt->CreateInstance( cFactory, 0, &IID_IUnknown,
694                                           (void**)&cObject );
695     cFactory->vt->Release( (IUnknown*)cFactory );
696     if( i_err || !cObject )
697     {
698         msg_Dbg( p_this, "class factory failure" );
699         FreeLibrary( *p_hmsdmo_dll );
700         return VLC_EGENERIC;
701     }
702     i_err = cObject->vt->QueryInterface( cObject, &IID_IMediaObject,
703                                         (void**)pp_dmo );
704     cObject->vt->Release( (IUnknown*)cObject );
705     if( i_err || !*pp_dmo )
706     {
707         msg_Dbg( p_this, "QueryInterface failure" );
708         FreeLibrary( *p_hmsdmo_dll );
709         return VLC_EGENERIC;
710     }
711
712     return VLC_SUCCESS;
713 }
714
715 /*****************************************************************************
716  * DecoderClose: close codec
717  *****************************************************************************/
718 void DecoderClose( vlc_object_t *p_this )
719 {
720     decoder_t *p_dec = (decoder_t*)p_this;
721     decoder_sys_t *p_sys = p_dec->p_sys;
722
723     if( !p_sys ) return;
724
725     if( p_sys->p_dmo ) p_sys->p_dmo->vt->Release( (IUnknown *)p_sys->p_dmo );
726     FreeLibrary( p_sys->hmsdmo_dll );
727
728 #ifdef LOADER
729 #if 0
730     Restore_LDT_Keeper( p_sys->ldt_fs );
731 #endif
732 #else
733     /* Uninitialize OLE/COM */
734     CoUninitialize();
735 #endif
736
737     if( p_sys->p_buffer ) free( p_sys->p_buffer );
738     free( p_sys );
739 }
740
741 /****************************************************************************
742  * DecodeBlock: the whole thing
743  ****************************************************************************
744  * This function must be fed with ogg packets.
745  ****************************************************************************/
746 static void *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
747 {
748     decoder_sys_t *p_sys = p_dec->p_sys;
749     block_t *p_block;
750     int i_result;
751
752     DMO_OUTPUT_DATA_BUFFER db;
753     CMediaBuffer *p_out;
754     block_t block_out;
755     uint32_t i_status;
756
757     if( p_sys == NULL )
758     {
759         if( DecOpen( VLC_OBJECT(p_dec) ) )
760         {
761             msg_Err( p_dec, "DecOpen failed" );
762             return NULL;
763         }
764         p_sys = p_dec->p_sys;
765     }
766
767     if( !pp_block ) return NULL;
768
769     p_block = *pp_block;
770
771     /* Won't work with streams with B-frames, but do we have any ? */
772     if( p_block && p_block->i_pts <= 0 ) p_block->i_pts = p_block->i_dts;
773
774     /* Date management */
775     if( p_block && p_block->i_pts > 0 &&
776         p_block->i_pts != date_Get( &p_sys->end_date ) )
777     {
778         date_Set( &p_sys->end_date, p_block->i_pts );
779     }
780
781 #if 0 /* Breaks the video decoding */
782     if( !date_Get( &p_sys->end_date ) )
783     {
784         /* We've just started the stream, wait for the first PTS. */
785         if( p_block ) block_Release( p_block );
786         return NULL;
787     }
788 #endif
789
790     /* Feed input to the DMO */
791     if( p_block && p_block->i_buffer )
792     {
793         CMediaBuffer *p_in;
794
795         p_in = CMediaBufferCreate( p_block, p_block->i_buffer, VLC_TRUE );
796
797         i_result = p_sys->p_dmo->vt->ProcessInput( p_sys->p_dmo, 0,
798                        (IMediaBuffer *)p_in, DMO_INPUT_DATA_BUFFERF_SYNCPOINT,
799                        0, 0 );
800
801         p_in->vt->Release( (IUnknown *)p_in );
802
803         if( i_result == S_FALSE )
804         {
805             /* No output generated */
806 #ifdef DMO_DEBUG
807             msg_Dbg( p_dec, "ProcessInput(): no output generated" );
808 #endif
809             return NULL;
810         }
811         else if( i_result == (int)DMO_E_NOTACCEPTING )
812         {
813             /* Need to call ProcessOutput */
814             msg_Dbg( p_dec, "ProcessInput(): not accepting" );
815         }
816         else if( i_result != S_OK )
817         {
818             msg_Dbg( p_dec, "ProcessInput(): failed" );
819             return NULL;
820         }
821         else
822         {
823             //msg_Dbg( p_dec, "ProcessInput(): successful" );
824             *pp_block = 0;
825         }
826     }
827     else if( p_block && !p_block->i_buffer )
828     {
829         block_Release( p_block );
830         *pp_block = 0;
831     }
832
833     /* Get output from the DMO */
834     block_out.p_buffer = p_sys->p_buffer;
835     block_out.i_buffer = 0;
836
837     p_out = CMediaBufferCreate( &block_out, p_sys->i_min_output, VLC_FALSE );
838     memset( &db, 0, sizeof(db) );
839     db.pBuffer = (IMediaBuffer *)p_out;
840
841     i_result = p_sys->p_dmo->vt->ProcessOutput( p_sys->p_dmo,
842                    DMO_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER,
843                    1, &db, &i_status );
844
845     if( i_result != S_OK )
846     {
847         if( i_result != S_FALSE )
848             msg_Dbg( p_dec, "ProcessOutput(): failed" );
849 #if DMO_DEBUG
850         else
851             msg_Dbg( p_dec, "ProcessOutput(): no output" );
852 #endif
853
854         p_out->vt->Release( (IUnknown *)p_out );
855         return NULL;
856     }
857
858 #if DMO_DEBUG
859     msg_Dbg( p_dec, "ProcessOutput(): success" );
860 #endif
861
862     if( !block_out.i_buffer )
863     {
864 #if DMO_DEBUG
865         msg_Dbg( p_dec, "ProcessOutput(): no output (i_buffer_out == 0)" );
866 #endif
867         p_out->vt->Release( (IUnknown *)p_out );
868         return NULL;
869     }
870
871     if( p_dec->fmt_out.i_cat == VIDEO_ES )
872     {
873         /* Get a new picture */
874         picture_t *p_pic = p_dec->pf_vout_buffer_new( p_dec );
875         if( !p_pic ) return NULL;
876
877         CopyPicture( p_dec, p_pic, block_out.p_buffer );
878
879         /* Date management */
880         p_pic->date = date_Get( &p_sys->end_date );
881         date_Increment( &p_sys->end_date, 1 );
882
883         p_out->vt->Release( (IUnknown *)p_out );
884
885         return p_pic;
886     }
887     else
888     {
889         aout_buffer_t *p_aout_buffer;
890         int i_samples = block_out.i_buffer /
891             ( p_dec->fmt_out.audio.i_bitspersample *
892               p_dec->fmt_out.audio.i_channels / 8 );
893
894         p_aout_buffer = p_dec->pf_aout_buffer_new( p_dec, i_samples );
895         memcpy( p_aout_buffer->p_buffer,
896                 block_out.p_buffer, block_out.i_buffer );
897
898         /* Date management */
899         p_aout_buffer->start_date = date_Get( &p_sys->end_date );
900         p_aout_buffer->end_date =
901             date_Increment( &p_sys->end_date, i_samples );
902
903         p_out->vt->Release( (IUnknown *)p_out );
904
905         return p_aout_buffer;
906     }
907
908     return NULL;
909 }
910
911 static void CopyPicture( decoder_t *p_dec, picture_t *p_pic, uint8_t *p_in )
912 {
913     int i_plane, i_line, i_width, i_dst_stride;
914     uint8_t *p_dst, *p_src = p_in;
915
916     p_dst = p_pic->p[1].p_pixels;
917     p_pic->p[1].p_pixels = p_pic->p[2].p_pixels;
918     p_pic->p[2].p_pixels = p_dst;
919
920     for( i_plane = 0; i_plane < p_pic->i_planes; i_plane++ )
921     {
922         p_dst = p_pic->p[i_plane].p_pixels;
923         i_width = p_pic->p[i_plane].i_visible_pitch;
924         i_dst_stride  = p_pic->p[i_plane].i_pitch;
925
926         for( i_line = 0; i_line < p_pic->p[i_plane].i_visible_lines; i_line++ )
927         {
928             p_dec->p_libvlc->pf_memcpy( p_dst, p_src, i_width );
929             p_src += i_width;
930             p_dst += i_dst_stride;
931         }
932     }
933
934     p_dst = p_pic->p[1].p_pixels;
935     p_pic->p[1].p_pixels = p_pic->p[2].p_pixels;
936     p_pic->p[2].p_pixels = p_dst;
937 }
938
939 /****************************************************************************
940  * Encoder descriptor declaration
941  ****************************************************************************/
942 struct encoder_sys_t
943 {
944     HINSTANCE hmsdmo_dll;
945     IMediaObject *p_dmo;
946
947     int i_min_output;
948
949     date_t end_date;
950
951 #ifdef LOADER
952     ldt_fs_t    *ldt_fs;
953 #endif
954 };
955
956 /*****************************************************************************
957  * EncoderOpen: open dmo codec
958  *****************************************************************************/
959 static int EncoderOpen( vlc_object_t *p_this )
960 {
961     encoder_t *p_enc = (encoder_t*)p_this;
962
963 #ifndef LOADER
964     int i_ret = EncOpen( p_this );
965     if( i_ret != VLC_SUCCESS ) return i_ret;
966
967 #else
968     /* We can't open it now, because of ldt_keeper or something
969      * Open/Encode/Close has to be done in the same thread */
970     int i;
971
972     /* Probe if we support it */
973     for( i = 0; encoders_table[i].i_fourcc != 0; i++ )
974     {
975         if( encoders_table[i].i_fourcc == p_enc->fmt_out.i_codec )
976         {
977             msg_Dbg( p_enc, "DMO codec for %4.4s may work with dll=%s",
978                      (char*)&p_enc->fmt_out.i_codec,
979                      encoders_table[i].psz_dll );
980             break;
981         }
982     }
983
984     p_enc->p_sys = NULL;
985     if( !encoders_table[i].i_fourcc ) return VLC_EGENERIC;
986 #endif /* LOADER */
987
988     /* Set callbacks */
989     p_enc->pf_encode_video = (block_t *(*)(encoder_t *, picture_t *))
990         EncodeBlock;
991     p_enc->pf_encode_audio = (block_t *(*)(encoder_t *, aout_buffer_t *))
992         EncodeBlock;
993
994     return VLC_SUCCESS;
995 }
996
997 /*****************************************************************************
998  * EncoderSetVideoType: configures the input and output types of the dmo
999  *****************************************************************************/
1000 static int EncoderSetVideoType( encoder_t *p_enc, IMediaObject *p_dmo )
1001 {
1002     int i, i_selected, i_err;
1003     DMO_MEDIA_TYPE dmo_type;
1004     VIDEOINFOHEADER vih, *p_vih;
1005     BITMAPINFOHEADER *p_bih;
1006
1007     /* FIXME */
1008     p_enc->fmt_in.video.i_bits_per_pixel = 
1009         p_enc->fmt_out.video.i_bits_per_pixel = 12;
1010
1011     /* Enumerate input format (for debug output) */
1012     i = 0;
1013     while( !p_dmo->vt->GetInputType( p_dmo, 0, i++, &dmo_type ) )
1014     {
1015         p_vih = (VIDEOINFOHEADER *)dmo_type.pbFormat;
1016
1017         msg_Dbg( p_enc, "available input chroma: %4.4s",
1018                  (char *)&dmo_type.subtype.Data1 );
1019         if( !memcmp( &dmo_type.subtype, &MEDIASUBTYPE_RGB565, 16 ) )
1020             msg_Dbg( p_enc, "-> MEDIASUBTYPE_RGB565" );
1021         if( !memcmp( &dmo_type.subtype, &MEDIASUBTYPE_RGB24, 16 ) )
1022             msg_Dbg( p_enc, "-> MEDIASUBTYPE_RGB24" );
1023
1024         DMOFreeMediaType( &dmo_type );
1025     }
1026
1027     /* Setup input format */
1028     memset( &dmo_type, 0, sizeof(dmo_type) );
1029     dmo_type.pUnk = 0;
1030     memset( &vih, 0, sizeof(VIDEOINFOHEADER) );
1031
1032     p_bih = &vih.bmiHeader;
1033     p_bih->biCompression = VLC_FOURCC('I','4','2','0');
1034     p_bih->biWidth = p_enc->fmt_in.video.i_width;
1035     p_bih->biHeight = p_enc->fmt_in.video.i_height;
1036     p_bih->biBitCount = p_enc->fmt_in.video.i_bits_per_pixel;
1037     p_bih->biSizeImage = p_enc->fmt_in.video.i_width *
1038         p_enc->fmt_in.video.i_height * p_enc->fmt_in.video.i_bits_per_pixel /8;
1039     p_bih->biPlanes = 3;
1040     p_bih->biSize = sizeof(BITMAPINFOHEADER);
1041
1042     vih.rcSource.left = vih.rcSource.top = 0;
1043     vih.rcSource.right = p_enc->fmt_in.video.i_width;
1044     vih.rcSource.bottom = p_enc->fmt_in.video.i_height;
1045     vih.rcTarget = vih.rcSource;
1046
1047     vih.AvgTimePerFrame = I64C(10000000) / 25; //FIXME
1048
1049     dmo_type.majortype = MEDIATYPE_Video;
1050     //dmo_type.subtype = MEDIASUBTYPE_RGB24;
1051     dmo_type.subtype = MEDIASUBTYPE_I420;
1052     //dmo_type.subtype.Data1 = p_bih->biCompression;
1053     dmo_type.formattype = FORMAT_VideoInfo;
1054     dmo_type.bFixedSizeSamples = TRUE;
1055     dmo_type.bTemporalCompression = FALSE;
1056     dmo_type.lSampleSize = p_bih->biSizeImage;
1057     dmo_type.cbFormat = sizeof(VIDEOINFOHEADER);
1058     dmo_type.pbFormat = (char *)&vih;
1059
1060     if( ( i_err = p_dmo->vt->SetInputType( p_dmo, 0, &dmo_type, 0 ) ) )
1061     {
1062         msg_Err( p_enc, "can't set DMO input type: %x", i_err );
1063         return VLC_EGENERIC;
1064     }
1065
1066     msg_Dbg( p_enc, "successfully set input type" );
1067
1068     /* Setup output format */
1069     memset( &dmo_type, 0, sizeof(dmo_type) );
1070     dmo_type.pUnk = 0;
1071
1072     /* Enumerate output types */
1073     i = 0, i_selected = -1;
1074     while( !p_dmo->vt->GetOutputType( p_dmo, 0, i++, &dmo_type ) )
1075     {
1076         p_vih = (VIDEOINFOHEADER *)dmo_type.pbFormat;
1077
1078         msg_Dbg( p_enc, "available output codec: %4.4s",
1079                  (char *)&dmo_type.subtype.Data1 );
1080
1081         if( p_vih->bmiHeader.biCompression == p_enc->fmt_out.i_codec )
1082             i_selected = i - 1;
1083
1084         DMOFreeMediaType( &dmo_type );
1085     }
1086
1087     if( i_selected < 0 )
1088     {
1089         msg_Err( p_enc, "couldn't find codec: %4.4s",
1090                  (char *)&p_enc->fmt_out.i_codec );
1091         return VLC_EGENERIC;
1092     }
1093
1094     p_dmo->vt->GetOutputType( p_dmo, 0, i_selected, &dmo_type );
1095     ((VIDEOINFOHEADER *)dmo_type.pbFormat)->dwBitRate =
1096         p_enc->fmt_out.i_bitrate;
1097
1098     /* Get the private data for the codec */
1099     while( 1 )
1100     {
1101         IWMCodecPrivateData *p_privdata;
1102         VIDEOINFOHEADER *p_vih;
1103         uint8_t *p_data = 0;
1104         uint32_t i_data = 0, i_vih;
1105
1106         i_err = p_dmo->vt->QueryInterface( (IUnknown *)p_dmo,
1107                                            &IID_IWMCodecPrivateData,
1108                                            (void **)&p_privdata );
1109         if( i_err ) break;
1110
1111         i_err = p_privdata->vt->SetPartialOutputType( p_privdata, &dmo_type );
1112         if( i_err )
1113         {
1114             msg_Err( p_enc, "SetPartialOutputType() failed" );
1115             p_privdata->vt->Release( (IUnknown *)p_privdata );
1116             break;
1117         }
1118
1119         i_err = p_privdata->vt->GetPrivateData( p_privdata, NULL, &i_data );
1120         if( i_err )
1121         {
1122             msg_Err( p_enc, "GetPrivateData() failed" );
1123             p_privdata->vt->Release( (IUnknown *)p_privdata );
1124             break;
1125         }
1126
1127         p_data = malloc( i_data );
1128         i_err = p_privdata->vt->GetPrivateData( p_privdata, p_data, &i_data );
1129
1130         /* Update the media type with the private data */
1131         i_vih = dmo_type.cbFormat + i_data;
1132         p_vih = CoTaskMemAlloc( i_vih );
1133         memcpy( p_vih, dmo_type.pbFormat, dmo_type.cbFormat );
1134         memcpy( ((uint8_t *)p_vih) + dmo_type.cbFormat, p_data, i_data );
1135         DMOFreeMediaType( &dmo_type );
1136         dmo_type.pbFormat = (char*)p_vih;
1137         dmo_type.cbFormat = i_vih;
1138
1139         msg_Dbg( p_enc, "found extra data: %i", i_data );
1140         p_enc->fmt_out.i_extra = i_data;
1141         p_enc->fmt_out.p_extra = p_data;
1142         break;
1143     }
1144
1145     i_err = p_dmo->vt->SetOutputType( p_dmo, 0, &dmo_type, 0 );
1146
1147     p_vih = (VIDEOINFOHEADER *)dmo_type.pbFormat;
1148     p_enc->fmt_in.i_codec = VLC_FOURCC('I','4','2','0');
1149
1150     DMOFreeMediaType( &dmo_type );
1151     if( i_err )
1152     {
1153         msg_Err( p_enc, "can't set DMO output type: %i", i_err );
1154         return VLC_EGENERIC;
1155     }
1156
1157     msg_Dbg( p_enc, "successfully set output type" );
1158     return VLC_SUCCESS;
1159 }
1160
1161 /*****************************************************************************
1162  * EncoderSetAudioType: configures the input and output types of the dmo
1163  *****************************************************************************/
1164 static int EncoderSetAudioType( encoder_t *p_enc, IMediaObject *p_dmo )
1165 {
1166     int i, i_selected, i_err;
1167     unsigned int i_last_byterate;
1168     uint16_t i_tag;
1169     DMO_MEDIA_TYPE dmo_type;
1170     WAVEFORMATEX *p_wf;
1171
1172     /* Setup the format structure */
1173     fourcc_to_wf_tag( p_enc->fmt_out.i_codec, &i_tag );
1174     if( i_tag == 0 ) return VLC_EGENERIC;
1175
1176     p_enc->fmt_in.i_codec = AOUT_FMT_S16_NE;
1177     p_enc->fmt_in.audio.i_bitspersample = 16;
1178
1179     /* We first need to choose an output type from the predefined
1180      * list of choices (we cycle through the list to select the best match) */
1181     i = 0; i_selected = -1; i_last_byterate = 0;
1182     while( !p_dmo->vt->GetOutputType( p_dmo, 0, i++, &dmo_type ) )
1183     {
1184         p_wf = (WAVEFORMATEX *)dmo_type.pbFormat;
1185         msg_Dbg( p_enc, "available format :%i, sample rate: %i, channels: %i, "
1186                  "bits per sample: %i, bitrate: %i, blockalign: %i",
1187                  (int) p_wf->wFormatTag, (int)p_wf->nSamplesPerSec,
1188                  (int)p_wf->nChannels, (int)p_wf->wBitsPerSample,
1189                  (int)p_wf->nAvgBytesPerSec * 8, (int)p_wf->nBlockAlign );
1190
1191         if( p_wf->wFormatTag == i_tag &&
1192             p_wf->nSamplesPerSec == p_enc->fmt_in.audio.i_rate &&
1193             p_wf->nChannels == p_enc->fmt_in.audio.i_channels &&
1194             p_wf->wBitsPerSample == p_enc->fmt_in.audio.i_bitspersample )
1195         {
1196             if( (int)p_wf->nAvgBytesPerSec <
1197                 p_enc->fmt_out.i_bitrate * 110 / 800 /* + 10% */ &&
1198                 p_wf->nAvgBytesPerSec > i_last_byterate )
1199             {
1200                 i_selected = i - 1;
1201                 i_last_byterate = p_wf->nAvgBytesPerSec;
1202                 msg_Dbg( p_enc, "selected entry %i (bitrate: %i)",
1203                          i_selected, p_wf->nAvgBytesPerSec * 8 );
1204             }
1205         }
1206
1207         DMOFreeMediaType( &dmo_type );
1208     }
1209
1210     if( i_selected < 0 )
1211     {
1212         msg_Err( p_enc, "couldn't find a matching output" );
1213         return VLC_EGENERIC;
1214     }
1215
1216     p_dmo->vt->GetOutputType( p_dmo, 0, i_selected, &dmo_type );
1217     p_wf = (WAVEFORMATEX *)dmo_type.pbFormat;
1218
1219     msg_Dbg( p_enc, "selected format: %i, sample rate:%i, "
1220              "channels: %i, bits per sample: %i, bitrate: %i, blockalign: %i",
1221              (int)p_wf->wFormatTag, (int)p_wf->nSamplesPerSec,
1222              (int)p_wf->nChannels, (int)p_wf->wBitsPerSample,
1223              (int)p_wf->nAvgBytesPerSec * 8, (int)p_wf->nBlockAlign );
1224
1225     p_enc->fmt_out.audio.i_rate = p_wf->nSamplesPerSec;
1226     p_enc->fmt_out.audio.i_channels = p_wf->nChannels;
1227     p_enc->fmt_out.audio.i_bitspersample = p_wf->wBitsPerSample;
1228     p_enc->fmt_out.audio.i_blockalign = p_wf->nBlockAlign;
1229     p_enc->fmt_out.i_bitrate = p_wf->nAvgBytesPerSec * 8;
1230
1231     if( p_wf->cbSize )
1232     {
1233         msg_Dbg( p_enc, "found cbSize: %i", p_wf->cbSize );
1234         p_enc->fmt_out.i_extra = p_wf->cbSize;
1235         p_enc->fmt_out.p_extra = malloc( p_enc->fmt_out.i_extra );
1236         memcpy( p_enc->fmt_out.p_extra, &p_wf[1], p_enc->fmt_out.i_extra );
1237     }
1238
1239     i_err = p_dmo->vt->SetOutputType( p_dmo, 0, &dmo_type, 0 );
1240     DMOFreeMediaType( &dmo_type );
1241
1242     if( i_err )
1243     {
1244         msg_Err( p_enc, "can't set DMO output type: %i", i_err );
1245         return VLC_EGENERIC;
1246     }
1247
1248     msg_Dbg( p_enc, "successfully set output type" );
1249
1250     /* Setup the input type */
1251     i = 0; i_selected = -1;
1252     while( !p_dmo->vt->GetInputType( p_dmo, 0, i++, &dmo_type ) )
1253     {
1254         p_wf = (WAVEFORMATEX *)dmo_type.pbFormat;
1255         msg_Dbg( p_enc, "available format :%i, sample rate: %i, channels: %i, "
1256                  "bits per sample: %i, bitrate: %i, blockalign: %i",
1257                  (int) p_wf->wFormatTag, (int)p_wf->nSamplesPerSec,
1258                  (int)p_wf->nChannels, (int)p_wf->wBitsPerSample,
1259                  (int)p_wf->nAvgBytesPerSec * 8, (int)p_wf->nBlockAlign );
1260
1261         if( p_wf->wFormatTag == WAVE_FORMAT_PCM &&
1262             p_wf->nSamplesPerSec == p_enc->fmt_in.audio.i_rate &&
1263             p_wf->nChannels == p_enc->fmt_in.audio.i_channels &&
1264             p_wf->wBitsPerSample == p_enc->fmt_in.audio.i_bitspersample )
1265         {
1266             i_selected = i - 1;
1267         }
1268
1269         DMOFreeMediaType( &dmo_type );
1270     }
1271
1272     if( i_selected < 0 )
1273     {
1274         msg_Err( p_enc, "couldn't find a matching input" );
1275         return VLC_EGENERIC;
1276     }
1277
1278     p_dmo->vt->GetInputType( p_dmo, 0, i_selected, &dmo_type );
1279     i_err = p_dmo->vt->SetInputType( p_dmo, 0, &dmo_type, 0 );
1280     DMOFreeMediaType( &dmo_type );
1281     if( i_err )
1282     {
1283         msg_Err( p_enc, "can't set DMO input type: %x", i_err );
1284         return VLC_EGENERIC;
1285     }
1286     msg_Dbg( p_enc, "successfully set input type" );
1287
1288     return VLC_SUCCESS;
1289 }
1290
1291 /*****************************************************************************
1292  * EncOpen: open dmo codec
1293  *****************************************************************************/
1294 static int EncOpen( vlc_object_t *p_this )
1295 {
1296     encoder_t *p_enc = (encoder_t*)p_this;
1297     encoder_sys_t *p_sys = NULL;
1298     IMediaObject *p_dmo = NULL;
1299     HINSTANCE hmsdmo_dll = NULL;
1300
1301 #ifdef LOADER
1302     ldt_fs_t *ldt_fs = Setup_LDT_Keeper();
1303 #else
1304     /* Initialize OLE/COM */
1305     CoInitialize( 0 );
1306 #endif /* LOADER */
1307
1308     if( LoadDMO( p_this, &hmsdmo_dll, &p_dmo, &p_enc->fmt_out, VLC_TRUE )
1309         != VLC_SUCCESS )
1310     {
1311         hmsdmo_dll = 0;
1312         p_dmo = 0;
1313         goto error;
1314     }
1315
1316     if( p_enc->fmt_in.i_cat == VIDEO_ES )
1317     {
1318         if( EncoderSetVideoType( p_enc, p_dmo ) != VLC_SUCCESS ) goto error;
1319     }
1320     else
1321     {
1322         if( EncoderSetAudioType( p_enc, p_dmo ) != VLC_SUCCESS ) goto error;
1323     }
1324
1325     /* Allocate the memory needed to store the decoder's structure */
1326     if( ( p_enc->p_sys = p_sys =
1327           (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
1328     {
1329         msg_Err( p_enc, "out of memory" );
1330         goto error;
1331     }
1332
1333     p_sys->hmsdmo_dll = hmsdmo_dll;
1334     p_sys->p_dmo = p_dmo;
1335 #ifdef LOADER
1336     p_sys->ldt_fs = ldt_fs;
1337 #endif
1338
1339     /* Find out some properties of the inputput */
1340     {
1341         uint32_t i_size, i_align, dum;
1342
1343         if( p_dmo->vt->GetInputSizeInfo( p_dmo, 0, &i_size, &i_align, &dum ) )
1344             msg_Err( p_enc, "GetInputSizeInfo() failed" );
1345         else
1346             msg_Dbg( p_enc, "GetInputSizeInfo(): bytes %i, align %i, %i",
1347                      i_size, i_align, dum );
1348     }
1349
1350     /* Find out some properties of the output */
1351     {
1352         uint32_t i_size, i_align;
1353
1354         p_sys->i_min_output = 0;
1355         if( p_dmo->vt->GetOutputSizeInfo( p_dmo, 0, &i_size, &i_align ) )
1356         {
1357             msg_Err( p_enc, "GetOutputSizeInfo() failed" );
1358             goto error;
1359         }
1360         else
1361         {
1362             msg_Dbg( p_enc, "GetOutputSizeInfo(): bytes %i, align %i",
1363                      i_size, i_align );
1364             p_sys->i_min_output = i_size;
1365         }
1366     }
1367
1368     /* Set output properties */
1369     p_enc->fmt_out.i_cat = p_enc->fmt_out.i_cat;
1370     if( p_enc->fmt_out.i_cat == AUDIO_ES )
1371         date_Init( &p_sys->end_date, p_enc->fmt_out.audio.i_rate, 1 );
1372     else
1373         date_Init( &p_sys->end_date, 25 /* FIXME */, 1 );
1374
1375     return VLC_SUCCESS;
1376
1377  error:
1378
1379     if( p_dmo ) p_dmo->vt->Release( (IUnknown *)p_dmo );
1380     if( hmsdmo_dll ) FreeLibrary( hmsdmo_dll );
1381
1382 #ifdef LOADER
1383     Restore_LDT_Keeper( ldt_fs );
1384 #else
1385     /* Uninitialize OLE/COM */
1386     CoUninitialize();
1387 #endif /* LOADER */
1388
1389     if( p_sys ) free( p_sys );
1390
1391     return VLC_EGENERIC;
1392 }
1393
1394 /****************************************************************************
1395  * Encode: the whole thing
1396  ****************************************************************************/
1397 static block_t *EncodeBlock( encoder_t *p_enc, void *p_data )
1398 {
1399     encoder_sys_t *p_sys = p_enc->p_sys;
1400     CMediaBuffer *p_in;
1401     block_t *p_chain = NULL;
1402     block_t *p_block_in;
1403     uint32_t i_status;
1404     int i_result;
1405     mtime_t i_pts;
1406
1407     if( p_sys == NULL )
1408     {
1409         if( EncOpen( VLC_OBJECT(p_enc) ) )
1410         {
1411             msg_Err( p_enc, "EncOpen failed" );
1412             return NULL;
1413         }
1414         p_sys = p_enc->p_sys;
1415     }
1416
1417     if( !p_data ) return NULL;
1418
1419     if( p_enc->fmt_out.i_cat == VIDEO_ES )
1420     {
1421         /* Get picture data */
1422         int i_plane, i_line, i_width, i_src_stride;
1423         picture_t *p_pic = (picture_t *)p_data;
1424         uint8_t *p_dst;
1425
1426         int i_buffer = p_enc->fmt_in.video.i_width *
1427             p_enc->fmt_in.video.i_height *
1428             p_enc->fmt_in.video.i_bits_per_pixel / 8;
1429
1430         p_block_in = block_New( p_enc, i_buffer );
1431
1432         /* Copy picture stride by stride */
1433         p_dst = p_block_in->p_buffer;
1434         for( i_plane = 0; i_plane < p_pic->i_planes; i_plane++ )
1435         {
1436             uint8_t *p_src = p_pic->p[i_plane].p_pixels;
1437             i_width = p_pic->p[i_plane].i_visible_pitch;
1438             i_src_stride = p_pic->p[i_plane].i_pitch;
1439
1440             for( i_line = 0; i_line < p_pic->p[i_plane].i_visible_lines;
1441                  i_line++ )
1442             {
1443                 p_enc->p_libvlc->pf_memcpy( p_dst, p_src, i_width );
1444                 p_dst += i_width;
1445                 p_src += i_src_stride;
1446             }
1447         }
1448
1449         i_pts = p_pic->date;
1450     }
1451     else
1452     {
1453         aout_buffer_t *p_aout_buffer = (aout_buffer_t *)p_data;
1454         p_block_in = block_New( p_enc, p_aout_buffer->i_nb_bytes );
1455         memcpy( p_block_in->p_buffer, p_aout_buffer->p_buffer,
1456                 p_block_in->i_buffer );
1457
1458         i_pts = p_aout_buffer->start_date;
1459     }
1460
1461     /* Feed input to the DMO */
1462     p_in = CMediaBufferCreate( p_block_in, p_block_in->i_buffer, VLC_TRUE );
1463     i_result = p_sys->p_dmo->vt->ProcessInput( p_sys->p_dmo, 0,
1464        (IMediaBuffer *)p_in, DMO_INPUT_DATA_BUFFERF_TIME, i_pts * 10, 0 );
1465
1466     p_in->vt->Release( (IUnknown *)p_in );
1467     if( i_result == S_FALSE )
1468     {
1469         /* No output generated */
1470 #ifdef DMO_DEBUG
1471         msg_Dbg( p_enc, "ProcessInput(): no output generated "I64Fd, i_pts );
1472 #endif
1473         return NULL;
1474     }
1475     else if( i_result == (int)DMO_E_NOTACCEPTING )
1476     {
1477         /* Need to call ProcessOutput */
1478         msg_Dbg( p_enc, "ProcessInput(): not accepting" );
1479     }
1480     else if( i_result != S_OK )
1481     {
1482         msg_Dbg( p_enc, "ProcessInput(): failed: %x", i_result );
1483         return NULL;
1484     }
1485
1486 #if DMO_DEBUG
1487     msg_Dbg( p_enc, "ProcessInput(): success" );
1488 #endif
1489
1490     /* Get output from the DMO */
1491     while( 1 )
1492     {
1493         DMO_OUTPUT_DATA_BUFFER db;
1494         block_t *p_block_out;
1495         CMediaBuffer *p_out;
1496
1497         p_block_out = block_New( p_enc, p_sys->i_min_output );
1498         p_block_out->i_buffer = 0;
1499         p_out = CMediaBufferCreate(p_block_out, p_sys->i_min_output, VLC_FALSE);
1500         memset( &db, 0, sizeof(db) );
1501         db.pBuffer = (IMediaBuffer *)p_out;
1502
1503         i_result = p_sys->p_dmo->vt->ProcessOutput( p_sys->p_dmo,
1504                                                     0, 1, &db, &i_status );
1505
1506         if( i_result != S_OK )
1507         {
1508             if( i_result != S_FALSE )
1509                 msg_Dbg( p_enc, "ProcessOutput(): failed: %x", i_result );
1510 #if DMO_DEBUG
1511             else
1512                 msg_Dbg( p_enc, "ProcessOutput(): no output" );
1513 #endif
1514
1515             p_out->vt->Release( (IUnknown *)p_out );
1516             block_Release( p_block_out );
1517             return p_chain;
1518         }
1519
1520         if( !p_block_out->i_buffer )
1521         {
1522 #if DMO_DEBUG
1523             msg_Dbg( p_enc, "ProcessOutput(): no output (i_buffer_out == 0)" );
1524 #endif
1525             p_out->vt->Release( (IUnknown *)p_out );
1526             block_Release( p_block_out );
1527             return p_chain;
1528         }
1529
1530         if( db.dwStatus & DMO_OUTPUT_DATA_BUFFERF_TIME )
1531         {
1532 #if DMO_DEBUG
1533             msg_Dbg( p_enc, "ProcessOutput(): pts: "I64Fd", "I64Fd,
1534                      i_pts, db.rtTimestamp / 10 );
1535 #endif
1536             i_pts = db.rtTimestamp / 10;
1537         }
1538
1539         if( db.dwStatus & DMO_OUTPUT_DATA_BUFFERF_TIMELENGTH )
1540         {
1541             p_block_out->i_length = db.rtTimelength / 10;
1542 #if DMO_DEBUG
1543             msg_Dbg( p_enc, "ProcessOutput(): length: "I64Fd,
1544                      p_block_out->i_length );
1545 #endif
1546         }
1547
1548         if( p_enc->fmt_out.i_cat == VIDEO_ES )
1549         {
1550             if( db.dwStatus & DMO_OUTPUT_DATA_BUFFERF_SYNCPOINT )
1551                 p_block_out->i_flags |= BLOCK_FLAG_TYPE_I;
1552             else
1553                 p_block_out->i_flags |= BLOCK_FLAG_TYPE_P;
1554         }
1555
1556         p_block_out->i_dts = p_block_out->i_pts = i_pts;
1557         block_ChainAppend( &p_chain, p_block_out );
1558     }
1559 }
1560
1561 /*****************************************************************************
1562  * EncoderClose: close codec
1563  *****************************************************************************/
1564 void EncoderClose( vlc_object_t *p_this )
1565 {
1566     encoder_t *p_enc = (encoder_t*)p_this;
1567     encoder_sys_t *p_sys = p_enc->p_sys;
1568
1569     if( !p_sys ) return;
1570
1571     if( p_sys->p_dmo ) p_sys->p_dmo->vt->Release( (IUnknown *)p_sys->p_dmo );
1572     FreeLibrary( p_sys->hmsdmo_dll );
1573
1574 #ifdef LOADER
1575 #if 0
1576     Restore_LDT_Keeper( p_sys->ldt_fs );
1577 #endif
1578 #else
1579     /* Uninitialize OLE/COM */
1580     CoUninitialize();
1581 #endif
1582
1583     free( p_sys );
1584 }