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