twolame.c 12 KB
Newer Older
1
/*****************************************************************************
2
 * twolame.c: libtwolame encoder (MPEG-1/2 layer II) module
3
 *            (using libtwolame from http://www.twolame.org/)
4
 *****************************************************************************
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
5
 * Copyright (C) 2004-2005 VLC authors and VideoLAN
6 7 8
 * $Id$
 *
 * Authors: Christophe Massiot <massiot@via.ecp.fr>
9
 *          Gildas Bazin
10
 *
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
11 12 13
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
14 15 16 17
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
18 19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
20
 *
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
21
 * You should have received a copy of the GNU Lesser General Public License
22 23
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24 25 26 27 28
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
29 30 31 32
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

33
#include <vlc_common.h>
34
#include <vlc_plugin.h>
35
#include <vlc_codec.h>
36

37
#include <twolame.h>
38 39 40 41 42 43 44 45 46

#define MPEG_FRAME_SIZE 1152
#define MAX_CODED_FRAME_SIZE 1792

/****************************************************************************
 * Local prototypes
 ****************************************************************************/
static int OpenEncoder   ( vlc_object_t * );
static void CloseEncoder ( vlc_object_t * );
47
static block_t *Encode   ( encoder_t *, block_t * );
48 49 50 51

/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
52
#define ENC_CFG_PREFIX "sout-twolame-"
53 54 55

#define ENC_QUALITY_TEXT N_("Encoding quality")
#define ENC_QUALITY_LONGTEXT N_( \
56
  "Force a specific encoding quality between 0.0 (high) and 50.0 (low), " \
57 58 59
  "instead of specifying a particular bitrate. " \
  "This will produce a VBR stream." )
#define ENC_MODE_TEXT N_("Stereo mode")
60
#define ENC_MODE_LONGTEXT N_( "Handling mode for stereo streams" )
61 62
#define ENC_VBR_TEXT N_("VBR mode")
#define ENC_VBR_LONGTEXT N_( \
63
  "Use Variable BitRate. Default is to use Constant BitRate (CBR)." )
64 65 66
#define ENC_PSY_TEXT N_("Psycho-acoustic model")
#define ENC_PSY_LONGTEXT N_( \
  "Integer from -1 (no model) to 4." )
67

68 69
static const int pi_stereo_values[] = { 0, 1, 2 };
static const char *const ppsz_stereo_descriptions[] =
70 71 72
{ N_("Stereo"), N_("Dual mono"), N_("Joint stereo") };


73 74 75
vlc_module_begin ()
    set_shortname( "Twolame")
    set_description( N_("Libtwolame audio encoder") )
76
    set_capability( "encoder", 120 )
77 78 79
    set_callbacks( OpenEncoder, CloseEncoder )
    set_category( CAT_INPUT )
    set_subcategory( SUBCAT_INPUT_ACODEC )
80

81
    add_float( ENC_CFG_PREFIX "quality", 0.0, ENC_QUALITY_TEXT,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
82
               ENC_QUALITY_LONGTEXT, false )
83
    add_integer( ENC_CFG_PREFIX "mode", 0, ENC_MODE_TEXT,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
84
                 ENC_MODE_LONGTEXT, false )
85
        change_integer_list( pi_stereo_values, ppsz_stereo_descriptions );
86
    add_bool( ENC_CFG_PREFIX "vbr", false, ENC_VBR_TEXT,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
87
              ENC_VBR_LONGTEXT, false )
88
    add_integer( ENC_CFG_PREFIX "psy", 3, ENC_PSY_TEXT,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
89
                 ENC_PSY_LONGTEXT, false )
90
vlc_module_end ()
91

92
static const char *const ppsz_enc_options[] = {
93
    "quality", "mode", "vbr", "psy", NULL
94 95 96
};

/*****************************************************************************
97
 * encoder_sys_t : twolame encoder descriptor
98 99 100 101 102 103
 *****************************************************************************/
struct encoder_sys_t
{
    /*
     * Input properties
     */
104
    int16_t p_buffer[MPEG_FRAME_SIZE * 2];
105
    int i_nb_samples;
106
    mtime_t i_pts;
107 108

    /*
109
     * libtwolame properties
110
     */
111
    twolame_options *p_twolame;
112 113 114 115 116 117
    unsigned char p_out_buffer[MAX_CODED_FRAME_SIZE];
};

/*****************************************************************************
 * OpenEncoder: probe the encoder and return score
 *****************************************************************************/
118 119 120 121 122 123 124 125 126
static const uint16_t mpa_bitrate_tab[2][15] =
{
    {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384},
    {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}
};

static const uint16_t mpa_freq_tab[6] =
{ 44100, 48000, 32000, 22050, 24000, 16000 };

