Merge pull request #5101 from FernetMenta/ffmpeg-threads
[vuplus_xbmc] / xbmc / cores / dvdplayer / DVDCodecs / Video / VDPAU.cpp
index adf7413..73c4fa4 100644 (file)
 #include "cores/VideoRenderers/RenderFlags.h"
 
 using namespace VDPAU;
-#define NUM_RENDER_PICS 9
+#define NUM_RENDER_PICS 7
+#define NUM_CROP_PIX 3
 
 #define ARSIZE(x) (sizeof(x) / sizeof((x)[0]))
 
+// settings codecs mapping
+DVDCodecAvailableType g_vdpau_available[] = {
+  { AV_CODEC_ID_H263, "videoplayer.usevdpaumpeg4" },
+  { AV_CODEC_ID_MPEG4, "videoplayer.usevdpaumpeg4" },
+  { AV_CODEC_ID_WMV3, "videoplayer.usevdpauvc1" },
+  { AV_CODEC_ID_VC1, "videoplayer.usevdpauvc1" },
+  { AV_CODEC_ID_MPEG2VIDEO, "videoplayer.usevdpaumpeg2" },
+};
+const size_t settings_count = sizeof(g_vdpau_available) / sizeof(DVDCodecAvailableType);
+
 CDecoder::Desc decoder_profiles[] = {
 {"MPEG1",        VDP_DECODER_PROFILE_MPEG1},
 {"MPEG2_SIMPLE", VDP_DECODER_PROFILE_MPEG2_SIMPLE},
@@ -52,9 +63,7 @@ CDecoder::Desc decoder_profiles[] = {
 {"VC1_SIMPLE",   VDP_DECODER_PROFILE_VC1_SIMPLE},
 {"VC1_MAIN",     VDP_DECODER_PROFILE_VC1_MAIN},
 {"VC1_ADVANCED", VDP_DECODER_PROFILE_VC1_ADVANCED},
-#ifdef VDP_DECODER_PROFILE_MPEG4_PART2_ASP
 {"MPEG4_PART2_ASP", VDP_DECODER_PROFILE_MPEG4_PART2_ASP},
-#endif
 };
 const size_t decoder_profile_count = sizeof(decoder_profiles)/sizeof(CDecoder::Desc);
 
@@ -74,10 +83,401 @@ static struct SInterlaceMapping
 static float studioCSCKCoeffs601[3] = {0.299, 0.587, 0.114}; //BT601 {Kr, Kg, Kb}
 static float studioCSCKCoeffs709[3] = {0.2126, 0.7152, 0.0722}; //BT709 {Kr, Kg, Kb}
 
-//since libvdpau 0.4, vdp_device_create_x11() installs a callback on the Display*,
-//if we unload libvdpau with dlclose(), we segfault on XCloseDisplay,
-//so we just keep a static handle to libvdpau around
-void* CDecoder::dl_handle;
+//-----------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
+
+CVDPAUContext *CVDPAUContext::m_context = 0;
+CCriticalSection CVDPAUContext::m_section;
+Display *CVDPAUContext::m_display = 0;
+void *CVDPAUContext::m_dlHandle = 0;
+
+CVDPAUContext::CVDPAUContext()
+{
+  m_context = 0;
+  m_refCount = 0;
+}
+
+void CVDPAUContext::Release()
+{
+  CSingleLock lock(m_section);
+
+  m_refCount--;
+  if (m_refCount <= 0)
+  {
+    Close();
+    delete this;
+    m_context = 0;
+  }
+}
+
+void CVDPAUContext::Close()
+{
+  CLog::Log(LOGNOTICE, "VDPAU::Close - closing decoder context");
+  DestroyContext();
+}
+
+bool CVDPAUContext::EnsureContext(CVDPAUContext **ctx)
+{
+  CSingleLock lock(m_section);
+
+  if (m_context)
+  {
+    m_context->m_refCount++;
+    *ctx = m_context;
+    return true;
+  }
+
+  m_context = new CVDPAUContext();
+  *ctx = m_context;
+  {
+    CSingleLock gLock(g_graphicsContext);
+    if (!m_context->LoadSymbols() || !m_context->CreateContext())
+    {
+      delete m_context;
+      m_context = 0;
+      *ctx = NULL;
+      return false;
+    }
+  }
+
+  m_context->m_refCount++;
+
+  *ctx = m_context;
+  return true;
+}
+
+VDPAU_procs& CVDPAUContext::GetProcs()
+{
+  return m_vdpProcs;
+}
+
+VdpVideoMixerFeature* CVDPAUContext::GetFeatures()
+{
+  return m_vdpFeatures;
+}
+
+int CVDPAUContext::GetFeatureCount()
+{
+  return m_featureCount;
+}
+
+bool CVDPAUContext::LoadSymbols()
+{
+  if (!m_dlHandle)
+  {
+    m_dlHandle  = dlopen("libvdpau.so.1", RTLD_LAZY);
+    if (!m_dlHandle)
+    {
+      const char* error = dlerror();
+      if (!error)
+        error = "dlerror() returned NULL";
+
+      CLog::Log(LOGERROR,"VDPAU::LoadSymbols: Unable to get handle to lib: %s", error);
+      return false;
+    }
+  }
+
+  char* error;
+  (void)dlerror();
+  dl_vdp_device_create_x11 = (VdpStatus (*)(Display*, int, VdpDevice*, VdpStatus (**)(VdpDevice, VdpFuncId, void**)))dlsym(m_dlHandle, (const char*)"vdp_device_create_x11");
+  error = dlerror();
+  if (error)
+  {
+    CLog::Log(LOGERROR,"(VDPAU) - %s in %s",error,__FUNCTION__);
+    m_vdpDevice = VDP_INVALID_HANDLE;
+    return false;
+  }
+  return true;
+}
+
+bool CVDPAUContext::CreateContext()
+{
+  CLog::Log(LOGNOTICE,"VDPAU::CreateContext - creating decoder context");
+
+  int mScreen;
+  { CSingleLock lock(g_graphicsContext);
+    if (!m_display)
+      m_display = XOpenDisplay(NULL);
+    mScreen = g_Windowing.GetCurrentScreen();
+  }
+
+  VdpStatus vdp_st;
+  // Create Device
+  vdp_st = dl_vdp_device_create_x11(m_display,
+                                    mScreen,
+                                   &m_vdpDevice,
+                                   &m_vdpProcs.vdp_get_proc_address);
+
+  CLog::Log(LOGNOTICE,"vdp_device = 0x%08x vdp_st = 0x%08x",m_vdpDevice,vdp_st);
+  if (vdp_st != VDP_STATUS_OK)
+  {
+    CLog::Log(LOGERROR,"(VDPAU) unable to init VDPAU - vdp_st = 0x%x.  Falling back.",vdp_st);
+    m_vdpDevice = VDP_INVALID_HANDLE;
+    return false;
+  }
+
+  QueryProcs();
+  SpewHardwareAvailable();
+  return true;
+}
+
+void CVDPAUContext::QueryProcs()
+{
+  VdpStatus vdp_st;
+
+#define VDP_PROC(id, proc) \
+  do { \
+    vdp_st = m_vdpProcs.vdp_get_proc_address(m_vdpDevice, id, (void**)&proc); \
+    if (vdp_st != VDP_STATUS_OK) \
+    { \
+      CLog::Log(LOGERROR, "CVDPAUContext::GetProcs - failed to get proc id"); \
+    } \
+  } while(0);
+
+  VDP_PROC(VDP_FUNC_ID_GET_ERROR_STRING                    , m_vdpProcs.vdp_get_error_string);
+  VDP_PROC(VDP_FUNC_ID_DEVICE_DESTROY                      , m_vdpProcs.vdp_device_destroy);
+  VDP_PROC(VDP_FUNC_ID_GENERATE_CSC_MATRIX                 , m_vdpProcs.vdp_generate_csc_matrix);
+  VDP_PROC(VDP_FUNC_ID_VIDEO_SURFACE_CREATE                , m_vdpProcs.vdp_video_surface_create);
+  VDP_PROC(VDP_FUNC_ID_VIDEO_SURFACE_DESTROY               , m_vdpProcs.vdp_video_surface_destroy);
+  VDP_PROC(VDP_FUNC_ID_VIDEO_SURFACE_PUT_BITS_Y_CB_CR      , m_vdpProcs.vdp_video_surface_put_bits_y_cb_cr);
+  VDP_PROC(VDP_FUNC_ID_VIDEO_SURFACE_GET_BITS_Y_CB_CR      , m_vdpProcs.vdp_video_surface_get_bits_y_cb_cr);
+  VDP_PROC(VDP_FUNC_ID_OUTPUT_SURFACE_PUT_BITS_Y_CB_CR     , m_vdpProcs.vdp_output_surface_put_bits_y_cb_cr);
+  VDP_PROC(VDP_FUNC_ID_OUTPUT_SURFACE_PUT_BITS_NATIVE      , m_vdpProcs.vdp_output_surface_put_bits_native);
+  VDP_PROC(VDP_FUNC_ID_OUTPUT_SURFACE_CREATE               , m_vdpProcs.vdp_output_surface_create);
+  VDP_PROC(VDP_FUNC_ID_OUTPUT_SURFACE_DESTROY              , m_vdpProcs.vdp_output_surface_destroy);
+  VDP_PROC(VDP_FUNC_ID_OUTPUT_SURFACE_GET_BITS_NATIVE      , m_vdpProcs.vdp_output_surface_get_bits_native);
+  VDP_PROC(VDP_FUNC_ID_OUTPUT_SURFACE_RENDER_OUTPUT_SURFACE, m_vdpProcs.vdp_output_surface_render_output_surface);
+  VDP_PROC(VDP_FUNC_ID_OUTPUT_SURFACE_PUT_BITS_INDEXED     , m_vdpProcs.vdp_output_surface_put_bits_indexed);
+  VDP_PROC(VDP_FUNC_ID_VIDEO_MIXER_CREATE                  , m_vdpProcs.vdp_video_mixer_create);
+  VDP_PROC(VDP_FUNC_ID_VIDEO_MIXER_SET_FEATURE_ENABLES     , m_vdpProcs.vdp_video_mixer_set_feature_enables);
+  VDP_PROC(VDP_FUNC_ID_VIDEO_MIXER_DESTROY                 , m_vdpProcs.vdp_video_mixer_destroy);
+  VDP_PROC(VDP_FUNC_ID_VIDEO_MIXER_RENDER                  , m_vdpProcs.vdp_video_mixer_render);
+  VDP_PROC(VDP_FUNC_ID_VIDEO_MIXER_SET_ATTRIBUTE_VALUES    , m_vdpProcs.vdp_video_mixer_set_attribute_values);
+  VDP_PROC(VDP_FUNC_ID_VIDEO_MIXER_QUERY_PARAMETER_SUPPORT , m_vdpProcs.vdp_video_mixer_query_parameter_support);
+  VDP_PROC(VDP_FUNC_ID_VIDEO_MIXER_QUERY_FEATURE_SUPPORT   , m_vdpProcs.vdp_video_mixer_query_feature_support);
+  VDP_PROC(VDP_FUNC_ID_DECODER_CREATE                      , m_vdpProcs.vdp_decoder_create);
+  VDP_PROC(VDP_FUNC_ID_DECODER_DESTROY                     , m_vdpProcs.vdp_decoder_destroy);
+  VDP_PROC(VDP_FUNC_ID_DECODER_RENDER                      , m_vdpProcs.vdp_decoder_render);
+  VDP_PROC(VDP_FUNC_ID_DECODER_QUERY_CAPABILITIES          , m_vdpProcs.vdp_decoder_query_caps);
+#undef VDP_PROC
+}
+
+VdpDevice CVDPAUContext::GetDevice()
+{
+  return m_vdpDevice;
+}
+
+void CVDPAUContext::DestroyContext()
+{
+  if (!m_vdpProcs.vdp_device_destroy)
+    return;
+
+  m_vdpProcs.vdp_device_destroy(m_vdpDevice);
+  m_vdpDevice = VDP_INVALID_HANDLE;
+}
+
+void CVDPAUContext::SpewHardwareAvailable()  //CopyrighVDPAUt (c) 2008 Wladimir J. van der Laan  -- VDPInfo
+{
+  VdpStatus rv;
+  CLog::Log(LOGNOTICE,"VDPAU Decoder capabilities:");
+  CLog::Log(LOGNOTICE,"name          level macbs width height");
+  CLog::Log(LOGNOTICE,"------------------------------------");
+  for(unsigned int x=0; x<decoder_profile_count; ++x)
+  {
+    VdpBool is_supported = false;
+    uint32_t max_level, max_macroblocks, max_width, max_height;
+    rv = m_vdpProcs.vdp_decoder_query_caps(m_vdpDevice, decoder_profiles[x].id,
+                                &is_supported, &max_level, &max_macroblocks, &max_width, &max_height);
+    if(rv == VDP_STATUS_OK && is_supported)
+    {
+      CLog::Log(LOGNOTICE,"%-16s %2i %5i %5i %5i\n", decoder_profiles[x].name,
+                max_level, max_macroblocks, max_width, max_height);
+    }
+  }
+  CLog::Log(LOGNOTICE,"------------------------------------");
+  m_featureCount = 0;
+#define CHECK_SUPPORT(feature)  \
+  do { \
+    VdpBool supported; \
+    if(m_vdpProcs.vdp_video_mixer_query_feature_support(m_vdpDevice, feature, &supported) == VDP_STATUS_OK && supported) { \
+      CLog::Log(LOGNOTICE, "Mixer feature: "#feature);  \
+      m_vdpFeatures[m_featureCount++] = feature; \
+    } \
+  } while(false)
+
+  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_NOISE_REDUCTION);
+  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_SHARPNESS);
+  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_DEINTERLACE_TEMPORAL);
+  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_DEINTERLACE_TEMPORAL_SPATIAL);
+  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_INVERSE_TELECINE);
+#ifdef VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L1
+  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L1);
+  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L2);
+  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L3);
+  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L4);
+  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L5);
+  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L6);
+  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L7);
+  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L8);
+  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L9);
+#endif
+#undef CHECK_SUPPORT
+}
+
+bool CVDPAUContext::Supports(VdpVideoMixerFeature feature)
+{
+  for(int i = 0; i < m_featureCount; i++)
+  {
+    if(m_vdpFeatures[i] == feature)
+      return true;
+  }
+  return false;
+}
+
+//-----------------------------------------------------------------------------
+// VDPAU Video Surface states
+//-----------------------------------------------------------------------------
+
+#define SURFACE_USED_FOR_REFERENCE 0x01
+#define SURFACE_USED_FOR_RENDER    0x02
+
+void CVideoSurfaces::AddSurface(VdpVideoSurface surf)
+{
+  CSingleLock lock(m_section);
+  m_state[surf] = SURFACE_USED_FOR_REFERENCE;
+}
+
+void CVideoSurfaces::ClearReference(VdpVideoSurface surf)
+{
+  CSingleLock lock(m_section);
+  if (m_state.find(surf) == m_state.end())
+  {
+    CLog::Log(LOGWARNING, "CVideoSurfaces::ClearReference - surface invalid");
+    return;
+  }
+  m_state[surf] &= ~SURFACE_USED_FOR_REFERENCE;
+  if (m_state[surf] == 0)
+  {
+    m_freeSurfaces.push_back(surf);
+  }
+}
+
+bool CVideoSurfaces::MarkRender(VdpVideoSurface surf)
+{
+  CSingleLock lock(m_section);
+  if (m_state.find(surf) == m_state.end())
+  {
+    CLog::Log(LOGWARNING, "CVideoSurfaces::MarkRender - surface invalid");
+    return false;
+  }
+  std::list<VdpVideoSurface>::iterator it;
+  it = std::find(m_freeSurfaces.begin(), m_freeSurfaces.end(), surf);
+  if (it != m_freeSurfaces.end())
+  {
+    m_freeSurfaces.erase(it);
+  }
+  m_state[surf] |= SURFACE_USED_FOR_RENDER;
+  return true;
+}
+
+void CVideoSurfaces::ClearRender(VdpVideoSurface surf)
+{
+  CSingleLock lock(m_section);
+  if (m_state.find(surf) == m_state.end())
+  {
+    CLog::Log(LOGWARNING, "CVideoSurfaces::ClearRender - surface invalid");
+    return;
+  }
+  m_state[surf] &= ~SURFACE_USED_FOR_RENDER;
+  if (m_state[surf] == 0)
+  {
+    m_freeSurfaces.push_back(surf);
+  }
+}
+
+bool CVideoSurfaces::IsValid(VdpVideoSurface surf)
+{
+  CSingleLock lock(m_section);
+  if (m_state.find(surf) != m_state.end())
+    return true;
+  else
+    return false;
+}
+
+VdpVideoSurface CVideoSurfaces::GetFree(VdpVideoSurface surf)
+{
+  CSingleLock lock(m_section);
+  if (m_state.find(surf) != m_state.end())
+  {
+    std::list<VdpVideoSurface>::iterator it;
+    it = std::find(m_freeSurfaces.begin(), m_freeSurfaces.end(), surf);
+    if (it == m_freeSurfaces.end())
+    {
+      CLog::Log(LOGWARNING, "CVideoSurfaces::GetFree - surface not free");
+    }
+    else
+    {
+      m_freeSurfaces.erase(it);
+      m_state[surf] = SURFACE_USED_FOR_REFERENCE;
+      return surf;
+    }
+  }
+
+  if (!m_freeSurfaces.empty())
+  {
+    VdpVideoSurface freeSurf = m_freeSurfaces.front();
+    m_freeSurfaces.pop_front();
+    m_state[freeSurf] = SURFACE_USED_FOR_REFERENCE;
+    return freeSurf;
+  }
+
+  return VDP_INVALID_HANDLE;
+}
+
+VdpVideoSurface CVideoSurfaces::GetAtIndex(int idx)
+{
+  if (idx >= m_state.size())
+    return VDP_INVALID_HANDLE;
+
+  std::map<VdpVideoSurface, int>::iterator it = m_state.begin();
+  for(int i = 0; i < idx; i++)
+    ++it;
+  return it->first;
+}
+
+VdpVideoSurface CVideoSurfaces::RemoveNext(bool skiprender)
+{
+  CSingleLock lock(m_section);
+  VdpVideoSurface surf;
+  std::map<VdpVideoSurface, int>::iterator it;
+  for(it = m_state.begin(); it != m_state.end(); ++it)
+  {
+    if (skiprender && it->second & SURFACE_USED_FOR_RENDER)
+      continue;
+    surf = it->first;
+    m_state.erase(surf);
+
+    std::list<VdpVideoSurface>::iterator it2;
+    it2 = std::find(m_freeSurfaces.begin(), m_freeSurfaces.end(), surf);
+    if (it2 != m_freeSurfaces.end())
+      m_freeSurfaces.erase(it2);
+    return surf;
+  }
+  return VDP_INVALID_HANDLE;
+}
+
+void CVideoSurfaces::Reset()
+{
+  CSingleLock lock(m_section);
+  m_freeSurfaces.clear();
+  m_state.clear();
+}
+
+int CVideoSurfaces::Size()
+{
+  CSingleLock lock(m_section);
+  return m_state.size();
+}
 
 //-----------------------------------------------------------------------------
 // CVDPAU
