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