/*****************************************************************************
 * va.c: Video Acceleration API for avcodec
 *****************************************************************************
 * Copyright (C) 2011, M2X BV
 * $Id: 9c540d3cb0c256e5df4de6ab0cad1c76881994ec $
 *
 * Authors: Jean-Paul Saman
 *
 * 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
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <vlc_common.h>
#include <vlc_fourcc.h>
#include <assert.h>

#ifdef HAVE_LIBAVCODEC_AVCODEC_H
#   include <libavcodec/avcodec.h>
#else
#   include <avcodec.h>
#endif

#include "avcodec.h"
#ifdef HAVE_AVCODEC_VAAPI
#  include <vlc_xlib.h>
#  include <libavcodec/vaapi.h>
#  include <va/va.h>
#  include <va/va_x11.h>
#endif
#include "va.h"
#include "vaapi.h"

#ifdef HAVE_AVCODEC_VAAPI

/* Global VAAPI connection state */
static vlc_va_conn_t vlc_va_conn = { NULL, 0, 0, 0, 0 };

/* */
vlc_va_conn_t *vlc_va_get_conn( void )
{
    return (vlc_va_conn_t *) &vlc_va_conn;
}

vlc_va_conn_t *vlc_va_Initialize( const char *display_name )
{
    /* connect global to caller */
    vlc_va_conn_t *conn = vlc_va_get_conn();
    assert(conn);
    if (conn->i_ref_count > 0)
    {
        conn->i_ref_count++;
        return conn;
    }

    /* Create a VA display */
    conn->p_display_x11 = XOpenDisplay(display_name);
    if( !conn->p_display_x11 )
        goto error;

    conn->p_display = vaGetDisplay(conn->p_display_x11);
    if( !conn->p_display )
        goto error;

    if( vaInitialize(conn->p_display, &conn->i_version_major, &conn->i_version_minor) )
        goto error;

    conn->i_ref_count++;
    return conn;

error:
    return NULL;
}

void vlc_va_Terminate( vlc_va_conn_t *conn )
{
    assert(conn);

    conn->i_ref_count--;
    if (conn->i_ref_count > 0)
        return;

    if( conn->p_display )
        vaTerminate( conn->p_display );
    if( conn->p_display_x11 )
        XCloseDisplay( conn->p_display_x11 );

    /* Reset values */
    conn->p_display = 0;
    conn->p_display_x11 = NULL;
    conn->i_version_major = conn->i_version_minor = 0;
    conn->i_ref_count = 0;
    conn = NULL;
}

#endif