@@ -85,93 +485,114 @@ void* CDecoder::dl_handle;
 
 CDecoder::CDecoder() : m_vdpauOutput(&m_inMsgEvent)
 {
-  m_vdpauConfig.vdpDevice = VDP_INVALID_HANDLE;
   m_vdpauConfig.videoSurfaces = &m_videoSurfaces;
-  m_vdpauConfig.videoSurfaceSec = &m_videoSurfaceSec;
 
   m_vdpauConfigured = false;
   m_hwContext.bitstream_buffers_allocated = 0;
   m_DisplayState = VDPAU_OPEN;
+  m_vdpauConfig.context = 0;
 }
 
-bool CDecoder::Open(AVCodecContext* avctx, const enum PixelFormat, unsigned int surfaces)
+bool CDecoder::Open(AVCodecContext* avctx, const enum PixelFormat fmt, unsigned int surfaces)
 {
+  // check if user wants to decode this format with VDPAU
+  std::string gpuvendor = g_Windowing.GetRenderVendor();
+  std::transform(gpuvendor.begin(), gpuvendor.end(), gpuvendor.begin(), ::tolower);
+  // nvidia is whitelisted despite for mpeg-4 we need to query user settings
+  if ((gpuvendor.compare(0, 6, "nvidia") != 0)  || (avctx->codec_id == AV_CODEC_ID_MPEG4) || (avctx->codec_id == AV_CODEC_ID_H263))
+  {
+    if (CDVDVideoCodec::IsCodecDisabled(g_vdpau_available, settings_count, avctx->codec_id))
+      return false;
+  }
+
+#ifndef GL_NV_vdpau_interop
+  CLog::Log(LOGNOTICE, "VDPAU: compilation without required extension GL_NV_vdpau_interop");
+  return false;
+#endif
+  if (!g_Windowing.IsExtSupported("GL_NV_vdpau_interop"))
+  {
+    CLog::Log(LOGNOTICE, "VDPAU::Open: required extension GL_NV_vdpau_interop not found");
+    return false;
+  }
+
   if(avctx->coded_width  == 0
   || avctx->coded_height == 0)
   {
-    CLog::Log(LOGWARNING,"(VDPAU) no width/height available, can't init");
+    CLog::Log(LOGWARNING,"VDPAU::Open: no width/height available, can't init");
     return false;
   }
   m_vdpauConfig.numRenderBuffers = surfaces;
   m_decoderThread = CThread::GetCurrentThreadId();
 
-  if ((avctx->codec_id == AV_CODEC_ID_MPEG4) && !g_advancedSettings.m_videoAllowMpeg4VDPAU)
+  if (!CVDPAUContext::EnsureContext(&m_vdpauConfig.context))
     return false;
 
-  if (!dl_handle)
-  {
-    dl_handle  = dlopen("libvdpau.so.1", RTLD_LAZY);
-    if (!dl_handle)
-    {
-      const char* error = dlerror();
-      if (!error)
-        error = "dlerror() returned NULL";
-
-      CLog::Log(LOGNOTICE,"(VDPAU) Unable to get handle to libvdpau: %s", error);
-      return false;
-    }
-  }
+  m_DisplayState = VDPAU_OPEN;
+  m_vdpauConfigured = false;
 
   if (!m_dllAvUtil.Load())
     return false;
 
-  InitVDPAUProcs();
   m_presentPicture = 0;
 
-  if (m_vdpauConfig.vdpDevice != VDP_INVALID_HANDLE)
   {
-    SpewHardwareAvailable();
-
     VdpDecoderProfile profile = 0;
-    if(avctx->codec_id == AV_CODEC_ID_H264)
-      profile = VDP_DECODER_PROFILE_H264_HIGH;
-#ifdef VDP_DECODER_PROFILE_MPEG4_PART2_ASP
-    else if(avctx->codec_id == AV_CODEC_ID_MPEG4)
-      profile = VDP_DECODER_PROFILE_MPEG4_PART2_ASP;
-#endif
+
+    // convert FFMPEG codec ID to VDPAU profile.
+    ReadFormatOf(avctx->codec_id, profile, m_vdpauConfig.vdpChromaType);
     if(profile)
     {
+      VdpStatus vdp_st;
+      VdpBool is_supported = false;
+      uint32_t max_level, max_macroblocks, max_width, max_height;
+
+      // query device capabilities to ensure that VDPAU can handle the requested codec
+      vdp_st = m_vdpauConfig.context->GetProcs().vdp_decoder_query_caps(m_vdpauConfig.context->GetDevice(),
+               profile, &is_supported, &max_level, &max_macroblocks, &max_width, &max_height);
+
+      // test to make sure there is a possibility the codec will work
+      if (CheckStatus(vdp_st, __LINE__))
+      {
+        CLog::Log(LOGERROR, "VDPAU::Open: error %s(%d) checking for decoder support", m_vdpauConfig.context->GetProcs().vdp_get_error_string(vdp_st), vdp_st);
+        return false;
+      }
+
+      if (max_width < avctx->coded_width || max_height < avctx->coded_height)
+      {
+        CLog::Log(LOGWARNING,"VDPAU::Open: requested picture dimensions (%i, %i) exceed hardware capabilities ( %i, %i).",
+                             avctx->coded_width, avctx->coded_height, max_width, max_height);
+        return false;
+      }
+
       if (!CDVDCodecUtils::IsVP3CompatibleWidth(avctx->coded_width))
-        CLog::Log(LOGWARNING,"(VDPAU) width %i might not be supported because of hardware bug", avctx->width);
+        CLog::Log(LOGWARNING,"VDPAU::Open width %i might not be supported because of hardware bug", avctx->width);
    
-      /* attempt to create a decoder with this width/height, some sizes are not supported by hw */
-      VdpStatus vdp_st;
-      vdp_st = m_vdpauConfig.vdpProcs.vdp_decoder_create(m_vdpauConfig.vdpDevice, profile, avctx->coded_width, avctx->coded_height, 5, &m_vdpauConfig.vdpDecoder);
+      // attempt to create a decoder with this width/height, some sizes are not supported by hw
+      vdp_st = m_vdpauConfig.context->GetProcs().vdp_decoder_create(m_vdpauConfig.context->GetDevice(), profile, avctx->coded_width, avctx->coded_height, 5, &m_vdpauConfig.vdpDecoder);
 
-      if(vdp_st != VDP_STATUS_OK)
+      if (CheckStatus(vdp_st, __LINE__))
       {
-        CLog::Log(LOGERROR, " (VDPAU) Error: %s(%d) checking for decoder support\n", m_vdpauConfig.vdpProcs.vdp_get_error_string(vdp_st), vdp_st);
-        FiniVDPAUProcs();
+        CLog::Log(LOGERROR, "VDPAU::Open: error: %s(%d) checking for decoder support", m_vdpauConfig.context->GetProcs().vdp_get_error_string(vdp_st), vdp_st);
         return false;
       }
 
-      m_vdpauConfig.vdpProcs.vdp_decoder_destroy(m_vdpauConfig.vdpDecoder);
+      m_vdpauConfig.context->GetProcs().vdp_decoder_destroy(m_vdpauConfig.vdpDecoder);
       CheckStatus(vdp_st, __LINE__);
-    }
-
-    /* finally setup ffmpeg */
-    memset(&m_hwContext, 0, sizeof(AVVDPAUContext));
-    m_hwContext.render = CDecoder::Render;
-    m_hwContext.bitstream_buffers_allocated = 0;
-    avctx->get_buffer      = CDecoder::FFGetBuffer;
-    avctx->release_buffer  = CDecoder::FFReleaseBuffer;
-    avctx->draw_horiz_band = CDecoder::FFDrawSlice;
-    avctx->slice_flags=SLICE_FLAG_CODED_ORDER|SLICE_FLAG_ALLOW_FIELD;
-    avctx->hwaccel_context = &m_hwContext;
-    avctx->thread_count    = 1;
 
-    g_Windowing.Register(this);
-    return true;
+      // finally setup ffmpeg
+      memset(&m_hwContext, 0, sizeof(AVVDPAUContext));
+      m_hwContext.render = CDecoder::Render;
+      m_hwContext.bitstream_buffers_allocated = 0;
+      avctx->get_buffer      = CDecoder::FFGetBuffer;
+      avctx->reget_buffer    = CDecoder::FFGetBuffer;
+      avctx->release_buffer  = CDecoder::FFReleaseBuffer;
+      avctx->draw_horiz_band = CDecoder::FFDrawSlice;
+      avctx->slice_flags=SLICE_FLAG_CODED_ORDER|SLICE_FLAG_ALLOW_FIELD;
+      avctx->hwaccel_context = &m_hwContext;
+
+      g_Windowing.Register(this);
+      return true;
+    }
   }
   return false;
 }
@@ -190,25 +611,18 @@ void CDecoder::Close()
   CSingleLock lock(m_DecoderSection);
 
   FiniVDPAUOutput();
-  FiniVDPAUProcs();
   m_vdpauOutput.Dispose();
 
-  while (!m_videoSurfaces.empty())
-  {
-    vdpau_render_state *render = m_videoSurfaces.back();
-    m_videoSurfaces.pop_back();
-    if (render->bitstream_buffers_allocated)
-      m_dllAvUtil.av_freep(&render->bitstream_buffers);
-    render->bitstream_buffers_allocated = 0;
-    free(render);
-  }
-
   if (m_hwContext.bitstream_buffers_allocated)
   {
     m_dllAvUtil.av_freep(&m_hwContext.bitstream_buffers);
   }
 
   m_dllAvUtil.Unload();
+
+  if (m_vdpauConfig.context)
+    m_vdpauConfig.context->Release();
+  m_vdpauConfig.context = 0;
 }
 
 long CDecoder::Release()
@@ -239,14 +653,10 @@ long CDecoder::Release()
       m_DisplayState = VDPAU_ERROR;
     }
 
-    for(unsigned int i = 0; i < m_videoSurfaces.size(); ++i)
+    VdpVideoSurface surf;
+    while((surf = m_videoSurfaces.RemoveNext(true)) != VDP_INVALID_HANDLE)
     {
-      vdpau_render_state *render = m_videoSurfaces[i];
-      if (render->surface != VDP_INVALID_HANDLE && !(render->state & FF_VDPAU_STATE_USED_FOR_RENDER))
-      {
-        m_vdpauConfig.vdpProcs.vdp_video_surface_destroy(render->surface);
-        render->surface = VDP_INVALID_HANDLE;
-      }
+      m_vdpauConfig.context->GetProcs().vdp_video_surface_destroy(surf);
     }
   }
   return IHardwareDecoder::Release();
