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