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