@@ -289,19 +699,27 @@ void CDecoder::OnLostDevice()
 {
   CLog::Log(LOGNOTICE,"CVDPAU::OnLostDevice event");
 
+  int count = g_graphicsContext.exit();
+
   CSingleLock lock(m_DecoderSection);
   FiniVDPAUOutput();
-  FiniVDPAUProcs();
+  if (m_vdpauConfig.context)
+    m_vdpauConfig.context->Release();
+  m_vdpauConfig.context = 0;
 
   m_DisplayState = VDPAU_LOST;
   lock.Leave();
   m_DisplayEvent.Reset();
+
+  g_graphicsContext.restore(count);
 }
 
 void CDecoder::OnResetDevice()
 {
   CLog::Log(LOGNOTICE,"CVDPAU::OnResetDevice event");
 
+  int count = g_graphicsContext.exit();
+
   CSingleLock lock(m_DecoderSection);
   if (m_DisplayState == VDPAU_LOST)
   {
@@ -309,6 +727,8 @@ void CDecoder::OnResetDevice()
     lock.Leave();
     m_DisplayEvent.Set();
   }
+
+  g_graphicsContext.restore(count);
 }
 
 int CDecoder::Check(AVCodecContext* avctx)
@@ -322,7 +742,7 @@ int CDecoder::Check(AVCodecContext* avctx)
   if (state == VDPAU_LOST)
   {
     CLog::Log(LOGNOTICE,"CVDPAU::Check waiting for display reset event");
-    if (!m_DisplayEvent.WaitMSec(2000))
+    if (!m_DisplayEvent.WaitMSec(4000))
     {
       CLog::Log(LOGERROR, "CVDPAU::Check - device didn't reset in reasonable time");
       state = VDPAU_RESET;
@@ -338,9 +758,15 @@ int CDecoder::Check(AVCodecContext* avctx)
     CSingleLock lock(m_DecoderSection);
 
     FiniVDPAUOutput();
-    FiniVDPAUProcs();
+    if (m_vdpauConfig.context)
+      m_vdpauConfig.context->Release();
+    m_vdpauConfig.context = 0;
 
-    InitVDPAUProcs();
+    if (CVDPAUContext::EnsureContext(&m_vdpauConfig.context))
+    {
+      m_DisplayState = VDPAU_OPEN;
+      m_vdpauConfigured = false;
+    }
 
     if (state == VDPAU_RESET)
       return VC_FLUSHED;
@@ -360,12 +786,7 @@ bool CDecoder::IsVDPAUFormat(PixelFormat format)
 
 bool CDecoder::Supports(VdpVideoMixerFeature feature)
 {
-  for(int i = 0; i < m_vdpauConfig.featureCount; i++)
-  {
-    if(m_vdpauConfig.vdpFeatures[i] == feature)
-      return true;
-  }
-  return false;
+  return m_vdpauConfig.context->Supports(feature);
 }
 
 bool CDecoder::Supports(EINTERLACEMETHOD method)
@@ -374,11 +795,8 @@ bool CDecoder::Supports(EINTERLACEMETHOD method)
   || method == VS_INTERLACEMETHOD_AUTO)
     return true;
 
-  if (!m_vdpauConfig.usePixmaps)
-  {
-    if (method == VS_INTERLACEMETHOD_RENDER_BOB)
-      return true;
-  }
+  if (method == VS_INTERLACEMETHOD_RENDER_BOB)
+    return true;
 
   if (method == VS_INTERLACEMETHOD_VDPAU_INVERSE_TELECINE)
     return false;
@@ -396,102 +814,10 @@ EINTERLACEMETHOD CDecoder::AutoInterlaceMethod()
   return VS_INTERLACEMETHOD_RENDER_BOB;
 }
 
-void CDecoder::InitVDPAUProcs()
-{
-  char* error;
-
-  (void)dlerror();
-  dl_vdp_device_create_x11 = (VdpStatus (*)(Display*, int, VdpDevice*, VdpStatus (**)(VdpDevice, VdpFuncId, void**)))dlsym(dl_handle, (const char*)"vdp_device_create_x11");
-  error = dlerror();
-  if (error)
-  {
-    CLog::Log(LOGERROR,"(VDPAU) - %s in %s",error,__FUNCTION__);
-    m_vdpauConfig.vdpDevice = VDP_INVALID_HANDLE;
-    return;
-  }
-
-  if (dl_vdp_device_create_x11)
-  {
-    m_Display = XOpenDisplay(NULL);
-  }
-
-  int mScreen = g_Windowing.GetCurrentScreen();
-  VdpStatus vdp_st;
-
-  // Create Device
-  vdp_st = dl_vdp_device_create_x11(m_Display, //x_display,
-                                 mScreen, //x_screen,
-                                 &m_vdpauConfig.vdpDevice,
-                                 &m_vdpauConfig.vdpProcs.vdp_get_proc_address);
-
-  CLog::Log(LOGNOTICE,"vdp_device = 0x%08x vdp_st = 0x%08x",m_vdpauConfig.vdpDevice,vdp_st);
-  if (vdp_st != VDP_STATUS_OK)
-  {
-    CLog::Log(LOGERROR,"(VDPAU) unable to init VDPAU - vdp_st = 0x%x.  Falling back.",vdp_st);
-    m_vdpauConfig.vdpDevice = VDP_INVALID_HANDLE;
-    return;
-  }
-
-#define VDP_PROC(id, proc) \
-  do { \
-    vdp_st = m_vdpauConfig.vdpProcs.vdp_get_proc_address(m_vdpauConfig.vdpDevice, id, (void**)&proc); \
-    CheckStatus(vdp_st, __LINE__); \
-  } while(0);
-
-  VDP_PROC(VDP_FUNC_ID_GET_ERROR_STRING                    , m_vdpauConfig.vdpProcs.vdp_get_error_string);
-  VDP_PROC(VDP_FUNC_ID_DEVICE_DESTROY                      , m_vdpauConfig.vdpProcs.vdp_device_destroy);
-  VDP_PROC(VDP_FUNC_ID_GENERATE_CSC_MATRIX                 , m_vdpauConfig.vdpProcs.vdp_generate_csc_matrix);
-  VDP_PROC(VDP_FUNC_ID_VIDEO_SURFACE_CREATE                , m_vdpauConfig.vdpProcs.vdp_video_surface_create);
-  VDP_PROC(VDP_FUNC_ID_VIDEO_SURFACE_DESTROY               , m_vdpauConfig.vdpProcs.vdp_video_surface_destroy);
-  VDP_PROC(VDP_FUNC_ID_VIDEO_SURFACE_PUT_BITS_Y_CB_CR      , m_vdpauConfig.vdpProcs.vdp_video_surface_put_bits_y_cb_cr);
-  VDP_PROC(VDP_FUNC_ID_VIDEO_SURFACE_GET_BITS_Y_CB_CR      , m_vdpauConfig.vdpProcs.vdp_video_surface_get_bits_y_cb_cr);
-  VDP_PROC(VDP_FUNC_ID_OUTPUT_SURFACE_PUT_BITS_Y_CB_CR     , m_vdpauConfig.vdpProcs.vdp_output_surface_put_bits_y_cb_cr);
-  VDP_PROC(VDP_FUNC_ID_OUTPUT_SURFACE_PUT_BITS_NATIVE      , m_vdpauConfig.vdpProcs.vdp_output_surface_put_bits_native);
-  VDP_PROC(VDP_FUNC_ID_OUTPUT_SURFACE_CREATE               , m_vdpauConfig.vdpProcs.vdp_output_surface_create);
-  VDP_PROC(VDP_FUNC_ID_OUTPUT_SURFACE_DESTROY              , m_vdpauConfig.vdpProcs.vdp_output_surface_destroy);
-  VDP_PROC(VDP_FUNC_ID_OUTPUT_SURFACE_GET_BITS_NATIVE      , m_vdpauConfig.vdpProcs.vdp_output_surface_get_bits_native);
-  VDP_PROC(VDP_FUNC_ID_OUTPUT_SURFACE_RENDER_OUTPUT_SURFACE, m_vdpauConfig.vdpProcs.vdp_output_surface_render_output_surface);
-  VDP_PROC(VDP_FUNC_ID_OUTPUT_SURFACE_PUT_BITS_INDEXED     , m_vdpauConfig.vdpProcs.vdp_output_surface_put_bits_indexed);
-  VDP_PROC(VDP_FUNC_ID_VIDEO_MIXER_CREATE                  , m_vdpauConfig.vdpProcs.vdp_video_mixer_create);
-  VDP_PROC(VDP_FUNC_ID_VIDEO_MIXER_SET_FEATURE_ENABLES     , m_vdpauConfig.vdpProcs.vdp_video_mixer_set_feature_enables);
-  VDP_PROC(VDP_FUNC_ID_VIDEO_MIXER_DESTROY                 , m_vdpauConfig.vdpProcs.vdp_video_mixer_destroy);
-  VDP_PROC(VDP_FUNC_ID_VIDEO_MIXER_RENDER                  , m_vdpauConfig.vdpProcs.vdp_video_mixer_render);
-  VDP_PROC(VDP_FUNC_ID_VIDEO_MIXER_SET_ATTRIBUTE_VALUES    , m_vdpauConfig.vdpProcs.vdp_video_mixer_set_attribute_values);
-  VDP_PROC(VDP_FUNC_ID_VIDEO_MIXER_QUERY_PARAMETER_SUPPORT , m_vdpauConfig.vdpProcs.vdp_video_mixer_query_parameter_support);
-  VDP_PROC(VDP_FUNC_ID_VIDEO_MIXER_QUERY_FEATURE_SUPPORT   , m_vdpauConfig.vdpProcs.vdp_video_mixer_query_feature_support);
-  VDP_PROC(VDP_FUNC_ID_DECODER_CREATE                      , m_vdpauConfig.vdpProcs.vdp_decoder_create);
-  VDP_PROC(VDP_FUNC_ID_DECODER_DESTROY                     , m_vdpauConfig.vdpProcs.vdp_decoder_destroy);
-  VDP_PROC(VDP_FUNC_ID_DECODER_RENDER                      , m_vdpauConfig.vdpProcs.vdp_decoder_render);
-  VDP_PROC(VDP_FUNC_ID_DECODER_QUERY_CAPABILITIES          , m_vdpauConfig.vdpProcs.vdp_decoder_query_caps);
-  VDP_PROC(VDP_FUNC_ID_PRESENTATION_QUEUE_TARGET_DESTROY          , m_vdpauConfig.vdpProcs.vdp_presentation_queue_target_destroy);
-  VDP_PROC(VDP_FUNC_ID_PRESENTATION_QUEUE_CREATE                  , m_vdpauConfig.vdpProcs.vdp_presentation_queue_create);
-  VDP_PROC(VDP_FUNC_ID_PRESENTATION_QUEUE_DESTROY                 , m_vdpauConfig.vdpProcs.vdp_presentation_queue_destroy);
-  VDP_PROC(VDP_FUNC_ID_PRESENTATION_QUEUE_DISPLAY                 , m_vdpauConfig.vdpProcs.vdp_presentation_queue_display);
-  VDP_PROC(VDP_FUNC_ID_PRESENTATION_QUEUE_BLOCK_UNTIL_SURFACE_IDLE, m_vdpauConfig.vdpProcs.vdp_presentation_queue_block_until_surface_idle);
-  VDP_PROC(VDP_FUNC_ID_PRESENTATION_QUEUE_TARGET_CREATE_X11       , m_vdpauConfig.vdpProcs.vdp_presentation_queue_target_create_x11);
-  VDP_PROC(VDP_FUNC_ID_PRESENTATION_QUEUE_QUERY_SURFACE_STATUS    , m_vdpauConfig.vdpProcs.vdp_presentation_queue_query_surface_status);
-  VDP_PROC(VDP_FUNC_ID_PRESENTATION_QUEUE_GET_TIME                , m_vdpauConfig.vdpProcs.vdp_presentation_queue_get_time);
-
-#undef VDP_PROC
-
-  // set all vdpau resources to invalid
-  m_DisplayState = VDPAU_OPEN;
-  m_vdpauConfigured = false;
-}
-
-void CDecoder::FiniVDPAUProcs()
-{
-  if (m_vdpauConfig.vdpDevice == VDP_INVALID_HANDLE) return;
-
-  VdpStatus vdp_st;
-  vdp_st = m_vdpauConfig.vdpProcs.vdp_device_destroy(m_vdpauConfig.vdpDevice);
-  CheckStatus(vdp_st, __LINE__);
-  m_vdpauConfig.vdpDevice = VDP_INVALID_HANDLE;
-}
-
 void CDecoder::FiniVDPAUOutput()
 {
-  if (m_vdpauConfig.vdpDevice == VDP_INVALID_HANDLE || !m_vdpauConfigured) return;
+  if (!m_vdpauConfigured)
+    return;
 
   CLog::Log(LOGNOTICE, " (VDPAU) %s", __FUNCTION__);
 
@@ -501,25 +827,21 @@ void CDecoder::FiniVDPAUOutput()
 
   VdpStatus vdp_st;
 
-  vdp_st = m_vdpauConfig.vdpProcs.vdp_decoder_destroy(m_vdpauConfig.vdpDecoder);
+  vdp_st = m_vdpauConfig.context->GetProcs().vdp_decoder_destroy(m_vdpauConfig.vdpDecoder);
   if (CheckStatus(vdp_st, __LINE__))
     return;
   m_vdpauConfig.vdpDecoder = VDP_INVALID_HANDLE;
 
-  CSingleLock lock(m_videoSurfaceSec);
-  CLog::Log(LOGDEBUG, "CVDPAU::FiniVDPAUOutput destroying %d video surfaces", (int)m_videoSurfaces.size());
+  CLog::Log(LOGDEBUG, "CVDPAU::FiniVDPAUOutput destroying %d video surfaces", m_videoSurfaces.Size());
 
-  for(unsigned int i = 0; i < m_videoSurfaces.size(); ++i)
+  VdpVideoSurface surf;
+  while((surf = m_videoSurfaces.RemoveNext()) != VDP_INVALID_HANDLE)
   {
-    vdpau_render_state *render = m_videoSurfaces[i];
-    if (render->surface != VDP_INVALID_HANDLE)
-    {
-      vdp_st = m_vdpauConfig.vdpProcs.vdp_video_surface_destroy(render->surface);
-      render->surface = VDP_INVALID_HANDLE;
-    }
+    m_vdpauConfig.context->GetProcs().vdp_video_surface_destroy(surf);
     if (CheckStatus(vdp_st, __LINE__))
       return;
   }
+  m_videoSurfaces.Reset();
 }
 
 void CDecoder::ReadFormatOf( AVCodecID codec
@@ -587,7 +909,7 @@ bool CDecoder::ConfigVDPAU(AVCodecContext* avctx, int ref_frames)
   else
     m_vdpauConfig.maxReferences = 2;
 
-  vdp_st = m_vdpauConfig.vdpProcs.vdp_decoder_create(m_vdpauConfig.vdpDevice,
+  vdp_st = m_vdpauConfig.context->GetProcs().vdp_decoder_create(m_vdpauConfig.context->GetDevice(),
                               vdp_decoder_profile,
                               m_vdpauConfig.surfaceWidth,
                               m_vdpauConfig.surfaceHeight,
@@ -610,15 +932,6 @@ bool CDecoder::ConfigVDPAU(AVCodecContext* avctx, int ref_frames)
                                                  sizeof(m_vdpauConfig)))
   {
     bool success = reply->signal == COutputControlProtocol::ACC ? true : false;
-    if (success)
-    {
-      CVdpauConfig *data;
-      data = (CVdpauConfig*)reply->data;
-      if (data)
-      {
-        m_vdpauConfig.usePixmaps = data->usePixmaps;
-      }
-    }
     reply->Release();
     if (!success)
     {
@@ -636,82 +949,7 @@ bool CDecoder::ConfigVDPAU(AVCodecContext* avctx, int ref_frames)
 
   m_inMsgEvent.Reset();
   m_vdpauConfigured = true;
-  return true;
-}
-
-void CDecoder::SpewHardwareAvailable()  //CopyrighVDPAUt (c) 2008 Wladimir J. van der Laan  -- VDPInfo
-{
-  VdpStatus rv;
-  CLog::Log(LOGNOTICE,"VDPAU Decoder capabilities:");
-  CLog::Log(LOGNOTICE,"name          level macbs width height");
-  CLog::Log(LOGNOTICE,"------------------------------------");
-  for(unsigned int x=0; x<decoder_profile_count; ++x)
-  {
-    VdpBool is_supported = false;
-    uint32_t max_level, max_macroblocks, max_width, max_height;
-    rv = m_vdpauConfig.vdpProcs.vdp_decoder_query_caps(m_vdpauConfig.vdpDevice, decoder_profiles[x].id,
-                                &is_supported, &max_level, &max_macroblocks, &max_width, &max_height);
-    if(rv == VDP_STATUS_OK && is_supported)
-    {
-      CLog::Log(LOGNOTICE,"%-16s %2i %5i %5i %5i\n", decoder_profiles[x].name,
-                max_level, max_macroblocks, max_width, max_height);
-    }
-  }
-  CLog::Log(LOGNOTICE,"------------------------------------");
-  m_vdpauConfig.featureCount = 0;
-#define CHECK_SUPPORT(feature)  \
-  do { \
-    VdpBool supported; \
-    if(m_vdpauConfig.vdpProcs.vdp_video_mixer_query_feature_support(m_vdpauConfig.vdpDevice, feature, &supported) == VDP_STATUS_OK && supported) { \
-      CLog::Log(LOGNOTICE, "Mixer feature: "#feature);  \
-      m_vdpauConfig.vdpFeatures[m_vdpauConfig.featureCount++] = feature; \
-    } \
-  } while(false)
-
-  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_NOISE_REDUCTION);
-  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_SHARPNESS);
-  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_DEINTERLACE_TEMPORAL);
-  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_DEINTERLACE_TEMPORAL_SPATIAL);
-  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_INVERSE_TELECINE);
-#ifdef VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L1
-  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L1);
-  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L2);
-  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L3);
-  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L4);
-  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L5);
-  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L6);
-  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L7);
-  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L8);
-  CHECK_SUPPORT(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L9);
-#endif
-#undef CHECK_SUPPORT
-
-}
-
-bool CDecoder::IsSurfaceValid(vdpau_render_state *render)
-{
-  // find render state in queue
-  bool found(false);
-  unsigned int i;
-  for(i = 0; i < m_videoSurfaces.size(); ++i)
-  {
-    if(m_videoSurfaces[i] == render)
-    {
-      found = true;
-      break;
-    }
-  }
-  if (!found)
-  {
-    CLog::Log(LOGERROR,"%s - video surface not found", __FUNCTION__);
-    return false;
-  }
-  if (m_videoSurfaces[i]->surface == VDP_INVALID_HANDLE)
-  {
-    m_videoSurfaces[i]->state = 0;
-    return false;
-  }
-
+  m_ErrorCount = 0;
   return true;
 }
 
