v4l2.c 54.7 KB
Newer Older
1 2 3
/*****************************************************************************
 * v4l2.c : Video4Linux2 input module for vlc
 *****************************************************************************
4 5
 * Copyright (C) 2002-2007 the VideoLAN team
 * $Id$
6 7
 *
 * Author: Benjamin Pracht <bigben at videolan dot org>
8
 *         Richard Hosking <richard at hovis dot net>
9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (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
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
22 23 24
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

25
/*
26 27 28
 * Sections based on the reference V4L2 capture example at
 * http://v4l2spec.bytesex.org/spec/capture-example.html
 */
29

30
/*
31
 * TODO: No mjpeg support yet.
32 33 34
 * TODO: Tuner partial implementation.
 * TODO: Alsa input support?
 */
35 36 37 38 39 40

/*****************************************************************************
 * Preamble
 *****************************************************************************/

#include <vlc/vlc.h>
Clément Stenac's avatar
Clément Stenac committed
41
#include <vlc_access.h>
42
#include <vlc_demux.h>
Clément Stenac's avatar
Clément Stenac committed
43 44
#include <vlc_input.h>
#include <vlc_vout.h>
45 46 47 48

#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
49
#include <sys/mman.h>
50 51 52

#include <linux/videodev2.h>

53 54
#include <sys/soundcard.h>

55 56
/*****************************************************************************
 * Module descriptior
57
 *****************************************************************************/
58 59 60 61 62 63 64 65

static int  Open ( vlc_object_t * );
static void Close( vlc_object_t * );

#define DEV_TEXT N_("Device name")
#define DEV_LONGTEXT N_( \
    "Name of the device to use. " \
    "If you don't specify anything, /dev/video0 will be used.")
66 67 68 69 70 71 72 73 74 75 76
#define ADEV_TEXT N_("Audio device name")
#define ADEV_LONGTEXT N_( \
    "Name of the audio device to use. " \
    "If you don't specify anything, no audio device will be used.")
#define STANDARD_TEXT N_( "Standard" )
#define STANDARD_LONGTEXT N_( \
    "Video standard (Default, SECAM, PAL, or NTSC)." )
#define CHROMA_TEXT N_("Video input chroma format")
#define CHROMA_LONGTEXT N_( \
    "Force the Video4Linux2 video device to use a specific chroma format " \
    "(eg. I420, RV24, etc.)")
Benjamin Pracht's avatar
Benjamin Pracht committed
77 78 79 80
#define INPUT_TEXT N_( "Input" )
#define INPUT_LONGTEXT N_( \
    "Input of the card to use (Usually, 0 = tuner, " \
    "1 = composite, 2 = svideo)." )
81 82 83 84 85 86 87 88 89 90 91
#define IOMETHOD_TEXT N_( "IO Method" )
#define IOMETHOD_LONGTEXT N_( \
    "IO Method (READ, MMAP, USERPTR)." )
#define FPS_TEXT N_( "Framerate" )
#define FPS_LONGTEXT N_( "Framerate to capture, if applicable " \
    "(-1 for autodetect)." )
#define STEREO_TEXT N_( "Stereo" )
#define STEREO_LONGTEXT N_( \
    "Capture the audio stream in stereo." )
#define SAMPLERATE_TEXT N_( "Samplerate" )
#define SAMPLERATE_LONGTEXT N_( \
92
    "Samplerate of the captured audio stream, in Hz (eg: 11025, 22050, 44100, 48000)" )
93 94 95 96
#define CACHING_TEXT N_("Caching value in ms")
#define CACHING_LONGTEXT N_( \
    "Caching value for V4L2 captures. This " \
    "value should be set in milliseconds." )
97

98 99 100 101 102 103 104 105 106 107
typedef enum {
    IO_METHOD_READ,
    IO_METHOD_MMAP,
    IO_METHOD_USERPTR,
} io_method;

static int i_standards_list[] =
    { V4L2_STD_UNKNOWN, V4L2_STD_SECAM, V4L2_STD_PAL, V4L2_STD_NTSC };
static const char *psz_standards_list_text[] =
    { N_("Default"), N_("SECAM"), N_("PAL"),  N_("NTSC") };
108

109 110 111 112
static int i_iomethod_list[] =
    { IO_METHOD_READ, IO_METHOD_MMAP, IO_METHOD_USERPTR };
static const char *psz_iomethod_list_text[] =
    { N_("READ"), N_("MMAP"),  N_("USERPTR") };
113 114 115 116 117 118 119 120 121

vlc_module_begin();
    set_shortname( _("Video4Linux2") );
    set_description( _("Video4Linux2 input") );
    set_category( CAT_INPUT );
    set_subcategory( SUBCAT_INPUT_ACCESS );

    add_string( "v4l2-dev", "/dev/video0", 0, DEV_TEXT, DEV_LONGTEXT,
                VLC_FALSE );
122 123 124 125
    add_string( "v4l2-adev", "/dev/dsp", 0, DEV_TEXT, DEV_LONGTEXT,
                VLC_FALSE );
    add_integer( "v4l2-standard", 0, NULL, STANDARD_TEXT, STANDARD_LONGTEXT,
                VLC_FALSE );
126
        change_integer_list( i_standards_list, psz_standards_list_text, 0 );
127 128
    add_string( "v4l2-chroma", NULL, NULL, CHROMA_TEXT, CHROMA_LONGTEXT,
                VLC_TRUE );
Benjamin Pracht's avatar
Benjamin Pracht committed
129 130
    add_integer( "v4l2-input", 0, NULL, INPUT_TEXT, INPUT_LONGTEXT,
                VLC_TRUE );
