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