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