@@ -730,98 +968,58 @@ int CDecoder::FFGetBuffer(AVCodecContext *avctx, AVFrame *pic)
     return -1;
   }
 
-  vdpau_render_state * render = NULL;
-
-  // find unused surface
-  { CSingleLock lock(vdp->m_videoSurfaceSec);
-    for(unsigned int i = 0; i < vdp->m_videoSurfaces.size(); i++)
-    {
-      if(!(vdp->m_videoSurfaces[i]->state & (FF_VDPAU_STATE_USED_FOR_REFERENCE | FF_VDPAU_STATE_USED_FOR_RENDER)))
-      {
-        render = vdp->m_videoSurfaces[i];
-        render->state = 0;
-        break;
-      }
-    }
-  }
+  VdpVideoSurface surf = (VdpVideoSurface)(uintptr_t)pic->data[3];
+  surf = vdp->m_videoSurfaces.GetFree(surf != 0 ? surf : VDP_INVALID_HANDLE);
 
   VdpStatus vdp_st = VDP_STATUS_ERROR;
-  if (render == NULL)
+  if (surf == VDP_INVALID_HANDLE)
   {
     // create a new surface
     VdpDecoderProfile profile;
     ReadFormatOf(avctx->codec_id, profile, vdp->m_vdpauConfig.vdpChromaType);
-    render = (vdpau_render_state*)calloc(sizeof(vdpau_render_state), 1);
-    if (render == NULL)
-    {
-      CLog::Log(LOGWARNING, "CVDPAU::FFGetBuffer - calloc failed");
-      return -1;
-    }
-    CSingleLock lock(vdp->m_videoSurfaceSec);
-    render->surface = VDP_INVALID_HANDLE;
-    vdp->m_videoSurfaces.push_back(render);
-  }
 
-  if (render->surface == VDP_INVALID_HANDLE)
-  {
-    vdp_st = vdp->m_vdpauConfig.vdpProcs.vdp_video_surface_create(vdp->m_vdpauConfig.vdpDevice,
+    vdp_st = vdp->m_vdpauConfig.context->GetProcs().vdp_video_surface_create(vdp->m_vdpauConfig.context->GetDevice(),
                                          vdp->m_vdpauConfig.vdpChromaType,
                                          avctx->coded_width,
                                          avctx->coded_height,
-                                         &render->surface);
+                                         &surf);
     vdp->CheckStatus(vdp_st, __LINE__);
     if (vdp_st != VDP_STATUS_OK)
     {
-      free(render);
       CLog::Log(LOGERROR, "CVDPAU::FFGetBuffer - No Video surface available could be created");
       return -1;
     }
+    vdp->m_videoSurfaces.AddSurface(surf);
   }
 
   pic->data[1] = pic->data[2] = NULL;
-  pic->data[0] = (uint8_t*)render;
-  pic->data[3] = (uint8_t*)(uintptr_t)render->surface;
+  pic->data[0] = (uint8_t*)(uintptr_t)surf;
+  pic->data[3] = (uint8_t*)(uintptr_t)surf;
 
   pic->linesize[0] = pic->linesize[1] =  pic->linesize[2] = 0;
 
   pic->type= FF_BUFFER_TYPE_USER;
 
-  render->state |= FF_VDPAU_STATE_USED_FOR_REFERENCE;
   pic->reordered_opaque= avctx->reordered_opaque;
   return 0;
 }
 
 void CDecoder::FFReleaseBuffer(AVCodecContext *avctx, AVFrame *pic)
 {
-  //CLog::Log(LOGNOTICE,"%s",__FUNCTION__);
   CDVDVideoCodecFFmpeg* ctx        = (CDVDVideoCodecFFmpeg*)avctx->opaque;
   CDecoder*             vdp        = (CDecoder*)ctx->GetHardware();
 
-  vdpau_render_state  * render;
+  VdpVideoSurface surf;
   unsigned int i;
 
   CSingleLock lock(vdp->m_DecoderSection);
 
-  render=(vdpau_render_state*)pic->data[0];
-  if(!render)
-  {
-    CLog::Log(LOGERROR, "CVDPAU::FFReleaseBuffer - invalid context handle provided");
-    return;
-  }
+  surf = (VdpVideoSurface)(uintptr_t)pic->data[3];
+
+  vdp->m_videoSurfaces.ClearReference(surf);
 
-  CSingleLock vLock(vdp->m_videoSurfaceSec);
-  render->state &= ~FF_VDPAU_STATE_USED_FOR_REFERENCE;
   for(i=0; i<4; i++)
     pic->data[i]= NULL;
-
-  // find render state in queue
-  if (!vdp->IsSurfaceValid(render))
-  {
-    CLog::Log(LOGDEBUG, "CVDPAU::FFReleaseBuffer - ignoring invalid buffer");
-    return;
-  }
-
-  render->state &= ~FF_VDPAU_STATE_USED_FOR_REFERENCE;
 }
 
 VdpStatus CDecoder::Render( VdpDecoder decoder, VdpVideoSurface target,
@@ -853,17 +1051,10 @@ void CDecoder::FFDrawSlice(struct AVCodecContext *s,
   }
 
   VdpStatus vdp_st;
-  vdpau_render_state * render;
-
-  render = (vdpau_render_state*)src->data[0];
-  if(!render)
-  {
-    CLog::Log(LOGERROR, "CVDPAU::FFDrawSlice - invalid context handle provided");
-    return;
-  }
+  VdpVideoSurface surf = (VdpVideoSurface)(uintptr_t)src->data[3];
 
   // ffmpeg vc-1 decoder does not flush, make sure the data buffer is still valid
-  if (!vdp->IsSurfaceValid(render))
+  if (!vdp->m_videoSurfaces.IsValid(surf))
   {
     CLog::Log(LOGWARNING, "CVDPAU::FFDrawSlice - ignoring invalid buffer");
     return;
@@ -881,19 +1072,22 @@ void CDecoder::FFDrawSlice(struct AVCodecContext *s,
       return;
   }
 
-//  uint64_t startTime = CurrentHostCounter();
+  uint64_t startTime = CurrentHostCounter();
   uint16_t decoded, processed, rend;
   vdp->m_bufferStats.Get(decoded, processed, rend);
-  vdp_st = vdp->m_vdpauConfig.vdpProcs.vdp_decoder_render(vdp->m_vdpauConfig.vdpDecoder,
-                                   render->surface,
+  vdp_st = vdp->m_vdpauConfig.context->GetProcs().vdp_decoder_render(vdp->m_vdpauConfig.vdpDecoder,
+                                   surf,
                                    (VdpPictureInfo const *)&(vdp->m_hwContext.info),
                                    vdp->m_hwContext.bitstream_buffers_used,
                                    vdp->m_hwContext.bitstream_buffers);
-  vdp->CheckStatus(vdp_st, __LINE__);
-//  uint64_t diff = CurrentHostCounter() - startTime;
-//  if (diff*1000/CurrentHostFrequency() > 30)
-//    CLog::Log(LOGWARNING,"CVDPAU::DrawSlice - VdpDecoderRender long decoding: %d ms, dec: %d, proc: %d, rend: %d", (int)((diff*1000)/CurrentHostFrequency()), decoded, processed, rend);
+  if (vdp->CheckStatus(vdp_st, __LINE__))
+    vdp->m_DecoderError = true;
+  else
+    vdp->m_DecoderError = false;
 
+  uint64_t diff = CurrentHostCounter() - startTime;
+  if (diff*1000/CurrentHostFrequency() > 30)
+    CLog::Log(LOGDEBUG, "CVDPAU::DrawSlice - VdpDecoderRender long decoding: %d ms, dec: %d, proc: %d, rend: %d", (int)((diff*1000)/CurrentHostFrequency()), decoded, processed, rend);
 }
 
 
@@ -905,35 +1099,29 @@ int CDecoder::Decode(AVCodecContext *avctx, AVFrame *pFrame)
 
   CSingleLock lock(m_DecoderSection);
 
+  if (m_DecoderError && pFrame)
+    return VC_ERROR;
+
   if (!m_vdpauConfigured)
     return VC_ERROR;
 
   if(pFrame)
   { // we have a new frame from decoder
 
-    vdpau_render_state * render = (vdpau_render_state*)pFrame->data[0];
-    if(!render)
-    {
-      CLog::Log(LOGERROR, "CVDPAU::Decode: no valid frame");
-      return VC_ERROR;
-    }
-
+    VdpVideoSurface surf = (VdpVideoSurface)(uintptr_t)pFrame->data[3];
     // ffmpeg vc-1 decoder does not flush, make sure the data buffer is still valid
-    if (!IsSurfaceValid(render))
+    if (!m_videoSurfaces.IsValid(surf))
     {
       CLog::Log(LOGWARNING, "CVDPAU::Decode - ignoring invalid buffer");
       return VC_BUFFER;
     }
-
-    CSingleLock lock(m_videoSurfaceSec);
-    render->state |= FF_VDPAU_STATE_USED_FOR_RENDER;
-    lock.Leave();
+    m_videoSurfaces.MarkRender(surf);
 
     // send frame to output for processing
     CVdpauDecodedPicture pic;
     memset(&pic.DVDPic, 0, sizeof(pic.DVDPic));
     ((CDVDVideoCodecFFmpeg*)avctx->opaque)->GetPictureCommon(&pic.DVDPic);
-    pic.render = render;
+    pic.videoSurface = surf;
     pic.DVDPic.color_matrix = avctx->colorspace;
     m_bufferStats.IncDecoded();
     m_vdpauOutput.m_dataPort.SendOutMessage(COutputDataProtocol::NEWFRAME, &pic, sizeof(pic));
@@ -960,7 +1148,14 @@ int CDecoder::Decode(AVCodecContext *avctx, AVFrame *pFrame)
   uint64_t startTime = CurrentHostCounter();
   while (!retval)
   {
-    if (m_vdpauOutput.m_dataPort.ReceiveInMessage(&msg))
+    // first fill the buffers to keep vdpau busy
+    // mixer will run with decoded >= 2. output is limited by number of output surfaces
+    // In case mixer is bypassed we limit by looking at processed
+    if (decoded < 3 && processed < 3)
+    {
+      retval |= VC_BUFFER;
+    }
+    else if (m_vdpauOutput.m_dataPort.ReceiveInMessage(&msg))
     {
       if (msg->signal == COutputDataProtocol::PICTURE)
       {
@@ -994,20 +1189,9 @@ int CDecoder::Decode(AVCodecContext *avctx, AVFrame *pFrame)
       msg->Release();
     }
 
-    // TODO
-    if (1) //(m_codecControl & DVP_FLAG_DRAIN))
-    {
-      if (decoded + processed + render < 4)
-      {
-        retval |= VC_BUFFER;
-      }
-    }
-    else
+    if (decoded < 3 && processed < 3)
     {
-      if (decoded < 4 && (processed + render) < 3)
-      {
-        retval |= VC_BUFFER;
-      }
+      retval |= VC_BUFFER;
     }
 
     if (!retval && !m_inMsgEvent.WaitMSec(2000))
@@ -1087,7 +1271,9 @@ bool CDecoder::CheckStatus(VdpStatus vdp_st, int line)
 {
   if (vdp_st != VDP_STATUS_OK)
   {
-    CLog::Log(LOGERROR, " (VDPAU) Error: %s(%d) at %s:%d\n", m_vdpauConfig.vdpProcs.vdp_get_error_string(vdp_st), vdp_st, __FILE__, line);
+    CLog::Log(LOGERROR, " (VDPAU) Error: %s(%d) at %s:%d\n", m_vdpauConfig.context->GetProcs().vdp_get_error_string(vdp_st), vdp_st, __FILE__, line);
+
+    m_ErrorCount++;
 
     if(m_DisplayState == VDPAU_OPEN)
     {
@@ -1096,12 +1282,13 @@ bool CDecoder::CheckStatus(VdpStatus vdp_st, int line)
         m_DisplayEvent.Reset();
         m_DisplayState = VDPAU_LOST;
       }
-      else
+      else if (m_ErrorCount > 2)
         m_DisplayState = VDPAU_ERROR;
     }
 
     return true;
   }
+  m_ErrorCount = 0;
   return false;
 }
 
@@ -1165,7 +1352,7 @@ void CVdpauRenderPicture::Sync()
 // Mixer
 //-----------------------------------------------------------------------------
 CMixer::CMixer(CEvent *inMsgEvent) :
-  CThread("Vdpau Mixer Thread"),
+  CThread("Vdpau Mixer"),
   m_controlPort("ControlPort", inMsgEvent, &m_outMsgEvent),
   m_dataPort("DataPort", inMsgEvent, &m_outMsgEvent)
 {
@@ -1329,11 +1516,6 @@ void CMixer::StateMachine(int signal, Protocol *port, Message *msg)
           }
           else
           {
-//            if (m_extTimeout != 0)
-//            {
-//              SetPostProcFeatures(false);
-//              CLog::Log(LOGWARNING,"CVDPAU::Mixer timeout - decoded: %d, outputSurf: %d", (int)m_decodedPics.size(), (int)m_outputSurfaces.size());
-//            }
             m_extTimeout = 100;
           }
           return;
@@ -1401,11 +1583,6 @@ void CMixer::StateMachine(int signal, Protocol *port, Message *msg)
           }
           else
           {
-//            if (m_extTimeout != 0)
-//            {
-//              SetPostProcFeatures(false);
-//              CLog::Log(LOGNOTICE,"---mixer wait2 decoded: %d, outputSurf: %d", (int)m_decodedPics.size(), (int)m_outputSurfaces.size());
-//            }
             m_extTimeout = 100;
           }
           return;
@@ -1541,20 +1718,15 @@ void CMixer::CreateVdpauMixer()
     &m_config.vdpChromaType};
 
   VdpStatus vdp_st = VDP_STATUS_ERROR;
-  vdp_st = m_config.vdpProcs.vdp_video_mixer_create(m_config.vdpDevice,
-                                m_config.featureCount,
-                                m_config.vdpFeatures,
+  vdp_st = m_config.context->GetProcs().vdp_video_mixer_create(m_config.context->GetDevice(),
+                                m_config.context->GetFeatureCount(),
+                                m_config.context->GetFeatures(),
                                 ARSIZE(parameters),
                                 parameters,
                                 parameter_values,
                                 &m_videoMixer);
   CheckStatus(vdp_st, __LINE__);
 
-  // create 3 pitches of black lines needed for clipping top
-  // and bottom lines when de-interlacing
-  m_BlackBar = new uint32_t[3*m_config.outWidth];
-  memset(m_BlackBar, 0, 3*m_config.outWidth*sizeof(uint32_t));
-
 }
 
 void CMixer::InitCSCMatrix(int Width)
@@ -1630,7 +1802,7 @@ void CMixer::PostProcOff()
                                      VDP_VIDEO_MIXER_FEATURE_INVERSE_TELECINE};
 
   VdpBool enabled[]={0,0,0};
-  vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+  vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
   CheckStatus(vdp_st, __LINE__);
 
   if(m_config.vdpau->Supports(VDP_VIDEO_MIXER_FEATURE_NOISE_REDUCTION))
@@ -1638,7 +1810,7 @@ void CMixer::PostProcOff()
     VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_NOISE_REDUCTION};
 
     VdpBool enabled[]={0};
