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