127 128 129 130
static int OpenEncoder( vlc_object_t *p_this )
{
    encoder_t *p_enc = (encoder_t *)p_this;
    encoder_sys_t *p_sys;
131
    int i_frequency;
132

133 134
    if( p_enc->fmt_out.i_codec != VLC_CODEC_MP2 &&
        p_enc->fmt_out.i_codec != VLC_CODEC_MPGA &&
135
        p_enc->fmt_out.i_codec != VLC_FOURCC( 'm', 'p', '2', 'a' ) &&
136
        !p_enc->obj.force )
137 138 139 140
    {
        return VLC_EGENERIC;
    }

141 142 143 144 145 146
    if( p_enc->fmt_in.audio.i_channels > 2 )
    {
        msg_Err( p_enc, "doesn't support > 2 channels" );
        return VLC_EGENERIC;
    }

147 148 149 150 151 152 153 154 155 156 157 158
    for ( i_frequency = 0; i_frequency < 6; i_frequency++ )
    {
        if ( p_enc->fmt_out.audio.i_rate == mpa_freq_tab[i_frequency] )
            break;
    }
    if ( i_frequency == 6 )
    {
        msg_Err( p_enc, "MPEG audio doesn't support frequency=%d",
                 p_enc->fmt_out.audio.i_rate );
        return VLC_EGENERIC;
    }

159 160
    /* Allocate the memory needed to store the decoder's structure */
    if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
161
        return VLC_ENOMEM;
162 163
    p_enc->p_sys = p_sys;

164
    p_enc->fmt_in.i_codec = VLC_CODEC_S16N;
165 166

    p_enc->fmt_out.i_cat = AUDIO_ES;
167
    p_enc->fmt_out.i_codec = VLC_CODEC_MPGA;
168

169
    config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
170

171
    p_sys->p_twolame = twolame_init();
172 173

    /* Set options */
174 175
    twolame_set_in_samplerate( p_sys->p_twolame, p_enc->fmt_out.audio.i_rate );
    twolame_set_out_samplerate( p_sys->p_twolame, p_enc->fmt_out.audio.i_rate );
176

177
    if( var_GetBool( p_enc, ENC_CFG_PREFIX "vbr" ) )
178
    {
179
        float f_quality = var_GetFloat( p_enc, ENC_CFG_PREFIX "quality" );
180 181
        if ( f_quality > 50.f ) f_quality = 50.f;
        if ( f_quality < 0.f ) f_quality = 0.f;
182
        twolame_set_VBR( p_sys->p_twolame, 1 );
183
        twolame_set_VBR_q( p_sys->p_twolame, f_quality );
184 185 186
    }
    else
    {
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
        int i;
        for ( i = 1; i < 14; i++ )
        {
            if ( p_enc->fmt_out.i_bitrate / 1000
                  <= mpa_bitrate_tab[i_frequency / 3][i] )
                break;
        }
        if ( p_enc->fmt_out.i_bitrate / 1000
              != mpa_bitrate_tab[i_frequency / 3][i] )
        {
            msg_Warn( p_enc, "MPEG audio doesn't support bitrate=%d, using %d",
                      p_enc->fmt_out.i_bitrate,
                      mpa_bitrate_tab[i_frequency / 3][i] * 1000 );
            p_enc->fmt_out.i_bitrate = mpa_bitrate_tab[i_frequency / 3][i]
                                        * 1000;
        }

        twolame_set_bitrate( p_sys->p_twolame,
                             p_enc->fmt_out.i_bitrate / 1000 );
206 207 208 209
    }

    if ( p_enc->fmt_in.audio.i_channels == 1 )
    {
210 211
        twolame_set_num_channels( p_sys->p_twolame, 1 );
        twolame_set_mode( p_sys->p_twolame, TWOLAME_MONO );
212 213 214
    }
    else
    {
215
        twolame_set_num_channels( p_sys->p_twolame, 2 );
216
        switch( var_GetInteger( p_enc, ENC_CFG_PREFIX "mode" ) )
217 218
        {
        case 1:
219
            twolame_set_mode( p_sys->p_twolame, TWOLAME_DUAL_CHANNEL );
220 221
            break;
        case 2:
222
            twolame_set_mode( p_sys->p_twolame, TWOLAME_JOINT_STEREO );
223 224 225
            break;
        case 0:
        default:
226
            twolame_set_mode( p_sys->p_twolame, TWOLAME_STEREO );
227 228 229 230
            break;
        }
    }

231 232
    twolame_set_psymodel( p_sys->p_twolame,
                          var_GetInteger( p_enc, ENC_CFG_PREFIX "psy" ) );
233 234

    if ( twolame_init_params( p_sys->p_twolame ) )
235
    {
236
        msg_Err( p_enc, "twolame initialization failed" );
237 238 239
        return -VLC_EGENERIC;
    }

240 241
    p_enc->pf_encode_audio = Encode;

242 243 244 245 246 247 248 249 250 251
    p_sys->i_nb_samples = 0;

    return VLC_SUCCESS;
}

/****************************************************************************
 * Encode: the whole thing
 ****************************************************************************
 * This function spits out MPEG packets.
 ****************************************************************************/