-    vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+    vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
     CheckStatus(vdp_st, __LINE__);
   }
 
@@ -1647,7 +1819,7 @@ void CMixer::PostProcOff()
     VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_SHARPNESS};
 
     VdpBool enabled[]={0};
-    vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+    vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
     CheckStatus(vdp_st, __LINE__);
   }
 
@@ -1759,13 +1931,13 @@ void CMixer::SetColor()
     float studioCSC[3][4];
     GenerateStudioCSCMatrix(colorStandard, studioCSC);
     void const * pm_CSCMatix[] = { &studioCSC };
-    vdp_st = m_config.vdpProcs.vdp_video_mixer_set_attribute_values(m_videoMixer, ARSIZE(attributes), attributes, pm_CSCMatix);
+    vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_attribute_values(m_videoMixer, ARSIZE(attributes), attributes, pm_CSCMatix);
   }
   else
   {
-    vdp_st = m_config.vdpProcs.vdp_generate_csc_matrix(&m_Procamp, colorStandard, &m_CSCMatrix);
+    vdp_st = m_config.context->GetProcs().vdp_generate_csc_matrix(&m_Procamp, colorStandard, &m_CSCMatrix);
     void const * pm_CSCMatix[] = { &m_CSCMatrix };
-    vdp_st = m_config.vdpProcs.vdp_video_mixer_set_attribute_values(m_videoMixer, ARSIZE(attributes), attributes, pm_CSCMatix);
+    vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_attribute_values(m_videoMixer, ARSIZE(attributes), attributes, pm_CSCMatix);
   }
 
   CheckStatus(vdp_st, __LINE__);
@@ -1783,16 +1955,16 @@ void CMixer::SetNoiseReduction()
   if (!CMediaSettings::Get().GetCurrentVideoSettings().m_NoiseReduction)
   {
     VdpBool enabled[]= {0};
-    vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+    vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
     CheckStatus(vdp_st, __LINE__);
     return;
   }
   VdpBool enabled[]={1};
-  vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+  vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
   CheckStatus(vdp_st, __LINE__);
   void* nr[] = { &CMediaSettings::Get().GetCurrentVideoSettings().m_NoiseReduction };
   CLog::Log(LOGNOTICE,"Setting Noise Reduction to %f",CMediaSettings::Get().GetCurrentVideoSettings().m_NoiseReduction);
-  vdp_st = m_config.vdpProcs.vdp_video_mixer_set_attribute_values(m_videoMixer, ARSIZE(attributes), attributes, nr);
+  vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_attribute_values(m_videoMixer, ARSIZE(attributes), attributes, nr);
   CheckStatus(vdp_st, __LINE__);
 }
 
@@ -1808,16 +1980,16 @@ void CMixer::SetSharpness()
   if (!CMediaSettings::Get().GetCurrentVideoSettings().m_Sharpness)
   {
     VdpBool enabled[]={0};
-    vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+    vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
     CheckStatus(vdp_st, __LINE__);
     return;
   }
   VdpBool enabled[]={1};
-  vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+  vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
   CheckStatus(vdp_st, __LINE__);
   void* sh[] = { &CMediaSettings::Get().GetCurrentVideoSettings().m_Sharpness };
   CLog::Log(LOGNOTICE,"Setting Sharpness to %f",CMediaSettings::Get().GetCurrentVideoSettings().m_Sharpness);
-  vdp_st = m_config.vdpProcs.vdp_video_mixer_set_attribute_values(m_videoMixer, ARSIZE(attributes), attributes, sh);
+  vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_attribute_values(m_videoMixer, ARSIZE(attributes), attributes, sh);
   CheckStatus(vdp_st, __LINE__);
 }
 
@@ -1867,7 +2039,7 @@ void CMixer::SetDeinterlacing()
   if (mode == VS_DEINTERLACEMODE_OFF)
   {
     VdpBool enabled[] = {0,0,0};
-    vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+    vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
   }
   else
   {
@@ -1876,7 +2048,7 @@ void CMixer::SetDeinterlacing()
       VdpBool enabled[] = {1,0,0};
       if (g_advancedSettings.m_videoVDPAUtelecine)
         enabled[2] = 1;
-      vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+      vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
     }
     else if (method == VS_INTERLACEMETHOD_VDPAU_TEMPORAL
          ||  method == VS_INTERLACEMETHOD_VDPAU_TEMPORAL_HALF)
@@ -1884,7 +2056,7 @@ void CMixer::SetDeinterlacing()
       VdpBool enabled[] = {1,0,0};
       if (g_advancedSettings.m_videoVDPAUtelecine)
         enabled[2] = 1;
-      vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+      vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
     }
     else if (method == VS_INTERLACEMETHOD_VDPAU_TEMPORAL_SPATIAL
          ||  method == VS_INTERLACEMETHOD_VDPAU_TEMPORAL_SPATIAL_HALF)
@@ -1892,12 +2064,12 @@ void CMixer::SetDeinterlacing()
       VdpBool enabled[] = {1,1,0};
       if (g_advancedSettings.m_videoVDPAUtelecine)
         enabled[2] = 1;
-      vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+      vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
     }
     else
     {
       VdpBool enabled[]={0,0,0};
-      vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+      vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
     }
   }
   CheckStatus(vdp_st, __LINE__);
@@ -1919,7 +2091,7 @@ void CMixer::SetDeintSkipChroma()
     val = 0;
 
   void const *values[]={&val};
-  vdp_st = m_config.vdpProcs.vdp_video_mixer_set_attribute_values(m_videoMixer, ARSIZE(attribute), attribute, values);
+  vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_attribute_values(m_videoMixer, ARSIZE(attribute), attribute, values);
 
   CheckStatus(vdp_st, __LINE__);
 }
@@ -1936,63 +2108,63 @@ void CMixer::SetHWUpscaling()
        if (m_config.vdpau->Supports(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L9))
        {
           VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L9 };
-          vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+          vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
           break;
        }
     case 8:
        if (m_config.vdpau->Supports(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L8))
        {
           VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L8 };
-          vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+          vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
           break;
        }
     case 7:
        if (m_config.vdpau->Supports(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L7))
        {
           VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L7 };
-          vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+          vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
           break;
        }
     case 6:
        if (m_config.vdpau->Supports(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L6))
        {
           VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L6 };
-          vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+          vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
           break;
        }
     case 5:
        if (m_config.vdpau->Supports(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L5))
        {
           VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L5 };
-          vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+          vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
           break;
        }
     case 4:
        if (m_config.vdpau->Supports(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L4))
        {
           VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L4 };
-          vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+          vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
           break;
        }
     case 3:
        if (m_config.vdpau->Supports(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L3))
        {
           VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L3 };
-          vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+          vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
           break;
        }
     case 2:
        if (m_config.vdpau->Supports(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L2))
        {
           VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L2 };
-          vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+          vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
           break;
        }
     case 1:
        if (m_config.vdpau->Supports(VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L1))
        {
           VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L1 };
-          vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+          vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
           break;
        }
     default:
@@ -2014,7 +2186,7 @@ void CMixer::DisableHQScaling()
   {
     VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L1 };
     VdpBool enabled[]={0};
-    vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+    vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
     CheckStatus(vdp_st, __LINE__);
   }
 
@@ -2022,7 +2194,7 @@ void CMixer::DisableHQScaling()
   {
     VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L2 };
     VdpBool enabled[]={0};
-    vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+    vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
     CheckStatus(vdp_st, __LINE__);
   }
 
@@ -2030,7 +2202,7 @@ void CMixer::DisableHQScaling()
   {
     VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L3 };
     VdpBool enabled[]={0};
-    vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+    vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
     CheckStatus(vdp_st, __LINE__);
   }
 
@@ -2038,7 +2210,7 @@ void CMixer::DisableHQScaling()
   {
     VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L4 };
     VdpBool enabled[]={0};
-    vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+    vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
     CheckStatus(vdp_st, __LINE__);
   }
 
@@ -2046,7 +2218,7 @@ void CMixer::DisableHQScaling()
   {
     VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L5 };
     VdpBool enabled[]={0};
-    vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+    vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
     CheckStatus(vdp_st, __LINE__);
   }
 
@@ -2054,7 +2226,7 @@ void CMixer::DisableHQScaling()
   {
     VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L6 };
     VdpBool enabled[]={0};
-    vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+    vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
     CheckStatus(vdp_st, __LINE__);
   }
 
@@ -2062,7 +2234,7 @@ void CMixer::DisableHQScaling()
   {
     VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L7 };
     VdpBool enabled[]={0};
-    vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+    vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
     CheckStatus(vdp_st, __LINE__);
   }
 
@@ -2070,7 +2242,7 @@ void CMixer::DisableHQScaling()
   {
     VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L8 };
     VdpBool enabled[]={0};
-    vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+    vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
     CheckStatus(vdp_st, __LINE__);
   }
 
@@ -2078,12 +2250,11 @@ void CMixer::DisableHQScaling()
   {
     VdpVideoMixerFeature feature[] = { VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L9 };
     VdpBool enabled[]={0};
-    vdp_st = m_config.vdpProcs.vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
+    vdp_st = m_config.context->GetProcs().vdp_video_mixer_set_feature_enables(m_videoMixer, ARSIZE(feature), feature, enabled);
     CheckStatus(vdp_st, __LINE__);
   }
 }
 
