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