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