131 132 133
    add_integer( "v4l2-io", IO_METHOD_MMAP, NULL, IOMETHOD_TEXT,
                 IOMETHOD_LONGTEXT, VLC_FALSE );
        change_integer_list( i_iomethod_list, psz_iomethod_list_text, 0 );
134 135 136 137 138 139 140
    add_float( "v4l2-fps", 0, NULL, FPS_TEXT, FPS_LONGTEXT, VLC_TRUE );
    add_bool( "v4l2-stereo", VLC_TRUE, NULL, STEREO_TEXT, STEREO_LONGTEXT,
                VLC_TRUE );
    add_integer( "v4l2-samplerate", 48000, NULL, SAMPLERATE_TEXT,
                SAMPLERATE_LONGTEXT, VLC_TRUE );
    add_integer( "v4l2-caching", DEFAULT_PTS_DELAY / 1000, NULL,
                CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
141 142 143 144 145 146 147 148 149 150

    add_shortcut( "v4l2" );
    set_capability( "access_demux", 10 );
    set_callbacks( Open, Close );
vlc_module_end();

/*****************************************************************************
 * Access: local prototypes
 *****************************************************************************/

151 152
static void ParseMRL( demux_t * );

153 154
static int Control( demux_t *, int, va_list );

155 156 157 158
static int Demux( demux_t * );
static block_t* GrabVideo( demux_t *p_demux );
static block_t* ProcessVideoFrame( demux_t *p_demux, uint8_t *p_frame );
static block_t* GrabAudio( demux_t *p_demux );
Benjamin Pracht's avatar
Benjamin Pracht committed
159

160
vlc_bool_t IsChromaSupported( demux_t *p_demux, unsigned int i_v4l2 );
161
unsigned int GetFourccFromString( char *psz_fourcc );
162 163 164 165 166 167 168

static int OpenVideoDev( demux_t *, char *psz_device );
static int OpenAudioDev( demux_t *, char *psz_device );
static vlc_bool_t ProbeVideoDev( demux_t *, char *psz_device );
static vlc_bool_t ProbeAudioDev( demux_t *, char *psz_device );

static struct
169
{
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    unsigned int i_v4l2;
    int i_fourcc;
} v4l2chroma_to_fourcc[] =
{
    { V4L2_PIX_FMT_GREY, VLC_FOURCC( 'G', 'R', 'E', 'Y' ) },
    { V4L2_PIX_FMT_HI240, VLC_FOURCC( 'I', '2', '4', '0' ) },
    { V4L2_PIX_FMT_RGB565, VLC_FOURCC( 'R', 'V', '1', '6' ) },
    { V4L2_PIX_FMT_RGB555, VLC_FOURCC( 'R', 'V', '1', '5' ) },
    { V4L2_PIX_FMT_BGR24, VLC_FOURCC( 'R', 'V', '2', '4' ) },
    { V4L2_PIX_FMT_BGR32, VLC_FOURCC( 'R', 'V', '3', '2' ) },
    { V4L2_PIX_FMT_YUYV, VLC_FOURCC( 'Y', 'U', 'Y', '2' ) },
    { V4L2_PIX_FMT_YUYV, VLC_FOURCC( 'Y', 'U', 'Y', 'V' ) },
    { V4L2_PIX_FMT_UYVY, VLC_FOURCC( 'U', 'Y', 'V', 'Y' ) },
    { V4L2_PIX_FMT_Y41P, VLC_FOURCC( 'I', '4', '1', 'N' ) },
    { V4L2_PIX_FMT_YUV422P, VLC_FOURCC( 'I', '4', '2', '2' ) },
    { V4L2_PIX_FMT_YVU420, VLC_FOURCC( 'I', '4', '2', '0' ) },
    { V4L2_PIX_FMT_YUV411P, VLC_FOURCC( 'I', '4', '1', '1' ) },
    { V4L2_PIX_FMT_YUV410, VLC_FOURCC( 'I', '4', '1', '0' ) },
    { 0, 0 }
};
190

191
struct buffer_t
192 193 194
{
    void *  start;
    size_t  length;
195
    void *  orig_userp;
196 197 198 199 200
};

struct demux_sys_t
{
    char *psz_device;  /* Main device from MRL, can be video or audio */
201

202 203 204 205 206
    char *psz_vdev;
    int  i_fd_video;

    char *psz_adev;
    int  i_fd_audio;
207

208 209
    /* Video */
    io_method io;
210

211
    int i_pts;
212 213 214 215 216

    struct v4l2_capability dev_cap;

    int i_input;
    struct v4l2_input *p_inputs;
Benjamin Pracht's avatar
Benjamin Pracht committed
217
    int i_selected_input;
218

219 220 221
    int i_standard;
    struct v4l2_standard *p_standards;
    v4l2_std_id i_selected_standard_id;
222 223 224 225 226 227 228

    int i_audio;
    /* V4L2 devices cannot have more than 32 audio inputs */
    struct v4l2_audio p_audios[32];

    int i_tuner;
    struct v4l2_tuner *p_tuners;
Benjamin Pracht's avatar
Benjamin Pracht committed
229 230 231

    int i_codec;
    struct v4l2_fmtdesc *p_codecs;
232

233 234
    struct buffer_t *p_buffers;
    unsigned int i_nbuffers;
235

236 237 238 239 240
    int i_width;
    int i_height;
    float f_fps;            /* <= 0.0 mean to grab at full rate */
    mtime_t i_video_pts;    /* only used when f_fps > 0 */
    int i_fourcc;
241

242 243
    picture_t pic;
    int i_video_frame_size;
244

245
    es_out_id_t *p_es_video;
246

247 248 249 250 251 252
    /* Audio */
    int i_sample_rate;
    vlc_bool_t b_stereo;
    int i_audio_max_frame_size;
    block_t *p_block_audio;
    es_out_id_t *p_es_audio;
253 254 255
};

/*****************************************************************************
256
 * Open: opens v4l2 device
257 258 259 260 261 262 263 264 265
 *****************************************************************************
 *
 * url: <video device>::::
 *
 *****************************************************************************/
static int Open( vlc_object_t *p_this )
{
    demux_t     *p_demux = (demux_t*)p_this;
    demux_sys_t *p_sys;
266 267
    vlc_value_t val;
    char *psz;
268

269
    /* Only when selected */
270
    if( *p_demux->psz_access == '\0' ) return VLC_EGENERIC;
271

272 273
    /* Set up p_demux */
    p_demux->pf_control = Control;
274
    p_demux->pf_demux = Demux;
275 276 277 278
    p_demux->info.i_update = 0;
    p_demux->info.i_title = 0;
    p_demux->info.i_seekpoint = 0;

279
    p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
280
    if( p_sys == NULL ) return VLC_ENOMEM;
281

282
    p_sys->i_video_pts = -1;
283

284 285 286
    var_Create( p_demux, "v4l2-standard", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
    var_Get( p_demux, "v4l2-standard", &val );
    p_sys->i_selected_standard_id = i_standards_list[val.i_int];
287

288
    p_sys->i_selected_input = var_CreateGetInteger( p_demux, "v4l2-input" );
289

290
    p_sys->io = var_CreateGetInteger( p_demux, "v4l2-io" );
291

292 293 294
    var_Create( p_demux, "v4l2-fps", VLC_VAR_FLOAT | VLC_VAR_DOINHERIT );
    var_Get( p_demux, "v4l2-fps", &val );
    p_sys->f_fps = val.f_float;
295

296 297 298
    var_Create( p_demux, "v4l2-samplerate", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
    var_Get( p_demux, "v4l2-samplerate", &val );
    p_sys->i_sample_rate = val.i_int;
299

300
    psz = var_CreateGetString( p_demux, "v4l2-chroma" );
301
    p_sys->i_fourcc = GetFourccFromString( psz );
302 303
    free( psz );

304 305 306 307 308 309 310 311 312
    var_Create( p_demux, "v4l2-stereo", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
    var_Get( p_demux, "v4l2-stereo", &val );
    p_sys->b_stereo = val.b_bool;

    p_sys->i_pts = var_CreateGetInteger( p_demux, "v4l2-caching" );

    p_sys->psz_device = p_sys->psz_vdev = p_sys->psz_adev = NULL;
    p_sys->i_fd_video = -1;
    p_sys->i_fd_audio = -1;
313

314 315 316 317
    p_sys->p_es_video = p_sys->p_es_audio = 0;
    p_sys->p_block_audio = 0;

    ParseMRL( p_demux );
318

319 320 321 322
    /* Find main device (video or audio) */
    if( p_sys->psz_device && *p_sys->psz_device )
    {
        msg_Dbg( p_demux, "main device='%s'", p_sys->psz_device );
323

324 325 326 327 328
        /* Try to open as video device */
        msg_Dbg( p_demux, "trying device '%s' as video", p_sys->psz_device );
        if( ProbeVideoDev( p_demux, p_sys->psz_device ) )
        {
            msg_Dbg( p_demux, "'%s' is a video device", p_sys->psz_device );
329
            /* Device was a video device */
330 331 332 333 334 335 336
            if( p_sys->psz_vdev ) free( p_sys->psz_vdev );
            p_sys->psz_vdev = p_sys->psz_device;
            p_sys->psz_device = NULL;
            p_sys->i_fd_video = OpenVideoDev( p_demux, p_sys->psz_vdev );
            if( p_sys->i_fd_video < 0 )
            {
                Close( p_this );
337
                return VLC_EGENERIC;
338 339 340 341
            }
        }
        else
        {
342
            /* Try to open as audio device */
343 344 345 346 347 348 349 350 351 352 353 354
            msg_Dbg( p_demux, "trying device '%s' as audio", p_sys->psz_device );
            if( ProbeAudioDev( p_demux, p_sys->psz_device ) )
            {
                msg_Dbg( p_demux, "'%s' is an audio device", p_sys->psz_device );
                /* Device was an audio device */
                if( p_sys->psz_adev ) free( p_sys->psz_adev );
                p_sys->psz_adev = p_sys->psz_device;
                p_sys->psz_device = NULL;
                p_sys->i_fd_audio = OpenAudioDev( p_demux, p_sys->psz_adev );
                if( p_sys->i_fd_audio < 0 )
                {
                    Close( p_this );
355
                    return VLC_EGENERIC;
356 357 358 359
                }
            }
        }
    }
360

361 362 363 364 365 366 367 368 369
    /* If no device opened, only continue if the access was forced */
    if( p_sys->i_fd_video < 0 && p_sys->i_fd_audio < 0 )
    {
        if( strcmp( p_demux->psz_access, "v4l2" ) )
        {
            Close( p_this );
            return VLC_EGENERIC;
        }
    }
Benjamin Pracht's avatar
Benjamin Pracht committed
370

371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    /* Find video device */
    if( p_sys->i_fd_video < 0 )
    {
        if( !p_sys->psz_vdev || !*p_sys->psz_vdev )
        {
            if( p_sys->psz_vdev ) free( p_sys->psz_vdev );
            p_sys->psz_vdev = var_CreateGetString( p_demux, "v4l2-dev" );;
        }

        if( p_sys->psz_vdev && *p_sys->psz_vdev && ProbeVideoDev( p_demux, p_sys->psz_vdev ) )
        {
            p_sys->i_fd_video = OpenVideoDev( p_demux, p_sys->psz_vdev );
        }
    }

    /* Find audio device */
    if( p_sys->i_fd_audio < 0 )
    {
        if( !p_sys->psz_adev || !*p_sys->psz_adev )
        {
            if( p_sys->psz_adev ) free( p_sys->psz_adev );
            p_sys->psz_adev = var_CreateGetString( p_demux, "v4l2-adev" );;
        }

        if( p_sys->psz_adev && *p_sys->psz_adev && ProbeAudioDev( p_demux, p_sys->psz_adev ) )
        {
            p_sys->i_fd_audio = OpenAudioDev( p_demux, p_sys->psz_adev );
        }
    }

    if( p_sys->i_fd_video < 0 && p_sys->i_fd_audio < 0 )
    {
        Close( p_this );
        return VLC_EGENERIC;
    }
406 407 408 409

    return VLC_SUCCESS;
}

410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
/*****************************************************************************
 * ParseMRL: parse the options contained in the MRL
 *****************************************************************************/
static void ParseMRL( demux_t *p_demux )
{
    demux_sys_t *p_sys = p_demux->p_sys;

    char *psz_dup = strdup( p_demux->psz_path );
    char *psz_parser = psz_dup;

    while( *psz_parser && *psz_parser != ':' )
    {
        psz_parser++;
    }

    if( *psz_parser == ':' )
    {
        /* read options */
        for( ;; )
        {
            *psz_parser++ = '\0';
431

432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
            if( !strncmp( psz_parser, "adev=", strlen( "adev=" ) ) )
            {
                int  i_len;

                psz_parser += strlen( "adev=" );
                if( strchr( psz_parser, ':' ) )
                {
                    i_len = strchr( psz_parser, ':' ) - psz_parser;
                }
                else
                {
                    i_len = strlen( psz_parser );
                }

                p_sys->psz_adev = strndup( psz_parser, i_len );

448
                psz_parser += i_len;
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
            }
            else if( !strncmp( psz_parser, "standard=", strlen( "standard=" ) ) )
            {
                psz_parser += strlen( "standard=" );
                if( !strncmp( psz_parser, "pal", strlen( "pal" ) ) )
                {
                    p_sys->i_selected_standard_id = V4L2_STD_PAL;
                    psz_parser += strlen( "pal" );
                }
                else if( !strncmp( psz_parser, "ntsc", strlen( "ntsc" ) ) )
                {
                    p_sys->i_selected_standard_id = V4L2_STD_NTSC;
                    psz_parser += strlen( "ntsc" );
                }
                else if( !strncmp( psz_parser, "secam", strlen( "secam" ) ) )
                {
                    p_sys->i_selected_standard_id = V4L2_STD_SECAM;
                    psz_parser += strlen( "secam" );
                }
                else if( !strncmp( psz_parser, "default", strlen( "default" ) ) )
                {
                    p_sys->i_selected_standard_id = V4L2_STD_UNKNOWN;
                    psz_parser += strlen( "default" );
                }
                else
                {
                    p_sys->i_selected_standard_id = i_standards_list[strtol( psz_parser, &psz_parser, 0 )];
                }
            }
            else if( !strncmp( psz_parser, "chroma=", strlen( "chroma=" ) ) )
            {
                int  i_len;

                psz_parser += strlen( "chroma=" );
                if( strchr( psz_parser, ':' ) )
                {
                    i_len = strchr( psz_parser, ':' ) - psz_parser;
                }
                else
                {
                    i_len = strlen( psz_parser );
                }

                char* chroma = strndup( psz_parser, i_len );
493
                p_sys->i_fourcc = GetFourccFromString( chroma );
494
                free( chroma );
495

496
                psz_parser += i_len;
497 498 499 500 501
            }
            else if( !strncmp( psz_parser, "input=", strlen( "input=" ) ) )
            {
                p_sys->i_selected_input = strtol( psz_parser + strlen( "input=" ),
                                       &psz_parser, 0 );
502
            }
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
            else if( !strncmp( psz_parser, "fps=", strlen( "fps=" ) ) )
            {
                p_sys->f_fps = strtof( psz_parser + strlen( "fps=" ),
                                       &psz_parser );
            }
            else if( !strncmp( psz_parser, "io=", strlen( "io=" ) ) )
            {
                psz_parser += strlen( "io=" );
                if( !strncmp( psz_parser, "read", strlen( "read" ) ) )
                {
                    p_sys->io = IO_METHOD_READ;
                    psz_parser += strlen( "read" );
                }
                else if( !strncmp( psz_parser, "mmap", strlen( "mmap" ) ) )
                {
                    p_sys->io = IO_METHOD_MMAP;
                    psz_parser += strlen( "mmap" );
                }
                else if( !strncmp( psz_parser, "userptr", strlen( "userptr" ) ) )
                {
                    p_sys->io = IO_METHOD_USERPTR;
                    psz_parser += strlen( "userptr" );
                }
                else
                {
                    p_sys->io = strtol( psz_parser, &psz_parser, 0 );
                }
            }
            else if( !strncmp( psz_parser, "samplerate=",
                               strlen( "samplerate=" ) ) )
            {
                p_sys->i_sample_rate =
                    strtol( psz_parser + strlen( "samplerate=" ),
                            &psz_parser, 0 );
            }
            else if( !strncmp( psz_parser, "stereo", strlen( "stereo" ) ) )
            {
                psz_parser += strlen( "stereo" );
                p_sys->b_stereo = VLC_TRUE;
            }
            else if( !strncmp( psz_parser, "mono", strlen( "mono" ) ) )
            {
                psz_parser += strlen( "mono" );
                p_sys->b_stereo = VLC_FALSE;
            }
            else if( !strncmp( psz_parser, "caching=", strlen( "caching=" ) ) )
            {
                p_sys->i_pts = strtol( psz_parser + strlen( "caching=" ),
                                       &psz_parser, DEFAULT_PTS_DELAY / 1000 );
            }
            else
            {
                msg_Warn( p_demux, "unknown option" );
            }

            while( *psz_parser && *psz_parser != ':' )
            {
                psz_parser++;
            }

            if( *psz_parser == '\0' )
            {
                break;
            }
        }
    }

    /* Main device */
    if( *psz_dup )
    {
        p_sys->psz_device = strdup( psz_dup );
    }
    if( psz_dup ) free( psz_dup );
}

578 579 580 581 582 583
/*****************************************************************************
 * Close: close device, free resources
 *****************************************************************************/
static void Close( vlc_object_t *p_this )
{
    demux_t     *p_demux = (demux_t *)p_this;
584
    demux_sys_t *p_sys   = p_demux->p_sys;
585 586 587
    struct v4l2_buffer buf;
    enum v4l2_buf_type buf_type;
    unsigned int i;
588

589
    /* Stop video capture */
590
    if( p_sys->i_fd_video >= 0 )
591 592 593 594 595 596
    {
        switch( p_sys->io )
        {
        case IO_METHOD_READ:
            /* Nothing to do */
            break;
597

598
        case IO_METHOD_MMAP:
599 600
        case IO_METHOD_USERPTR:
            /* Some drivers 'hang' internally if this is not done before streamoff */
601 602 603 604 605 606 607
            for( unsigned int i = 0; i < p_sys->i_nbuffers; i++ )
            {
                memset( &buf, 0, sizeof(buf) );
                buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
                buf.memory = V4L2_MEMORY_USERPTR;
                ioctl( p_sys->i_fd_video, VIDIOC_DQBUF, &buf ); /* ignore result */
            }
608 609

            buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
610 611
            if( ioctl( p_sys->i_fd_video, VIDIOC_STREAMOFF, &buf_type ) < 0 ) {
                msg_Err( p_demux, "VIDIOC_STREAMOFF failed" );
612 613 614
            }

            break;
615 616
        }
    }
617

618 619 620 621 622 623 624
    /* Free Video Buffers */
    if( p_sys->p_buffers ) {
        switch( p_sys->io )
        {
        case IO_METHOD_READ:
            free( p_sys->p_buffers[0].start );
            break;
625

626
        case IO_METHOD_MMAP:
627
            for( i = 0; i < p_sys->i_nbuffers; ++i )
628 629 630 631 632
            {
                if( munmap( p_sys->p_buffers[i].start, p_sys->p_buffers[i].length ) )
                {
                    msg_Err( p_demux, "munmap failed" );
                }
633
            }
634
            break;
635 636 637

        case IO_METHOD_USERPTR:
            for( i = 0; i < p_sys->i_nbuffers; ++i )
638
            {
639
               free( p_sys->p_buffers[i].orig_userp );
640 641
            }
            break;
642 643 644
        }
        free( p_sys->p_buffers );
    }
Benjamin Pracht's avatar
Benjamin Pracht committed
645

646 647 648 649
    /* Close */
    if( p_sys->i_fd_video >= 0 ) close( p_sys->i_fd_video );
    if( p_sys->i_fd_audio >= 0 ) close( p_sys->i_fd_audio );

650
    if( p_sys->p_block_audio ) block_Release( p_sys->p_block_audio );
651
    if( p_sys->psz_device ) free( p_sys->psz_device );
652 653 654
    if( p_sys->psz_vdev ) free( p_sys->psz_vdev );
    if( p_sys->psz_adev ) free( p_sys->psz_adev );
    if( p_sys->p_standards ) free( p_sys->p_standards );
655
    if( p_sys->p_inputs ) free( p_sys->p_inputs );
Benjamin Pracht's avatar
Benjamin Pracht committed
656 657
    if( p_sys->p_tuners ) free( p_sys->p_tuners );
    if( p_sys->p_codecs ) free( p_sys->p_codecs );
658 659 660 661 662 663 664 665 666

    free( p_sys );
}

/*****************************************************************************
 * Control:
 *****************************************************************************/
static int Control( demux_t *p_demux, int i_query, va_list args )
{
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
    demux_sys_t *p_sys = p_demux->p_sys;
    vlc_bool_t *pb;
    int64_t    *pi64;

    switch( i_query )
    {
        /* Special for access_demux */
        case DEMUX_CAN_PAUSE:
        case DEMUX_SET_PAUSE_STATE:
        case DEMUX_CAN_CONTROL_PACE:
            pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
            *pb = VLC_FALSE;
            return VLC_SUCCESS;

        case DEMUX_GET_PTS_DELAY:
            pi64 = (int64_t*)va_arg( args, int64_t * );
            *pi64 = (int64_t)p_sys->i_pts * 1000;
            return VLC_SUCCESS;

        case DEMUX_GET_TIME:
            pi64 = (int64_t*)va_arg( args, int64_t * );
            *pi64 = mdate();
            return VLC_SUCCESS;

        /* TODO implement others */
        default:
            return VLC_EGENERIC;
    }

Laurent Aimar's avatar
Laurent Aimar committed
696
    return VLC_EGENERIC;
697 698 699
}

/*****************************************************************************
700
 * Demux: Processes the audio or video frame
701
 *****************************************************************************/
702
static int Demux( demux_t *p_demux )
703
{
704
    demux_sys_t *p_sys = p_demux->p_sys;
705
    es_out_id_t *p_es = p_sys->p_es_audio;
706
    block_t *p_block = NULL;
707

708 709 710 711 712 713 714
    /* Try grabbing audio frames first */
    if( p_sys->i_fd_audio < 0 || !( p_block = GrabAudio( p_demux ) ) )
    {
        /* Try grabbing video frame */
        p_es = p_sys->p_es_video;
        if( p_sys->i_fd_video > 0 ) p_block = GrabVideo( p_demux );
    }
715

716 717 718 719 720 721 722 723 724 725 726
    if( !p_block )
    {
        /* Sleep so we do not consume all the cpu, 10ms seems
         * like a good value (100fps) */
        msleep( 10 );
        return 1;
    }

    es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block->i_pts );
    es_out_Send( p_demux->out, p_es, p_block );

Laurent Aimar's avatar
Laurent Aimar committed
727
    return 1;
728 729
}

730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
/*****************************************************************************
 * GrabVideo: Grab a video frame
 *****************************************************************************/
static block_t* GrabVideo( demux_t *p_demux )
{
    demux_sys_t *p_sys = p_demux->p_sys;

    block_t *p_block = NULL;
    struct v4l2_buffer buf;

    if( p_sys->f_fps >= 0.1 && p_sys->i_video_pts > 0 )
    {
        mtime_t i_dur = (mtime_t)((double)1000000 / (double)p_sys->f_fps);

        /* Did we wait long enough ? (frame rate reduction) */
        if( p_sys->i_video_pts + i_dur > mdate() ) return 0;
    }
747

748 749 750 751 752 753
    /* Grab Video Frame */
    switch( p_sys->io )
    {
    case IO_METHOD_READ:
        if( read( p_sys->i_fd_video, p_sys->p_buffers[0].start, p_sys->p_buffers[0].length ) )
        {
754
            switch( errno )
755 756 757 758 759 760 761 762 763
            {
            case EAGAIN:
                return 0;
            case EIO:
                /* Could ignore EIO, see spec. */
                /* fall through */
            default:
                msg_Err( p_demux, "Failed to read frame" );
                return 0;
764
               }
765
        }
766

767 768
        p_block = ProcessVideoFrame( p_demux, (uint8_t*)p_sys->p_buffers[0].start );
        if( !p_block ) return 0;
769

770
        break;
771

772 773 774 775
    case IO_METHOD_MMAP:
        memset( &buf, 0, sizeof(buf) );
        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        buf.memory = V4L2_MEMORY_MMAP;
776

777 778 779
        /* Wait for next frame */
        if (ioctl( p_sys->i_fd_video, VIDIOC_DQBUF, &buf ) < 0 )
        {
780
            switch( errno )
781 782 783 784 785 786 787 788 789
            {
            case EAGAIN:
                return 0;
            case EIO:
                /* Could ignore EIO, see spec. */
                /* fall through */
            default:
                msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
                return 0;
790
               }
791 792 793 794 795 796
        }

        if( buf.index >= p_sys->i_nbuffers ) {
            msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
            return 0;
        }
797

798 799 800
        p_block = ProcessVideoFrame( p_demux, p_sys->p_buffers[buf.index].start );
        if( !p_block ) return 0;

801
        /* Unlock */
802 803 804
        if( ioctl( p_sys->i_fd_video, VIDIOC_QBUF, &buf ) < 0 )
        {
            msg_Err (p_demux, "Failed to unlock (VIDIOC_QBUF)");
805
            return 0;
806
        }
807

808
        break;
809 810

    case IO_METHOD_USERPTR:
811 812 813
        memset( &buf, 0, sizeof(buf) );
        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        buf.memory = V4L2_MEMORY_USERPTR;
814

815 816 817
        /* Wait for next frame */
        if (ioctl( p_sys->i_fd_video, VIDIOC_DQBUF, &buf ) < 0 )
        {
818
            switch( errno )
819 820 821 822 823 824 825 826 827
            {
            case EAGAIN:
                return 0;
            case EIO:
                /* Could ignore EIO, see spec. */
                /* fall through */
            default:
                msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
                return 0;
828
               }
829 830 831 832 833 834
        }

        /* Find frame? */
        unsigned int i;
        for( i = 0; i < p_sys->i_nbuffers; i++ )
        {
835
            if( buf.m.userptr == (unsigned long)p_sys->p_buffers[i].start &&
836 837 838 839 840 841 842
                buf.length == p_sys->p_buffers[i].length ) break;
        }

        if( i >= p_sys->i_nbuffers ) {
            msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
            return 0;
        }
843

844 845 846
        p_block = ProcessVideoFrame( p_demux, (uint8_t*)buf.m.userptr );
        if( !p_block ) return 0;

847
        /* Unlock */
848 849 850 851 852
        if( ioctl( p_sys->i_fd_video, VIDIOC_QBUF, &buf ) < 0 )
        {
            msg_Err (p_demux, "Failed to unlock (VIDIOC_QBUF)");
            return 0;
        }
853

854
        break;
855

856
    }
857

858 859
    /* Timestamp */
    p_sys->i_video_pts = p_block->i_pts = p_block->i_dts = mdate();
860

861 862 863 864 865 866 867 868 869 870 871 872 873
    return p_block;
}

/*****************************************************************************
 * ProcessVideoFrame: Helper function to take a buffer and copy it into
 * a new block
 *****************************************************************************/
static block_t* ProcessVideoFrame( demux_t *p_demux, uint8_t *p_frame )
{
    demux_sys_t *p_sys = p_demux->p_sys;
    block_t *p_block;

    if( !p_frame ) return 0;
874

875 876 877 878 879 880 881 882 883
    /* New block */
    if( !( p_block = block_New( p_demux, p_sys->i_video_frame_size ) ) )
    {
        msg_Warn( p_demux, "Cannot get new block" );
        return 0;
    }

    /* Copy frame */
    memcpy( p_block->p_buffer, p_frame, p_sys->i_video_frame_size );
884

885 886 887 888 889 890 891 892 893 894 895 896
    return p_block;
}

/*****************************************************************************
 * GrabAudio: Grab an audio frame
 *****************************************************************************/
static block_t* GrabAudio( demux_t *p_demux )
{
    demux_sys_t *p_sys = p_demux->p_sys;
    struct audio_buf_info buf_info;
    int i_read, i_correct;
    block_t *p_block;
897

898 899 900 901 902 903 904 905 906 907 908 909 910 911
    /* Copied from v4l.c */

    if( p_sys->p_block_audio ) p_block = p_sys->p_block_audio;
    else p_block = block_New( p_demux, p_sys->i_audio_max_frame_size );

    if( !p_block )
    {
        msg_Warn( p_demux, "cannot get block" );
        return 0;
    }

    p_sys->p_block_audio = p_block;

    i_read = read( p_sys->i_fd_audio, p_block->p_buffer,
912
                   p_sys->i_audio_max_frame_size );
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936

    if( i_read <= 0 ) return 0;

    p_block->i_buffer = i_read;
    p_sys->p_block_audio = 0;

    /* Correct the date because of kernel buffering */
    i_correct = i_read;
    if( ioctl( p_sys->i_fd_audio, SNDCTL_DSP_GETISPACE, &buf_info ) == 0 )
    {
        i_correct += buf_info.bytes;
    }

    /* Timestamp */
    p_block->i_pts = p_block->i_dts =
        mdate() - I64C(1000000) * (mtime_t)i_correct /
        2 / ( p_sys->b_stereo ? 2 : 1) / p_sys->i_sample_rate;

    return p_block;
}

/*****************************************************************************
 * Helper function to initalise video IO using the Read method
 *****************************************************************************/
937
static int InitRead( demux_t *p_demux, int i_fd, unsigned int i_buffer_size )
938 939 940 941 942 943 944 945 946
{
    demux_sys_t *p_sys = p_demux->p_sys;

    p_sys->p_buffers = calloc( 1, sizeof( *p_sys->p_buffers ) );
    if( !p_sys->p_buffers )
    {
        msg_Err( p_demux, "Out of memory" );
        goto open_failed;
    }
947

948 949 950 951 952 953
    p_sys->p_buffers[0].length = i_buffer_size;
    p_sys->p_buffers[0].start = malloc( i_buffer_size );
    if( !p_sys->p_buffers[0].start )
    {
        msg_Err( p_demux, "Out of memory" );
        goto open_failed;
954
    }
955 956

    return VLC_SUCCESS;
957

958 959
open_failed:
    return VLC_EGENERIC;
960

961 962 963 964 965
}

/*****************************************************************************
 * Helper function to initalise video IO using the mmap method
 *****************************************************************************/
966
static int InitMmap( demux_t *p_demux, int i_fd )
967 968 969
{
    demux_sys_t *p_sys = p_demux->p_sys;
    struct v4l2_requestbuffers req;
970

971 972 973 974
    memset( &req, 0, sizeof(req) );
    req.count = 4;
    req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    req.memory = V4L2_MEMORY_MMAP;
975

976 977 978 979 980
    if( ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
    {
        msg_Err( p_demux, "device does not support mmap i/o" );
        goto open_failed;
    }
981

982 983 984 985 986
    if( req.count < 2 )
    {
        msg_Err( p_demux, "Insufficient buffer memory" );
        goto open_failed;
    }
987

988 989 990 991 992 993
    p_sys->p_buffers = calloc( req.count, sizeof( *p_sys->p_buffers ) );
    if( !p_sys->p_buffers )
    {
        msg_Err( p_demux, "Out of memory" );
        goto open_failed;
    }
994

995 996 997
    for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < req.count; ++p_sys->i_nbuffers )
    {
        struct v4l2_buffer buf;
Rafaël Carré's avatar
Rafaël Carré committed
998

999 1000 1001 1002
        memset( &buf, 0, sizeof(buf) );
        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        buf.memory = V4L2_MEMORY_MMAP;
        buf.index = p_sys->i_nbuffers;
1003

1004 1005 1006 1007 1008
        if( ioctl( i_fd, VIDIOC_QUERYBUF, &buf ) < 0 )
        {
            msg_Err( p_demux, "VIDIOC_QUERYBUF" );
            goto open_failed;
        }
1009

1010
        p_sys->p_buffers[p_sys->i_nbuffers].length = buf.length;
1011
        p_sys->p_buffers[p_sys->i_nbuffers].start =
Rafaël Carré's avatar
Rafaël Carré committed
1012
            mmap( NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, i_fd, buf.m.offset );
1013 1014 1015

        if( p_sys->p_buffers[p_sys->i_nbuffers].start == MAP_FAILED )
        {
Rafaël Carré's avatar
Rafaël Carré committed
1016
            msg_Err( p_demux, "mmap failed (%m)" );
1017 1018 1019
            goto open_failed;
        }
    }
1020

1021
    return VLC_SUCCESS;
1022

1023 1024
open_failed:
    return VLC_EGENERIC;
1025

1026 1027 1028 1029 1030
}

/*****************************************************************************
 * Helper function to initalise video IO using the userbuf method
 *****************************************************************************/
1031
static int InitUserP( demux_t *p_demux, int i_fd, unsigned int i_buffer_size )
1032 1033 1034
{
    demux_sys_t *p_sys = p_demux->p_sys;
    struct v4l2_requestbuffers req;
1035 1036 1037 1038
    unsigned int i_page_size;

    i_page_size = getpagesize();
    i_buffer_size = ( i_buffer_size + i_page_size - 1 ) & ~( i_page_size - 1);
1039

1040 1041 1042 1043
    memset( &req, 0, sizeof(req) );
    req.count = 4;
    req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    req.memory = V4L2_MEMORY_USERPTR;
1044

1045 1046 1047 1048 1049
    if( ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
    {
        msg_Err( p_demux, "device does not support user pointer i/o" );
        goto open_failed;
    }
1050

1051 1052 1053 1054 1055 1056
    p_sys->p_buffers = calloc( 4, sizeof( *p_sys->p_buffers ) );
    if( !p_sys->p_buffers )
    {
        msg_Err( p_demux, "Out of memory" );
        goto open_failed;
    }
1057

1058 1059 1060
    for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < 4; ++p_sys->i_nbuffers )
    {
        p_sys->p_buffers[p_sys->i_nbuffers].length = i_buffer_size;
1061 1062 1063
        p_sys->p_buffers[p_sys->i_nbuffers].start =
            vlc_memalign( &p_sys->p_buffers[p_sys->i_nbuffers].orig_userp,
                /* boundary */ i_page_size, i_buffer_size );
1064 1065 1066 1067 1068 1069 1070 1071 1072

        if( !p_sys->p_buffers[p_sys->i_nbuffers].start )
        {
            msg_Err( p_demux, "out of memory" );
            goto open_failed;
        }
    }

    return VLC_SUCCESS;
1073

1074 1075
open_failed:
    return VLC_EGENERIC;
1076

1077 1078 1079
}

/*****************************************************************************
1080
 * GetFourccFromString: Returns the fourcc code from the given string
1081
 *****************************************************************************/
1082
unsigned int GetFourccFromString( char *psz_fourcc )
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
{
    if( strlen( psz_fourcc ) >= 4 )
    {
        int i_chroma = VLC_FOURCC( psz_fourcc[0], psz_fourcc[1], psz_fourcc[2], psz_fourcc[3] );

        /* Find out v4l2 chroma code */
        for( int i = 0; v4l2chroma_to_fourcc[i].i_fourcc != 0; i++ )
        {
            if( v4l2chroma_to_fourcc[i].i_fourcc == i_chroma )
            {
                return v4l2chroma_to_fourcc[i].i_fourcc;
            }
        }
    }
1097

1098 1099 1100 1101
    return 0;
}

/*****************************************************************************
1102
 * IsChromaSupported: returns true if the specified V4L2 chroma constant is
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
 * in the array of supported chromas returned by the driver
 *****************************************************************************/
vlc_bool_t IsChromaSupported( demux_t *p_demux, unsigned int i_chroma )
{
    demux_sys_t *p_sys = p_demux->p_sys;

    for( int i_index = 0; i_index < p_sys->i_codec; i_index++ )
    {
        if( p_sys->p_codecs[i_index].pixelformat == i_chroma ) return VLC_TRUE;
    }
1113 1114

    return VLC_FALSE;
1115
}
1116 1117

/*****************************************************************************
Benjamin Pracht's avatar
Benjamin Pracht committed
1118
 * OpenVideoDev: open and set up the video device and probe for capabilities
1119
 *****************************************************************************/
1120
int OpenVideoDev( demux_t *p_demux, char *psz_device )
1121
{
Benjamin Pracht's avatar
Benjamin Pracht committed
1122 1123
    int i_fd;
    demux_sys_t *p_sys = p_demux->p_sys;
1124 1125 1126 1127 1128
    struct v4l2_cropcap cropcap;
    struct v4l2_crop crop;
    struct v4l2_format fmt;
    unsigned int i_min;
    enum v4l2_buf_type buf_type;
1129

1130
    if( ( i_fd = open( psz_device, O_RDWR ) ) < 0 )
Benjamin Pracht's avatar
Benjamin Pracht committed
1131
    {
1132
        msg_Err( p_demux, "cannot open device (%m)" );
Benjamin Pracht's avatar
Benjamin Pracht committed
1133 1134 1135
        goto open_failed;
    }

1136
    /* Select standard */
1137

1138 1139 1140 1141 1142 1143 1144 1145 1146
    if( p_sys->i_selected_standard_id != V4L2_STD_UNKNOWN )
    {
        if( ioctl( i_fd, VIDIOC_S_STD, &p_sys->i_selected_standard_id ) < 0 )
        {
           msg_Err( p_demux, "cannot set input (%m)" );
           goto open_failed;
        }
        msg_Dbg( p_demux, "Set standard" );
    }
Benjamin Pracht's avatar
Benjamin Pracht committed
1147