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