-
 void CMixer::Init()
 {
   m_Brightness = 0.0;
@@ -2092,6 +2263,8 @@ void CMixer::Init()
   m_Sharpness = 0.0;
   m_DeintMode = 0;
   m_Deint = 0;
+  m_Upscale = 0;
+  m_SeenInterlaceFlag = false;
   m_ColorMatrix = 0;
   m_PostProc = false;
   m_vdpError = false;
@@ -2109,9 +2282,7 @@ void CMixer::Uninit()
   {
     m_outputSurfaces.pop();
   }
-  m_config.vdpProcs.vdp_video_mixer_destroy(m_videoMixer);
-
-  delete [] m_BlackBar;
+  m_config.context->GetProcs().vdp_video_mixer_destroy(m_videoMixer);
 }
 
 void CMixer::Flush()
@@ -2120,17 +2291,13 @@ void CMixer::Flush()
   {
     CVdpauDecodedPicture pic = m_mixerInput.back();
     m_mixerInput.pop_back();
-    CSingleLock lock(*m_config.videoSurfaceSec);
-    if (pic.render)
-      pic.render->state &= ~FF_VDPAU_STATE_USED_FOR_RENDER;
+    m_config.videoSurfaces->ClearRender(pic.videoSurface);
   }
   while (!m_decodedPics.empty())
   {
     CVdpauDecodedPicture pic = m_decodedPics.front();
     m_decodedPics.pop();
-    CSingleLock lock(*m_config.videoSurfaceSec);
-    if (pic.render)
-      pic.render->state &= ~FF_VDPAU_STATE_USED_FOR_RENDER;
+    m_config.videoSurfaces->ClearRender(pic.videoSurface);
   }
   Message *msg;
   while (m_dataPort.ReceiveOutMessage(&msg))
@@ -2138,9 +2305,7 @@ void CMixer::Flush()
     if (msg->signal == CMixerDataProtocol::FRAME)
     {
       CVdpauDecodedPicture pic = *(CVdpauDecodedPicture*)msg->data;
-      CSingleLock lock(*m_config.videoSurfaceSec);
-      if (pic.render)
-        pic.render->state &= ~FF_VDPAU_STATE_USED_FOR_RENDER;
+      m_config.videoSurfaces->ClearRender(pic.videoSurface);
     }
     else if (msg->signal == CMixerDataProtocol::BUFFER)
     {
@@ -2155,10 +2320,9 @@ void CMixer::Flush()
 void CMixer::InitCycle()
 {
   CheckFeatures();
-  uint64_t latency;
   int flags;
+  uint64_t latency;
   m_config.stats->GetParams(latency, flags);
-  latency = (latency*1000)/CurrentHostFrequency();
   // TODO
   if (0) //flags & DVP_FLAG_NO_POSTPROC)
     SetPostProcFeatures(false);
@@ -2170,6 +2334,7 @@ void CMixer::InitCycle()
   EDEINTERLACEMODE   mode = CMediaSettings::Get().GetCurrentVideoSettings().m_DeinterlaceMode;
   EINTERLACEMETHOD method = GetDeinterlacingMethod();
   bool interlaced = m_mixerInput[1].DVDPic.iFlags & DVP_FLAG_INTERLACED;
+  m_SeenInterlaceFlag |= interlaced;
 
   // TODO
   if (//!(flags & DVP_FLAG_NO_POSTPROC) &&
@@ -2248,11 +2413,18 @@ void CMixer::InitCycle()
   }
   m_mixerstep = 0;
 
+  m_processPicture.crop = false;
   if (m_mixerInput[1].DVDPic.format == RENDER_FMT_VDPAU)
   {
     m_processPicture.outputSurface = m_outputSurfaces.front();
     m_mixerInput[1].DVDPic.iWidth = m_config.outWidth;
     m_mixerInput[1].DVDPic.iHeight = m_config.outHeight;
+    if (m_SeenInterlaceFlag)
+    {
+      double ratio = (double)m_mixerInput[1].DVDPic.iDisplayHeight / m_mixerInput[1].DVDPic.iHeight;
+      m_mixerInput[1].DVDPic.iDisplayHeight = lrint(ratio*(m_mixerInput[1].DVDPic.iHeight-NUM_CROP_PIX*2));
+      m_processPicture.crop = true;
+    }
   }
   else
   {
@@ -2261,21 +2433,22 @@ void CMixer::InitCycle()
   }
 
   m_processPicture.DVDPic = m_mixerInput[1].DVDPic;
-  m_processPicture.render = m_mixerInput[1].render;
+  m_processPicture.videoSurface = m_mixerInput[1].videoSurface;
 }
 
 void CMixer::FiniCycle()
 {
-  while (m_mixerInput.size() > 3)
+  // Keep video surfaces for one 2 cycles longer than used
+  // by mixer. This avoids blocking in decoder.
+  // NVidia recommends num_ref + 5
+  while (m_mixerInput.size() > 5)
   {
     CVdpauDecodedPicture &tmp = m_mixerInput.back();
-    if (tmp.render && m_processPicture.DVDPic.format != RENDER_FMT_VDPAU_420)
+    if (m_processPicture.DVDPic.format != RENDER_FMT_VDPAU_420)
     {
-      CSingleLock lock(*m_config.videoSurfaceSec);
-      tmp.render->state &= ~FF_VDPAU_STATE_USED_FOR_RENDER;
+      m_config.videoSurfaces->ClearRender(tmp.videoSurface);
     }
     m_mixerInput.pop_back();
-//    m_config.stats->DecDecoded();
   }
 }
 
@@ -2304,10 +2477,10 @@ void CMixer::ProcessPicture()
     // use only 2 past 1 future for progressive/weave
     // (only used for postproc anyway eg noise reduction)
     if (m_mixerInput.size() > 3)
-      past_surfaces[1] = m_mixerInput[3].render->surface;
+      past_surfaces[1] = m_mixerInput[3].videoSurface;
     if (m_mixerInput.size() > 2)
-      past_surfaces[0] = m_mixerInput[2].render->surface;
-    futu_surfaces[0] = m_mixerInput[0].render->surface;
+      past_surfaces[0] = m_mixerInput[2].videoSurface;
+    futu_surfaces[0] = m_mixerInput[0].videoSurface;
     pastCount = 2;
     futuCount = 1;
   }
@@ -2317,31 +2490,31 @@ void CMixer::ProcessPicture()
     { // first field
       if (m_mixerInput.size() > 3)
       {
-        past_surfaces[3] = m_mixerInput[3].render->surface;
-        past_surfaces[2] = m_mixerInput[3].render->surface;
+        past_surfaces[3] = m_mixerInput[3].videoSurface;
+        past_surfaces[2] = m_mixerInput[3].videoSurface;
       }
       if (m_mixerInput.size() > 2)
       {
-        past_surfaces[1] = m_mixerInput[2].render->surface;
-        past_surfaces[0] = m_mixerInput[2].render->surface;
+        past_surfaces[1] = m_mixerInput[2].videoSurface;
+        past_surfaces[0] = m_mixerInput[2].videoSurface;
       }
-      futu_surfaces[0] = m_mixerInput[1].render->surface;
-      futu_surfaces[1] = m_mixerInput[0].render->surface;;
+      futu_surfaces[0] = m_mixerInput[1].videoSurface;
+      futu_surfaces[1] = m_mixerInput[0].videoSurface;
     }
     else
     { // second field
       if (m_mixerInput.size() > 3)
       {
-        past_surfaces[3] = m_mixerInput[3].render->surface;
+        past_surfaces[3] = m_mixerInput[3].videoSurface;
       }
       if (m_mixerInput.size() > 2)
       {
-        past_surfaces[2] = m_mixerInput[2].render->surface;
-        past_surfaces[1] = m_mixerInput[2].render->surface;
+        past_surfaces[2] = m_mixerInput[2].videoSurface;
+        past_surfaces[1] = m_mixerInput[2].videoSurface;
       }
-      past_surfaces[0] = m_mixerInput[1].render->surface;
-      futu_surfaces[0] = m_mixerInput[1].render->surface;
-      futu_surfaces[1] = m_mixerInput[1].render->surface;
+      past_surfaces[0] = m_mixerInput[1].videoSurface;
+      futu_surfaces[0] = m_mixerInput[0].videoSurface;
+      futu_surfaces[1] = m_mixerInput[0].videoSurface;
 
       if (m_mixerInput[0].DVDPic.pts != DVD_NOPTS_VALUE &&
           m_mixerInput[1].DVDPic.pts != DVD_NOPTS_VALUE)
@@ -2370,13 +2543,13 @@ void CMixer::ProcessPicture()
   destRect.y1 = m_config.outHeight;
 
   // start vdpau video mixer
-  vdp_st = m_config.vdpProcs.vdp_video_mixer_render(m_videoMixer,
+  vdp_st = m_config.context->GetProcs().vdp_video_mixer_render(m_videoMixer,
                                 VDP_INVALID_HANDLE,
                                 0,
                                 m_mixerfield,
                                 pastCount,
                                 past_surfaces,
-                                m_mixerInput[1].render->surface,
+                                m_mixerInput[1].videoSurface,
                                 futuCount,
                                 futu_surfaces,
                                 &sourceRect,
@@ -2386,32 +2559,6 @@ void CMixer::ProcessPicture()
                                 0,
                                 NULL);
   CheckStatus(vdp_st, __LINE__);
-
-  if (m_mixerfield != VDP_VIDEO_MIXER_PICTURE_STRUCTURE_FRAME)
-  {
-    // in order to clip top and bottom lines when de-interlacing
-    // we black those lines as a work around for not working
-    // background colour using the mixer
-    // pixel perfect is preferred over overscanning or zooming
-
-    VdpRect clipRect = destRect;
-    clipRect.y1 = clipRect.y0 + 2;
-    uint32_t *data[] = {m_BlackBar};
-    uint32_t pitches[] = {destRect.x1};
-    vdp_st = m_config.vdpProcs.vdp_output_surface_put_bits_native(m_processPicture.outputSurface,
-                                            (void**)data,
-                                            pitches,
-                                            &clipRect);
-    CheckStatus(vdp_st, __LINE__);
-
-    clipRect = destRect;
-    clipRect.y0 = clipRect.y1 - 2;
-    vdp_st = m_config.vdpProcs.vdp_output_surface_put_bits_native(m_processPicture.outputSurface,
-                                            (void**)data,
-                                            pitches,
-                                            &clipRect);
-    CheckStatus(vdp_st, __LINE__);
-  }
 }
 
 
@@ -2419,7 +2566,7 @@ bool CMixer::CheckStatus(VdpStatus vdp_st, int line)
 {
   if (vdp_st != VDP_STATUS_OK)
   {
-    CLog::Log(LOGERROR, " (VDPAU) Error: %s(%d) at %s:%d\n", m_config.vdpProcs.vdp_get_error_string(vdp_st), vdp_st, __FILE__, line);
+    CLog::Log(LOGERROR, " (VDPAU) Error: %s(%d) at %s:%d\n", m_config.context->GetProcs().vdp_get_error_string(vdp_st), vdp_st, __FILE__, line);
     m_vdpError = true;
     return true;
   }
@@ -2455,7 +2602,7 @@ VdpauBufferPool::~VdpauBufferPool()
 // Output
 //-----------------------------------------------------------------------------
 COutput::COutput(CEvent *inMsgEvent) :
-  CThread("Vdpau Output Thread"),
+  CThread("Vdpau Output"),
   m_controlPort("OutputControlPort", inMsgEvent, &m_outMsgEvent),
   m_dataPort("OutputDataPort", inMsgEvent, &m_outMsgEvent),
   m_mixer(&m_outMsgEvent)
@@ -2820,8 +2967,12 @@ bool COutput::Init()
 bool COutput::Uninit()
 {
   m_mixer.Dispose();
+  glFlush();
+  while(ProcessSyncPicture())
+  {
+    Sleep(10);
+  }
   GLUnmapSurfaces();
-  GLUnbindPixmaps();
   ReleaseBufferPool();
   DestroyGlxContext();
   return true;
@@ -2848,12 +2999,7 @@ void COutput::Flush()
     if (msg->signal == CMixerDataProtocol::PICTURE)
     {
       CVdpauProcessedPicture pic = *(CVdpauProcessedPicture*)msg->data;
-      if (pic.DVDPic.format == RENDER_FMT_VDPAU_420)
-      {
-        CSingleLock lock(*m_config.videoSurfaceSec);
-        if (pic.render)
-          pic.render->state &= ~FF_VDPAU_STATE_USED_FOR_RENDER;
-      }
+      m_bufferPool.processedPics.push(pic);
     }
     msg->Release();
   }
@@ -2863,9 +3009,7 @@ void COutput::Flush()
     if (msg->signal == COutputDataProtocol::NEWFRAME)
     {
       CVdpauDecodedPicture pic = *(CVdpauDecodedPicture*)msg->data;
-      CSingleLock lock(*m_config.videoSurfaceSec);
-      if (pic.render)
-        pic.render->state &= ~FF_VDPAU_STATE_USED_FOR_RENDER;
+      m_config.videoSurfaces->ClearRender(pic.videoSurface);
     }
     else if (msg->signal == COutputDataProtocol::RETURNPIC)
     {
@@ -2900,78 +3044,38 @@ void COutput::Flush()
         CLog::Log(LOGDEBUG, "COutput::Flush - gl surface not found");
         continue;
       }
-      vdpau_render_state *render = it2->second.sourceVuv;
-      if (render)
-        render->state |= FF_VDPAU_STATE_USED_FOR_RENDER;
+      m_config.videoSurfaces->MarkRender(it2->second.sourceVuv);
     }
   }