252
static void Bufferize( encoder_t *p_enc, int16_t *p_in, int i_nb_samples )
253
{
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
    encoder_sys_t *p_sys = p_enc->p_sys;
    const unsigned i_offset = p_sys->i_nb_samples * p_enc->fmt_in.audio.i_channels;
    const unsigned i_len = ARRAY_SIZE(p_sys->p_buffer);

    if( i_offset >= i_len )
    {
        msg_Err( p_enc, "buffer full" );
        return;
    }

    unsigned i_copy = i_nb_samples * p_enc->fmt_in.audio.i_channels;
    if( i_copy + i_offset > i_len)
    {
        msg_Err( p_enc, "dropping samples" );
        i_copy = i_len - i_offset;
    }
270

271
    memcpy( p_sys->p_buffer + i_offset, p_in, i_copy * sizeof(int16_t) );
272 273
}

274
static block_t *Encode( encoder_t *p_enc, block_t *p_aout_buf )
275 276
{
    encoder_sys_t *p_sys = p_enc->p_sys;
277 278 279 280
    block_t *p_chain = NULL;

    if( unlikely( !p_aout_buf ) ) {
        int i_used = 0;
281
        block_t *p_block;
282

283
        i_used = twolame_encode_flush( p_sys->p_twolame,
284
                                p_sys->p_out_buffer, MAX_CODED_FRAME_SIZE );
285
        if( i_used <= 0 )
286
            return NULL;
287

288
        p_block = block_Alloc( i_used );
289 290
        if( !p_block )
            return NULL;
291
        memcpy( p_block->p_buffer, p_sys->p_out_buffer, i_used );
Ilkka Ollakka's avatar
Ilkka Ollakka committed
292
        p_block->i_length = CLOCK_FREQ *
293 294 295 296 297 298
                (mtime_t)MPEG_FRAME_SIZE / (mtime_t)p_enc->fmt_out.audio.i_rate;
        p_block->i_dts = p_block->i_pts = p_sys->i_pts;
        p_sys->i_pts += p_block->i_length;

        return p_block;
    }
299

300
    int16_t *p_buffer = (int16_t *)p_aout_buf->p_buffer;
301 302
    int i_nb_samples = p_aout_buf->i_nb_samples;

303
    p_sys->i_pts = p_aout_buf->i_pts -
304 305
                (mtime_t)1000000 * (mtime_t)p_sys->i_nb_samples /
                (mtime_t)p_enc->fmt_out.audio.i_rate;
306 307 308 309

    while ( p_sys->i_nb_samples + i_nb_samples >= MPEG_FRAME_SIZE )
    {
        int i_used;
310
        block_t *p_block;
311

312
        Bufferize( p_enc, p_buffer, MPEG_FRAME_SIZE - p_sys->i_nb_samples );
313 314 315
        i_nb_samples -= MPEG_FRAME_SIZE - p_sys->i_nb_samples;
        p_buffer += (MPEG_FRAME_SIZE - p_sys->i_nb_samples) * 2;

316
        i_used = twolame_encode_buffer_interleaved( p_sys->p_twolame,
317 318
                               p_sys->p_buffer, MPEG_FRAME_SIZE,
                               p_sys->p_out_buffer, MAX_CODED_FRAME_SIZE );
319 320 321 322 323 324 325
        /* On error, buffer samples and return what was already encoded */
        if( i_used < 0 )
        {
            msg_Err( p_enc, "encoder error: %d", i_used );
            break;
        }

326
        p_sys->i_nb_samples = 0;
327
        p_block = block_Alloc( i_used );
328 329 330
        if( !p_block )
        {
            if( p_chain )
331
                block_ChainRelease( p_chain );
332 333
            return NULL;
        }
Rafaël Carré's avatar
Rafaël Carré committed
334
        memcpy( p_block->p_buffer, p_sys->p_out_buffer, i_used );
Ilkka Ollakka's avatar
Ilkka Ollakka committed
335
        p_block->i_length = CLOCK_FREQ *
336 337 338
                (mtime_t)MPEG_FRAME_SIZE / (mtime_t)p_enc->fmt_out.audio.i_rate;
        p_block->i_dts = p_block->i_pts = p_sys->i_pts;
        p_sys->i_pts += p_block->i_length;
339 340 341 342 343
        block_ChainAppend( &p_chain, p_block );
    }

    if ( i_nb_samples )
    {
344
        Bufferize( p_enc, p_buffer, i_nb_samples );
345 346 347 348 349 350 351
        p_sys->i_nb_samples += i_nb_samples;
    }

    return p_chain;
}

/*****************************************************************************
352
 * CloseEncoder: twolame encoder destruction
353 354 355 356 357 358
 *****************************************************************************/
static void CloseEncoder( vlc_object_t *p_this )
{
    encoder_t *p_enc = (encoder_t *)p_this;
    encoder_sys_t *p_sys = p_enc->p_sys;

359
    twolame_close( &p_sys->p_twolame );
360 361 362

    free( p_sys );
}