+
+  // clear processed pics
+  while(!m_bufferPool.processedPics.empty())
+  {
+    CVdpauProcessedPicture procPic = m_bufferPool.processedPics.front();
+    if (procPic.DVDPic.format == RENDER_FMT_VDPAU)
+    {
+      m_mixer.m_dataPort.SendOutMessage(CMixerDataProtocol::BUFFER, &procPic.outputSurface, sizeof(procPic.outputSurface));
+    }
+    else if (procPic.DVDPic.format == RENDER_FMT_VDPAU_420)
+    {
+      m_config.videoSurfaces->ClearRender(procPic.videoSurface);
+    }
+    m_bufferPool.processedPics.pop();
+  }
 }
 
 bool COutput::HasWork()
 {
-  if (m_config.usePixmaps)
-  {
-    if (!m_bufferPool.processedPics.empty() && FindFreePixmap() >= 0)
-      return true;
-    if (!m_bufferPool.notVisiblePixmaps.empty() && !m_bufferPool.freeRenderPics.empty())
-      return true;
-    return false;
-  }
-  else
-  {
-    if (!m_bufferPool.processedPics.empty() && !m_bufferPool.freeRenderPics.empty())
-      return true;
-    return false;
-  }
+  if (!m_bufferPool.processedPics.empty() && !m_bufferPool.freeRenderPics.empty())
+    return true;
+  return false;
 }
 
 CVdpauRenderPicture* COutput::ProcessMixerPicture()
 {
   CVdpauRenderPicture *retPic = NULL;
 
-  if (m_config.usePixmaps)
-  {
-    if (!m_bufferPool.processedPics.empty() && FindFreePixmap() >= 0)
-    {
-      unsigned int i = FindFreePixmap();
-      VdpauBufferPool::Pixmaps *pixmap = &m_bufferPool.pixmaps[i];
-      pixmap->used = true;
-      CVdpauProcessedPicture pic = m_bufferPool.processedPics.front();
-      m_bufferPool.processedPics.pop();
-      pixmap->surface = pic.outputSurface;
-      pixmap->DVDPic = pic.DVDPic;
-      pixmap->id = i;
-      m_bufferPool.notVisiblePixmaps.push_back(i);
-      m_config.vdpProcs.vdp_presentation_queue_display(pixmap->vdp_flip_queue,
-                                                       pixmap->surface,0,0,0);
-    }
-    if (!m_bufferPool.notVisiblePixmaps.empty() && !m_bufferPool.freeRenderPics.empty())
-    {
-      VdpStatus vdp_st;
-      VdpTime time;
-      VdpPresentationQueueStatus status;
-      int idx = m_bufferPool.notVisiblePixmaps.front();
-      VdpauBufferPool::Pixmaps *pixmap = &m_bufferPool.pixmaps[idx];
-      vdp_st = m_config.vdpProcs.vdp_presentation_queue_query_surface_status(
-                        pixmap->vdp_flip_queue, pixmap->surface, &status, &time);
-
-      if (vdp_st == VDP_STATUS_OK && status == VDP_PRESENTATION_QUEUE_STATUS_VISIBLE)
-      {
-        int idx = m_bufferPool.freeRenderPics.front();
-        retPic = m_bufferPool.allRenderPics[idx];
-        m_bufferPool.freeRenderPics.pop_front();
-        m_bufferPool.usedRenderPics.push_back(idx);
-        retPic->sourceIdx = pixmap->id;
-        retPic->DVDPic = pixmap->DVDPic;
-        retPic->valid = true;
-        retPic->texture[0] = pixmap->texture;
-        retPic->crop = CRect(0,0,0,0);
-        m_bufferPool.notVisiblePixmaps.pop_front();
-        m_mixer.m_dataPort.SendOutMessage(CMixerDataProtocol::BUFFER, &pixmap->surface, sizeof(pixmap->surface));
-      }
-    }
-  } // pixmap
-  else if (!m_bufferPool.processedPics.empty() && !m_bufferPool.freeRenderPics.empty())
+  if (!m_bufferPool.processedPics.empty() && !m_bufferPool.freeRenderPics.empty())
   {
     int idx = m_bufferPool.freeRenderPics.front();
     retPic = m_bufferPool.allRenderPics[idx];
@@ -2987,18 +3091,23 @@ CVdpauRenderPicture* COutput::ProcessMixerPicture()
       m_config.useInteropYuv = false;
       m_bufferPool.numOutputSurfaces = NUM_RENDER_PICS;
       EnsureBufferPool();
-      GLMapSurfaces();
+      GLMapSurface(false, procPic.outputSurface);
       retPic->sourceIdx = procPic.outputSurface;
       retPic->texture[0] = m_bufferPool.glOutputSurfaceMap[procPic.outputSurface].texture[0];
-      retPic->crop = CRect(0,0,0,0);
+      retPic->texWidth = m_config.outWidth;
+      retPic->texHeight = m_config.outHeight;
+      retPic->crop.x1 = 0;
+      retPic->crop.y1 = procPic.crop ? NUM_CROP_PIX : 0;
+      retPic->crop.x2 = m_config.outWidth;
+      retPic->crop.y2 = m_config.outHeight - retPic->crop.y1;
     }
     else
     {
       m_config.useInteropYuv = true;
-      GLMapSurfaces();
-      retPic->sourceIdx = procPic.render->surface;
+      GLMapSurface(true, procPic.videoSurface);
+      retPic->sourceIdx = procPic.videoSurface;
       for (unsigned int i=0; i<4; ++i)
-        retPic->texture[i] = m_bufferPool.glVideoSurfaceMap[procPic.render->surface].texture[i];
+        retPic->texture[i] = m_bufferPool.glVideoSurfaceMap[procPic.videoSurface].texture[i];
       retPic->texWidth = m_config.surfaceWidth;
       retPic->texHeight = m_config.surfaceHeight;
       retPic->crop.x1 = 0;
@@ -3101,12 +3210,7 @@ bool COutput::ProcessSyncPicture()
 
 void COutput::ProcessReturnPicture(CVdpauRenderPicture *pic)
 {
-  if (m_config.usePixmaps)
-  {
-    m_bufferPool.pixmaps[pic->sourceIdx].used = false;
-    return;
-  }
-  else if (pic->DVDPic.format == RENDER_FMT_VDPAU_420)
+  if (pic->DVDPic.format == RENDER_FMT_VDPAU_420)
   {
     std::map<VdpVideoSurface, VdpauBufferPool::GLVideoSurface>::iterator it;
     it = m_bufferPool.glVideoSurfaceMap.find(pic->sourceIdx);
@@ -3115,9 +3219,11 @@ void COutput::ProcessReturnPicture(CVdpauRenderPicture *pic)
       CLog::Log(LOGDEBUG, "COutput::ProcessReturnPicture - gl surface not found");
       return;
     }
-    vdpau_render_state *render = it->second.sourceVuv;
-    CSingleLock lock(*m_config.videoSurfaceSec);
-    render->state &= ~FF_VDPAU_STATE_USED_FOR_RENDER;
+#ifdef GL_NV_vdpau_interop
+    glVDPAUUnmapSurfacesNV(1, &(it->second.glVdpauSurface));
+#endif
+    VdpVideoSurface surf = it->second.sourceVuv;
+    m_config.videoSurfaces->ClearRender(surf);
   }
   else if (pic->DVDPic.format == RENDER_FMT_VDPAU)
   {
@@ -3128,26 +3234,14 @@ void COutput::ProcessReturnPicture(CVdpauRenderPicture *pic)
       CLog::Log(LOGDEBUG, "COutput::ProcessReturnPicture - gl surface not found");
       return;
     }
+#ifdef GL_NV_vdpau_interop
+    glVDPAUUnmapSurfacesNV(1, &(it->second.glVdpauSurface));
+#endif
     VdpOutputSurface outSurf = it->second.sourceRgb;
     m_mixer.m_dataPort.SendOutMessage(CMixerDataProtocol::BUFFER, &outSurf, sizeof(outSurf));
   }
 }
 
-int COutput::FindFreePixmap()
-{
-  // find free pixmap
-  unsigned int i;
-  for (i = 0; i < m_bufferPool.pixmaps.size(); ++i)
-  {
-    if (!m_bufferPool.pixmaps[i].used)
-      break;
-  }
-  if (i == m_bufferPool.pixmaps.size())
-    return -1;
-  else
-    return i;
-}
-
 bool COutput::EnsureBufferPool()
 {
   VdpStatus vdp_st;
@@ -3156,7 +3250,7 @@ bool COutput::EnsureBufferPool()
   VdpOutputSurface outputSurface;
   for (int i = m_bufferPool.outputSurfaces.size(); i < m_bufferPool.numOutputSurfaces; i++)
   {
-    vdp_st = m_config.vdpProcs.vdp_output_surface_create(m_config.vdpDevice,
+    vdp_st = m_config.context->GetProcs().vdp_output_surface_create(m_config.context->GetDevice(),
                                       VDP_RGBA_FORMAT_B8G8R8A8,
                                       m_config.outWidth,
                                       m_config.outHeight,
@@ -3170,40 +3264,6 @@ bool COutput::EnsureBufferPool()
                                       sizeof(VdpOutputSurface));
     CLog::Log(LOGNOTICE, "VDPAU::COutput::InitBufferPool - Output Surface created");
   }
-
-
-  if (m_config.usePixmaps && m_bufferPool.pixmaps.empty())
-  {
-    // create pixmpas
-    VdpauBufferPool::Pixmaps pixmap;
-    unsigned int numPixmaps = NUM_RENDER_PICS;
-    for (unsigned int i = 0; i < numPixmaps; i++)
-    {
-      pixmap.pixmap = None;
-      pixmap.glPixmap = None;
-      pixmap.vdp_flip_queue = VDP_INVALID_HANDLE;
-      pixmap.vdp_flip_target = VDP_INVALID_HANDLE;
-      MakePixmap(pixmap);
-      glXMakeCurrent(m_Display, None, NULL);
-      vdp_st = m_config.vdpProcs.vdp_presentation_queue_target_create_x11(m_config.vdpDevice,
-                                             pixmap.pixmap, //x_window,
-                                             &pixmap.vdp_flip_target);
-
-      CheckStatus(vdp_st, __LINE__);
-
-      vdp_st = m_config.vdpProcs.vdp_presentation_queue_create(m_config.vdpDevice,
-                                            pixmap.vdp_flip_target,
-                                            &pixmap.vdp_flip_queue);
-      CheckStatus(vdp_st, __LINE__);
-      glXMakeCurrent(m_Display, m_glPixmap, m_glContext);
-
-      pixmap.id = i;
-      pixmap.used = false;
-      m_bufferPool.pixmaps.push_back(pixmap);
-    }
-    GLBindPixmaps();
-  }
-
   return true;
 }
 
@@ -3213,38 +3273,12 @@ void COutput::ReleaseBufferPool()
 
   CSingleLock lock(m_bufferPool.renderPicSec);
 
-  if (m_config.usePixmaps)
-  {
-    for (unsigned int i = 0; i < m_bufferPool.pixmaps.size(); ++i)
-    {
-      if (m_bufferPool.pixmaps[i].vdp_flip_queue != VDP_INVALID_HANDLE)
-      {
-        vdp_st = m_config.vdpProcs.vdp_presentation_queue_destroy(m_bufferPool.pixmaps[i].vdp_flip_queue);
-        CheckStatus(vdp_st, __LINE__);
-      }
-      if (m_bufferPool.pixmaps[i].vdp_flip_target != VDP_INVALID_HANDLE)
-      {
-        vdp_st = m_config.vdpProcs.vdp_presentation_queue_target_destroy(m_bufferPool.pixmaps[i].vdp_flip_target);
-        CheckStatus(vdp_st, __LINE__);
-      }
-      if (m_bufferPool.pixmaps[i].glPixmap)
-      {
-        glXDestroyPixmap(m_Display, m_bufferPool.pixmaps[i].glPixmap);
-      }
-      if (m_bufferPool.pixmaps[i].pixmap)
-      {
-        XFreePixmap(m_Display, m_bufferPool.pixmaps[i].pixmap);
-      }
-    }
-    m_bufferPool.pixmaps.clear();
-  }
-
   // release all output surfaces
   for (unsigned int i = 0; i < m_bufferPool.outputSurfaces.size(); ++i)
   {
     if (m_bufferPool.outputSurfaces[i] == VDP_INVALID_HANDLE)
       continue;
-    vdp_st = m_config.vdpProcs.vdp_output_surface_destroy(m_bufferPool.outputSurfaces[i]);
+    vdp_st = m_config.context->GetProcs().vdp_output_surface_destroy(m_bufferPool.outputSurfaces[i]);
     CheckStatus(vdp_st, __LINE__);
   }
   m_bufferPool.outputSurfaces.clear();
@@ -3333,7 +3367,7 @@ void COutput::PreCleanup()
     m_bufferPool.glOutputSurfaceMap.erase(it_map);
 #endif
 
-    vdp_st = m_config.vdpProcs.vdp_output_surface_destroy(m_bufferPool.outputSurfaces[i]);
+    vdp_st = m_config.context->GetProcs().vdp_output_surface_destroy(m_bufferPool.outputSurfaces[i]);
     CheckStatus(vdp_st, __LINE__);
 
     m_bufferPool.outputSurfaces[i] = VDP_INVALID_HANDLE;
@@ -3353,89 +3387,8 @@ void COutput::InitMixer()
   }
 }
 
-bool COutput::MakePixmap(VdpauBufferPool::Pixmaps &pixmap)
-{
-  CLog::Log(LOGNOTICE,"Creating %ix%i pixmap", m_config.outWidth, m_config.outHeight);
-
-    // Get our window attribs.
-  XWindowAttributes wndattribs;
-  XGetWindowAttributes(m_Display, g_Windowing.GetWindow(), &wndattribs);
-
-  pixmap.pixmap = XCreatePixmap(m_Display,
-                           g_Windowing.GetWindow(),
-                           m_config.outWidth,
-                           m_config.outHeight,
-                           wndattribs.depth);
-  if (!pixmap.pixmap)
-  {
-    CLog::Log(LOGERROR, "VDPAU::COUtput::MakePixmap - GLX Error: MakePixmap: Unable to create XPixmap");
-    return false;
-  }
-
-//  XGCValues values = {};
-//  GC xgc;
-//  values.foreground = BlackPixel (m_Display, DefaultScreen (m_Display));
-//  xgc = XCreateGC(m_Display, pixmap.pixmap, GCForeground, &values);
-//  XFillRectangle(m_Display, pixmap.pixmap, xgc, 0, 0, m_config.outWidth, m_config.outHeight);
-//  XFreeGC(m_Display, xgc);
-
-  if(!MakePixmapGL(pixmap))
-    return false;
-
-  return true;
-}
-
-bool COutput::MakePixmapGL(VdpauBufferPool::Pixmaps &pixmap)
-{
-  int num=0;
-  int fbConfigIndex = 0;
-
-  int doubleVisAttributes[] = {
-    GLX_RENDER_TYPE, GLX_RGBA_BIT,
-    GLX_RED_SIZE, 8,
-    GLX_GREEN_SIZE, 8,
-    GLX_BLUE_SIZE, 8,
-    GLX_ALPHA_SIZE, 8,
-    GLX_DEPTH_SIZE, 8,
-    GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT,
-    GLX_BIND_TO_TEXTURE_RGBA_EXT, True,
-    GLX_DOUBLEBUFFER, False,
-    GLX_Y_INVERTED_EXT, True,
-    GLX_X_RENDERABLE, True,
-    None
-  };
-
-  int pixmapAttribs[] = {
-    GLX_TEXTURE_TARGET_EXT, GLX_TEXTURE_2D_EXT,
-    GLX_TEXTURE_FORMAT_EXT, GLX_TEXTURE_FORMAT_RGBA_EXT,
-    None
-  };
-
-  GLXFBConfig *fbConfigs;
-  fbConfigs = glXChooseFBConfig(m_Display, g_Windowing.GetCurrentScreen(), doubleVisAttributes, &num);
-  if (fbConfigs==NULL)
-  {
-    CLog::Log(LOGERROR, "VDPAU::COutput::MakPixmapGL - No compatible framebuffers found");
-    return false;
-  }
-  fbConfigIndex = 0;
-
-  pixmap.glPixmap = glXCreatePixmap(m_Display, fbConfigs[fbConfigIndex], pixmap.pixmap, pixmapAttribs);
-
-  if (!pixmap.glPixmap)
-  {
-    CLog::Log(LOGERROR, "VDPAU::COutput::MakPixmapGL - Could not create Pixmap");
-    XFree(fbConfigs);
-    return false;
-  }
-  XFree(fbConfigs);
-  return true;
-}
-
 bool COutput::GLInit()
 {
-  glXBindTexImageEXT = NULL;
-  glXReleaseTexImageEXT = NULL;
 #ifdef GL_NV_vdpau_interop
   glVDPAUInitNV = NULL;
   glVDPAUFiniNV = NULL;
@@ -3449,11 +3402,7 @@ bool COutput::GLInit()
   glVDPAUGetSurfaceivNV = NULL;
 #endif
 
-  m_config.usePixmaps = false;
-
 #ifdef GL_NV_vdpau_interop
-  if (glewIsSupported("GL_NV_vdpau_interop"))
-  {
     if (!glVDPAUInitNV)
       glVDPAUInitNV    = (PFNGLVDPAUINITNVPROC)glXGetProcAddress((GLubyte *) "glVDPAUInitNV");
     if (!glVDPAUFiniNV)
@@ -3475,32 +3424,15 @@ bool COutput::GLInit()
     if (!glVDPAUGetSurfaceivNV)
       glVDPAUGetSurfaceivNV = (PFNGLVDPAUGETSURFACEIVNVPROC)glXGetProcAddress((GLubyte *) "glVDPAUGetSurfaceivNV");
 
-    CLog::Log(LOGNOTICE, "VDPAU::COutput GL interop supported");
-  }
-  else
-#endif
-  {
-    m_config.usePixmaps = true;
-    CSettings::Get().SetBool("videoplayer.usevdpaumixer",true);
-  }
-  if (!glXBindTexImageEXT)
-    glXBindTexImageEXT    = (PFNGLXBINDTEXIMAGEEXTPROC)glXGetProcAddress((GLubyte *) "glXBindTexImageEXT");
-  if (!glXReleaseTexImageEXT)
-    glXReleaseTexImageEXT = (PFNGLXRELEASETEXIMAGEEXTPROC)glXGetProcAddress((GLubyte *) "glXReleaseTexImageEXT");
-
-#ifdef GL_NV_vdpau_interop
-  if (!m_config.usePixmaps)
+  while (glGetError() != GL_NO_ERROR);
+  glVDPAUInitNV(reinterpret_cast<void*>(m_config.context->GetDevice()), reinterpret_cast<void*>(m_config.context->GetProcs().vdp_get_proc_address));
+  if (glGetError() != GL_NO_ERROR)
   {
-    while (glGetError() != GL_NO_ERROR);
-    glVDPAUInitNV(reinterpret_cast<void*>(m_config.vdpDevice), reinterpret_cast<void*>(m_config.vdpProcs.vdp_get_proc_address));
-    if (glGetError() != GL_NO_ERROR)
-    {
-      CLog::Log(LOGERROR, "VDPAU::COutput - GLInitInterop glVDPAUInitNV failed");
-      m_vdpError = true;
-      return false;
-    }
-    CLog::Log(LOGNOTICE, "VDPAU::COutput: vdpau gl interop initialized");
+    CLog::Log(LOGERROR, "VDPAU::COutput - GLInitInterop glVDPAUInitNV failed");
+    m_vdpError = true;
+    return false;
   }
+  CLog::Log(LOGNOTICE, "VDPAU::COutput: vdpau gl interop initialized");
 #endif
 
 #ifdef GL_ARB_sync
@@ -3514,95 +3446,103 @@ bool COutput::GLInit()
   return true;
 }
 
-void COutput::GLMapSurfaces()
+void COutput::GLMapSurface(bool yuv, uint32_t source)
 {
 #ifdef GL_NV_vdpau_interop
-  if (m_config.usePixmaps)
-    return;
 
-  if (m_config.useInteropYuv)
+  if (yuv)
   {
-    VdpauBufferPool::GLVideoSurface glSurface;
-    if (m_config.videoSurfaces->size() != m_bufferPool.glVideoSurfaceMap.size())
+    std::map<VdpVideoSurface, VdpauBufferPool::GLVideoSurface>::iterator it;
+    it = m_bufferPool.glVideoSurfaceMap.find(source);
+    if (it == m_bufferPool.glVideoSurfaceMap.end())
     {
-      CSingleLock lock(*m_config.videoSurfaceSec);
-      for (unsigned int i = 0; i < m_config.videoSurfaces->size(); i++)
-      {
-        if ((*m_config.videoSurfaces)[i]->surface == VDP_INVALID_HANDLE)
-          continue;
+      VdpauBufferPool::GLVideoSurface glSurface;
+      VdpVideoSurface surf = source;
 
-        if (m_bufferPool.glVideoSurfaceMap.find((*m_config.videoSurfaces)[i]->surface) == m_bufferPool.glVideoSurfaceMap.end())
-        {
-          glSurface.sourceVuv = (*m_config.videoSurfaces)[i];
-          while (glGetError() != GL_NO_ERROR) ;
-          glGenTextures(4, glSurface.texture);
-          if (glGetError() != GL_NO_ERROR)
-          {
-             CLog::Log(LOGERROR, "VDPAU::COutput error creating texture");
-             m_vdpError = true;
-          }
-          glSurface.glVdpauSurface = glVDPAURegisterVideoSurfaceNV(reinterpret_cast<void*>((*m_config.videoSurfaces)[i]->surface),
+      if (surf == VDP_INVALID_HANDLE)
+        return;
+
+      glSurface.sourceVuv = surf;
+      while (glGetError() != GL_NO_ERROR) ;
+      glGenTextures(4, glSurface.texture);
+      if (glGetError() != GL_NO_ERROR)
+      {
+        CLog::Log(LOGERROR, "VDPAU::COutput error creating texture");
+        m_vdpError = true;
+      }
+      glSurface.glVdpauSurface = glVDPAURegisterVideoSurfaceNV(reinterpret_cast<void*>(surf),
                                                     GL_TEXTURE_2D, 4, glSurface.texture);
 
-          if (glGetError() != GL_NO_ERROR)
-          {
-            CLog::Log(LOGERROR, "VDPAU::COutput error register video surface");
-            m_vdpError = true;
-          }
-          glVDPAUSurfaceAccessNV(glSurface.glVdpauSurface, GL_READ_ONLY);
-          if (glGetError() != GL_NO_ERROR)
-          {
-            CLog::Log(LOGERROR, "VDPAU::COutput error setting access");
-            m_vdpError = true;
-          }
-          glVDPAUMapSurfacesNV(1, &glSurface.glVdpauSurface);
-          if (glGetError() != GL_NO_ERROR)
-          {
-            CLog::Log(LOGERROR, "VDPAU::COutput error mapping surface");
-            m_vdpError = true;
-          }
-          m_bufferPool.glVideoSurfaceMap[(*m_config.videoSurfaces)[i]->surface] = glSurface;
-          if (m_vdpError)
-            return;
-          CLog::Log(LOGNOTICE, "VDPAU::COutput registered surface");
-        }
+      if (glGetError() != GL_NO_ERROR)
+      {
+        CLog::Log(LOGERROR, "VDPAU::COutput error register video surface");
+        m_vdpError = true;
+      }
+      glVDPAUSurfaceAccessNV(glSurface.glVdpauSurface, GL_READ_ONLY);
+      if (glGetError() != GL_NO_ERROR)
+      {
+        CLog::Log(LOGERROR, "VDPAU::COutput error setting access");
+        m_vdpError = true;
       }
+      m_bufferPool.glVideoSurfaceMap[surf] = glSurface;
+
+      CLog::Log(LOGNOTICE, "VDPAU::COutput registered surface");
     }
+
+    while (glGetError() != GL_NO_ERROR) ;
+    glVDPAUMapSurfacesNV(1, &m_bufferPool.glVideoSurfaceMap[source].glVdpauSurface);
+    if (glGetError() != GL_NO_ERROR)
+    {
+      CLog::Log(LOGERROR, "VDPAU::COutput error mapping surface");
+      m_vdpError = true;
+    }
+
+    if (m_vdpError)
+      return;
   }
   else
   {
-    if (m_bufferPool.glOutputSurfaceMap.size() != m_bufferPool.numOutputSurfaces)
+    std::map<VdpOutputSurface, VdpauBufferPool::GLVideoSurface>::iterator it;
+    it = m_bufferPool.glOutputSurfaceMap.find(source);
+    if (it == m_bufferPool.glOutputSurfaceMap.end())
     {
-      VdpauBufferPool::GLVideoSurface glSurface;
-      for (unsigned int i = m_bufferPool.glOutputSurfaceMap.size(); i<m_bufferPool.outputSurfaces.size(); i++)
+      unsigned int idx = 0;
+      for (idx = 0; idx<m_bufferPool.outputSurfaces.size(); idx++)
       {
-        glSurface.sourceRgb = m_bufferPool.outputSurfaces[i];
-        glGenTextures(1, glSurface.texture);
-        glSurface.glVdpauSurface = glVDPAURegisterOutputSurfaceNV(reinterpret_cast<void*>(m_bufferPool.outputSurfaces[i]),
+        if (m_bufferPool.outputSurfaces[idx] == source)
+          break;
+      }
+
+      VdpauBufferPool::GLVideoSurface glSurface;
+      glSurface.sourceRgb = m_bufferPool.outputSurfaces[idx];
+      glGenTextures(1, glSurface.texture);
+      glSurface.glVdpauSurface = glVDPAURegisterOutputSurfaceNV(reinterpret_cast<void*>(m_bufferPool.outputSurfaces[idx]),
                                                GL_TEXTURE_2D, 1, glSurface.texture);
-        if (glGetError() != GL_NO_ERROR)
-        {
-          CLog::Log(LOGERROR, "VDPAU::COutput error register output surface");
-          m_vdpError = true;
-        }
-        glVDPAUSurfaceAccessNV(glSurface.glVdpauSurface, GL_READ_ONLY);
-        if (glGetError() != GL_NO_ERROR)
-        {
-          CLog::Log(LOGERROR, "VDPAU::COutput error setting access");
-          m_vdpError = true;
-        }
-        glVDPAUMapSurfacesNV(1, &glSurface.glVdpauSurface);
-        if (glGetError() != GL_NO_ERROR)
-        {
-          CLog::Log(LOGERROR, "VDPAU::COutput error mapping surface");
-          m_vdpError = true;
-        }
-        m_bufferPool.glOutputSurfaceMap[m_bufferPool.outputSurfaces[i]] = glSurface;
-        if (m_vdpError)
-          return;
+      if (glGetError() != GL_NO_ERROR)
+      {
+        CLog::Log(LOGERROR, "VDPAU::COutput error register output surface");
+        m_vdpError = true;
+      }
+      glVDPAUSurfaceAccessNV(glSurface.glVdpauSurface, GL_READ_ONLY);
+      if (glGetError() != GL_NO_ERROR)
+      {
+        CLog::Log(LOGERROR, "VDPAU::COutput error setting access");
+        m_vdpError = true;
       }
+      m_bufferPool.glOutputSurfaceMap[source] = glSurface;
       CLog::Log(LOGNOTICE, "VDPAU::COutput registered output surfaces");
     }
+
+    while (glGetError() != GL_NO_ERROR) ;
+    glVDPAUMapSurfacesNV(1, &m_bufferPool.glOutputSurfaceMap[source].glVdpauSurface);
+    if (glGetError() != GL_NO_ERROR)
+    {
+      CLog::Log(LOGERROR, "VDPAU::COutput error mapping surface");
+      m_vdpError = true;
+    }
+
+    if (m_vdpError)
+      return;
   }
 #endif
 }
@@ -3610,10 +3550,8 @@ void COutput::GLMapSurfaces()
 void COutput::GLUnmapSurfaces()
 {
 #ifdef GL_NV_vdpau_interop
-  if (m_config.usePixmaps)
-    return;
 
-  { CSingleLock lock(*m_config.videoSurfaceSec);
+  {
     std::map<VdpVideoSurface, VdpauBufferPool::GLVideoSurface>::iterator it;
     for (it = m_bufferPool.glVideoSurfaceMap.begin(); it != m_bufferPool.glVideoSurfaceMap.end(); ++it)
     {
@@ -3638,57 +3576,11 @@ void COutput::GLUnmapSurfaces()
 #endif
 }
 
-void COutput::GLBindPixmaps()
-{
-  if (!m_config.usePixmaps)
-    return;
-
-  for (unsigned int i = 0; i < m_bufferPool.pixmaps.size(); i++)
-  {
-    // create texture
-    glGenTextures(1, &m_bufferPool.pixmaps[i].texture);
-
-    //bind texture
-    glBindTexture(GL_TEXTURE_2D, m_bufferPool.pixmaps[i].texture);
-
-    // bind pixmap
-    glXBindTexImageEXT(m_Display, m_bufferPool.pixmaps[i].glPixmap, GLX_FRONT_LEFT_EXT, NULL);
-
-    glBindTexture(GL_TEXTURE_2D, 0);
-  }
-
-  CLog::Log(LOGNOTICE, "VDPAU::COutput: bound pixmaps");
-}
-
-void COutput::GLUnbindPixmaps()
-{
-  if (!m_config.usePixmaps)
-    return;
-
-  for (unsigned int i = 0; i < m_bufferPool.pixmaps.size(); i++)
-  {
-    // create texture
-    if (!glIsTexture(m_bufferPool.pixmaps[i].texture))
-      continue;
-
-    //bind texture
-    glBindTexture(GL_TEXTURE_2D, m_bufferPool.pixmaps[i].texture);
-
-    // release pixmap
-    glXReleaseTexImageEXT(m_Display, m_bufferPool.pixmaps[i].glPixmap, GLX_FRONT_LEFT_EXT);
-
-    glBindTexture(GL_TEXTURE_2D, 0);
-
-    glDeleteTextures(1, &m_bufferPool.pixmaps[i].texture);
-  }
-  CLog::Log(LOGNOTICE, "VDPAU::COutput: unbound pixmaps");
-}
-
 bool COutput::CheckStatus(VdpStatus vdp_st, int line)
 {
   if (vdp_st != VDP_STATUS_OK)
   {
-    CLog::Log(LOGERROR, " (VDPAU) Error: %s(%d) at %s:%d\n", m_config.vdpProcs.vdp_get_error_string(vdp_st), vdp_st, __FILE__, line);
+    CLog::Log(LOGERROR, " (VDPAU) Error: %s(%d) at %s:%d\n", m_config.context->GetProcs().vdp_get_error_string(vdp_st), vdp_st, __FILE__, line);
     m_vdpError = true;
     return true;
   }