xpra icon
Bug tracker and wiki

This bug tracker and wiki are being discontinued
please use https://github.com/Xpra-org/xpra instead.


Ticket #370: nvenc-stub.patch

File nvenc-stub.patch, 57.2 KB (added by Antoine Martin, 8 years ago)

stubs for implementing an nvenc encoder

  • xpra/codecs/nvenc/__init__.py

     
    22# Copyright (C) 2013 Antoine Martin <antoine@devloop.org.uk>
    33# Xpra is released under the terms of the GNU GPL v2, or, at your option, any
    44# later version. See the file COPYING for details.
    5 
    6 raise ImportError("not implemented yet")
  • xpra/codecs/nvenc/constants.txt

     
     1# This file is part of Xpra.
     2# Copyright (C) 2013 Antoine Martin <antoine@devloop.org.uk>
     3# Xpra is released under the terms of the GNU GPL v2, or, at your option, any
     4# later version. See the file COPYING for details.
     5
     6## This file is processed by setup.py to create a .pxi
     7##
     8## The resulting .pxi file will make all the constants available to
     9## Cython code under their own names, and also create a python-exposed
     10## dictionary through which the constants can be accessed like
     11## constants["AV_..."].
     12
     13NVENCAPI_VERSION
     14
     15NVENC_INFINITE_GOPLENGTH
     16
     17#NV_ENC_PARAMS_FRAME_FIELD_MODE:
     18NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME
     19NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD
     20NV_ENC_PARAMS_FRAME_FIELD_MODE_MBAFF
     21
     22#NV_ENC_PARAMS_RC_MODE:
     23NV_ENC_PARAMS_RC_CONSTQP
     24NV_ENC_PARAMS_RC_VBR
     25NV_ENC_PARAMS_RC_CBR
     26NV_ENC_PARAMS_RC_VBR_MINQP
     27NV_ENC_PARAMS_RC_2_PASS_QUALITY
     28NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP
     29NV_ENC_PARAMS_RC_CBR2
     30
     31#NV_ENC_PIC_STRUCT:
     32NV_ENC_PIC_STRUCT_FRAME
     33NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM
     34NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP
     35
     36#NV_ENC_PIC_TYPE:
     37NV_ENC_PIC_TYPE_P
     38NV_ENC_PIC_TYPE_B
     39NV_ENC_PIC_TYPE_I
     40NV_ENC_PIC_TYPE_IDR
     41NV_ENC_PIC_TYPE_BI
     42NV_ENC_PIC_TYPE_SKIPPED
     43NV_ENC_PIC_TYPE_INTRA_REFRESH
     44NV_ENC_PIC_TYPE_UNKNOWN
     45
     46#NV_ENC_SLICE_TYPE:
     47NV_ENC_SLICE_TYPE_DEFAULT
     48NV_ENC_SLICE_TYPE_I
     49NV_ENC_SLICE_TYPE_UNKNOWN
     50
     51#NV_ENC_MV_PRECISION:
     52NV_ENC_MV_PRECISION_FULL_PEL
     53NV_ENC_MV_PRECISION_HALF_PEL
     54NV_ENC_MV_PRECISION_QUARTER_PEL
     55
     56#NV_ENC_BUFFER_FORMAT:
     57NV_ENC_BUFFER_FORMAT_UNDEFINED
     58NV_ENC_BUFFER_FORMAT_NV12_PL
     59NV_ENC_BUFFER_FORMAT_NV12_TILED16x16
     60NV_ENC_BUFFER_FORMAT_NV12_TILED64x16
     61NV_ENC_BUFFER_FORMAT_YV12_PL
     62NV_ENC_BUFFER_FORMAT_YV12_TILED16x16
     63NV_ENC_BUFFER_FORMAT_YV12_TILED64x16
     64NV_ENC_BUFFER_FORMAT_IYUV_PL
     65NV_ENC_BUFFER_FORMAT_IYUV_TILED16x16
     66NV_ENC_BUFFER_FORMAT_IYUV_TILED64x16
     67NV_ENC_BUFFER_FORMAT_YUV444_PL
     68NV_ENC_BUFFER_FORMAT_YUV444_TILED16x16
     69NV_ENC_BUFFER_FORMAT_YUV444_TILED64x16
     70
     71#NV_ENC_LEVEL:
     72NV_ENC_LEVEL_AUTOSELECT
     73NV_ENC_LEVEL_H264_1
     74NV_ENC_LEVEL_H264_1b
     75NV_ENC_LEVEL_H264_11
     76NV_ENC_LEVEL_H264_12
     77NV_ENC_LEVEL_H264_13
     78NV_ENC_LEVEL_H264_2
     79NV_ENC_LEVEL_H264_21
     80NV_ENC_LEVEL_H264_22
     81NV_ENC_LEVEL_H264_3
     82NV_ENC_LEVEL_H264_31
     83NV_ENC_LEVEL_H264_32
     84NV_ENC_LEVEL_H264_4
     85NV_ENC_LEVEL_H264_41
     86NV_ENC_LEVEL_H264_42
     87NV_ENC_LEVEL_H264_5
     88NV_ENC_LEVEL_H264_51
     89NV_ENC_LEVEL_MPEG2_LOW
     90NV_ENC_LEVEL_MPEG2_MAIN
     91NV_ENC_LEVEL_MPEG2_HIGH
     92NV_ENC_LEVEL_MPEG2_HIGH1440
     93NV_ENC_LEVEL_VC1_LOW
     94NV_ENC_LEVEL_VC1_MEDIAN
     95NV_ENC_LEVEL_VC1_HIGH
     96NV_ENC_LEVEL_VC1_0
     97NV_ENC_LEVEL_VC1_1
     98NV_ENC_LEVEL_VC1_2
     99NV_ENC_LEVEL_VC1_3
     100NV_ENC_LEVEL_VC1_4
     101
     102#NVENCSTATUS:
     103NV_ENC_SUCCESS
     104NV_ENC_ERR_NO_ENCODE_DEVICE
     105NV_ENC_ERR_UNSUPPORTED_DEVICE
     106NV_ENC_ERR_INVALID_ENCODERDEVICE
     107NV_ENC_ERR_INVALID_DEVICE
     108NV_ENC_ERR_DEVICE_NOT_EXIST
     109NV_ENC_ERR_INVALID_PTR
     110NV_ENC_ERR_INVALID_EVENT
     111NV_ENC_ERR_INVALID_PARAM
     112NV_ENC_ERR_INVALID_CALL
     113NV_ENC_ERR_OUT_OF_MEMORY
     114NV_ENC_ERR_ENCODER_NOT_INITIALIZED
     115NV_ENC_ERR_UNSUPPORTED_PARAM
     116NV_ENC_ERR_LOCK_BUSY
     117NV_ENC_ERR_NOT_ENOUGH_BUFFER
     118NV_ENC_ERR_INVALID_VERSION
     119NV_ENC_ERR_MAP_FAILED
     120NV_ENC_ERR_NEED_MORE_INPUT
     121NV_ENC_ERR_ENCODER_BUSY
     122NV_ENC_ERR_EVENT_NOT_REGISTERD
     123NV_ENC_ERR_GENERIC
     124NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY
     125NV_ENC_ERR_UNIMPLEMENTED
     126NV_ENC_ERR_RESOURCE_REGISTER_FAILED
     127NV_ENC_ERR_RESOURCE_NOT_REGISTERED
     128NV_ENC_ERR_RESOURCE_NOT_MAPPED
     129
     130#NV_ENC_PIC_FLAGS:
     131NV_ENC_PIC_FLAG_FORCEINTRA
     132NV_ENC_PIC_FLAG_FORCEIDR
     133NV_ENC_PIC_FLAG_OUTPUT_SPSPPS
     134NV_ENC_PIC_FLAG_EOS
     135NV_ENC_PIC_FLAG_DYN_RES_CHANGE
     136NV_ENC_PIC_FLAG_DYN_BITRATE_CHANGE
     137NV_ENC_PIC_FLAG_USER_FORCE_CONSTQP
     138NV_ENC_PIC_FLAG_DYN_RCMODE_CHANGE
     139NV_ENC_PIC_FLAG_REINIT_ENCODER
     140
     141#NV_ENC_MEMORY_HEAP:
     142NV_ENC_MEMORY_HEAP_AUTOSELECT
     143NV_ENC_MEMORY_HEAP_VID
     144NV_ENC_MEMORY_HEAP_SYSMEM_CACHED
     145NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED
     146
     147#NV_ENC_H264_ENTROPY_CODING_MODE:
     148NV_ENC_H264_ENTROPY_CODING_MODE_AUTOSELECT
     149NV_ENC_H264_ENTROPY_CODING_MODE_CABAC
     150NV_ENC_H264_ENTROPY_CODING_MODE_CAVLC
     151
     152#NV_ENC_H264_FMO_MODE:
     153NV_ENC_H264_FMO_AUTOSELECT
     154NV_ENC_H264_FMO_ENABLE
     155NV_ENC_H264_FMO_DISABLE
     156
     157#NV_ENC_H264_ADAPTIVE_TRANSFORM_MODE:
     158NV_ENC_H264_ADAPTIVE_TRANSFORM_AUTOSELECT
     159NV_ENC_H264_ADAPTIVE_TRANSFORM_DISABLE
     160NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE
     161
     162#NV_ENC_STEREO_PACKING_MODE:
     163NV_ENC_STEREO_PACKING_MODE_NONE
     164NV_ENC_STEREO_PACKING_MODE_CHECKERBOARD
     165NV_ENC_STEREO_PACKING_MODE_COLINTERLEAVE
     166NV_ENC_STEREO_PACKING_MODE_ROWINTERLEAVE
     167NV_ENC_STEREO_PACKING_MODE_SIDEBYSIDE
     168NV_ENC_STEREO_PACKING_MODE_TOPBOTTOM
     169NV_ENC_STEREO_PACKING_MODE_FRAMESEQ
     170
     171#NV_ENC_INPUT_RESOURCE_TYPE:
     172NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX
     173NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR
     174NV_ENC_INPUT_RESOURCE_TYPE_CUDAARRAY
     175
     176#NV_ENC_DEVICE_TYPE
     177NV_ENC_DEVICE_TYPE_DIRECTX
     178NV_ENC_DEVICE_TYPE_CUDA
     179
     180#NV_ENC_CAPS:
     181NV_ENC_CAPS_NUM_MAX_BFRAMES
     182NV_ENC_CAPS_SUPPORTED_RATECONTROL_MODES
     183NV_ENC_CAPS_SUPPORT_FIELD_ENCODING
     184NV_ENC_CAPS_SUPPORT_MONOCHROME
     185NV_ENC_CAPS_SUPPORT_FMO
     186NV_ENC_CAPS_SUPPORT_QPELMV
     187NV_ENC_CAPS_SUPPORT_BDIRECT_MODE
     188NV_ENC_CAPS_SUPPORT_CABAC
     189NV_ENC_CAPS_SUPPORT_ADAPTIVE_TRANSFORM
     190NV_ENC_CAPS_SUPPORT_STEREO_MVC
     191NV_ENC_CAPS_NUM_MAX_TEMPORAL_LAYERS
     192NV_ENC_CAPS_SUPPORT_HIERARCHICAL_PFRAMES
     193NV_ENC_CAPS_SUPPORT_HIERARCHICAL_BFRAMES
     194NV_ENC_CAPS_LEVEL_MAX
     195NV_ENC_CAPS_LEVEL_MIN
     196NV_ENC_CAPS_SEPARATE_COLOUR_PLANE
     197NV_ENC_CAPS_WIDTH_MAX
     198NV_ENC_CAPS_HEIGHT_MAX
     199NV_ENC_CAPS_SUPPORT_TEMPORAL_SVC
     200NV_ENC_CAPS_SUPPORT_DYN_RES_CHANGE
     201NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE
     202NV_ENC_CAPS_SUPPORT_DYN_FORCE_CONSTQP
     203NV_ENC_CAPS_SUPPORT_DYN_RCMODE_CHANGE
     204NV_ENC_CAPS_SUPPORT_SUBFRAME_READBACK
     205NV_ENC_CAPS_SUPPORT_CONSTRAINED_ENCODING
     206NV_ENC_CAPS_SUPPORT_INTRA_REFRESH
     207NV_ENC_CAPS_SUPPORT_CUSTOM_VBV_BUF_SIZE
     208NV_ENC_CAPS_SUPPORT_DYNAMIC_SLICE_MODE
     209NV_ENC_CAPS_SUPPORT_REF_PIC_INVALIDATION
     210NV_ENC_CAPS_PREPROC_SUPPORT
     211NV_ENC_CAPS_ASYNC_ENCODE_SUPPORT
     212NV_ENC_CAPS_MB_NUM_MAX
     213NV_ENC_CAPS_EXPOSED_COUNT
  • xpra/codecs/nvenc/encoder.py

     
    1 # This file is part of Xpra.
    2 # Copyright (C) 2013 Antoine Martin <antoine@devloop.org.uk>
    3 # Xpra is released under the terms of the GNU GPL v2, or, at your option, any
    4 # later version. See the file COPYING for details.
    5 
    6 from xpra.codecs.codec_constants import codec_spec
    7 
    8 COLORSPACES = ("YUV420P", )
    9 def get_colorspaces():
    10     return COLORSPACES
    11 
    12 def get_spec(colorspace):
    13     assert colorspace in COLORSPACES, "invalid colorspace: %s (must be one of %s)" % (colorspace, COLORSPACES)
    14     #ratings: quality, speed, setup cost, cpu cost, gpu cost, latency, max_w, max_h, max_pixels
    15     return codec_spec(Encoder, quality=60, setup_cost=100, cpu_cost=10, gpu_cost=100)
    16 
    17 def get_type():
    18     return "nvenc"
    19 
    20 
    21 class Encoder(object):
    22 
    23     def init_context(self, width, height, src_format, quality, speed, options):
    24         raise Exception("this is a fake encoder!")
  • xpra/codecs/nvenc/encoder.pyx

     
    33# Xpra is released under the terms of the GNU GPL v2, or, at your option, any
    44# later version. See the file COPYING for details.
    55
     6import binascii
     7import time
     8import os
     9
     10from xpra.log import Logger, debug_if_env
     11log = Logger()
     12debug = debug_if_env(log, "XPRA_NVENC_DEBUG")
     13error = log.error
     14
     15from libc.stdint cimport uint8_t, uint16_t, uint32_t, int32_t, uint64_t
     16
     17FORCE = True
     18
     19
     20cdef extern from "string.h":
     21    void * memcpy ( void * destination, void * source, size_t num )
     22    void * memset ( void * ptr, int value, size_t num )
     23
     24#could also use pycuda...
     25cdef extern from "cuda.h":
     26    ctypedef int CUdevice
     27    ctypedef struct CUcontext:
     28        pass
     29    int cuInit(unsigned int flags)
     30    int cuDeviceGet(CUdevice *device, int ordinal)
     31    int cuDeviceGetCount(int *count)
     32    int cuDeviceGetName(char *name, int len, CUdevice dev)
     33    int cuDeviceComputeCapability(int *major, int *minor, CUdevice dev)
     34
     35    int cuCtxCreate(CUcontext *pctx, unsigned int flags, CUdevice dev)
     36    int cuCtxPopCurrent(CUcontext *pctx)
     37
     38
     39cdef extern from "NvTypes.h":
     40    pass
     41
     42
     43CODEC_PROFILES = {
     44                  #NV_ENC_H264_PROFILE_BASELINE_GUID
     45                  "baseline"    : 66,
     46                  #NV_ENC_H264_PROFILE_MAIN_GUID
     47                  "main"        : 77,
     48                  #NV_ENC_H264_PROFILE_HIGH_GUID
     49                  "high"        : 100,
     50                  #NV_ENC_H264_PROFILE_STEREO_GUID
     51                  "stereo"      : 128,
     52                  }
     53#cdef extern from "videoFormats.h":
     54#    const char *getVideoFormatString(unsigned int dwFormat)
     55
     56ctypedef uint32_t CONSTANT
     57
     58cdef extern from "nvEncodeAPI.h":
     59
     60    ctypedef int NVENCSTATUS
     61    ctypedef void* NV_ENC_INPUT_PTR
     62    ctypedef void* NV_ENC_OUTPUT_PTR
     63    ctypedef void* NV_ENC_REGISTERED_PTR
     64
     65    ctypedef struct NV_ENC_PIC_PARAMS:
     66        pass
     67    ctypedef struct NV_ENC_LOCK_BITSTREAM:
     68        pass
     69    ctypedef struct NV_ENC_LOCK_INPUT_BUFFER:
     70        pass
     71    ctypedef struct NV_ENC_STAT:
     72        pass
     73    ctypedef struct NV_ENC_SEQUENCE_PARAM_PAYLOAD:
     74        pass
     75    ctypedef struct NV_ENC_EVENT_PARAMS:
     76        pass
     77    ctypedef struct NV_ENC_MAP_INPUT_RESOURCE:
     78        pass
     79    ctypedef struct NV_ENC_REGISTER_RESOURCE:
     80        pass
     81
     82    ctypedef struct GUID:
     83        uint32_t Data1
     84        uint16_t Data2
     85        uint16_t Data3
     86        uint8_t  Data4[8]
     87
     88    #Encode Codec GUIDS supported by the NvEncodeAPI interface.
     89    GUID NV_ENC_CODEC_H264_GUID
     90    #NV_ENC_CODEC_MPEG2_GUID, etc..
     91
     92    #Encode Profile GUIDS supported by the NvEncodeAPI interface.
     93    GUID NV_ENC_H264_PROFILE_BASELINE_GUID
     94    GUID NV_ENC_H264_PROFILE_BASELINE_GUID
     95    GUID NV_ENC_H264_PROFILE_MAIN_GUID
     96    GUID NV_ENC_H264_PROFILE_HIGH_GUID
     97    GUID NV_ENC_H264_PROFILE_STEREO_GUID
     98    GUID NV_ENC_H264_PROFILE_SVC_TEMPORAL_SCALABILTY
     99    GUID NV_ENC_H264_PROFILE_CONSTRAINED_HIGH_GUID
     100    #GUID NV_ENC_MPEG2_PROFILE_SIMPLE_GUID etc..
     101
     102    #Preset GUIDS supported by the NvEncodeAPI interface.
     103    GUID NV_ENC_PRESET_DEFAULT_GUID
     104    GUID NV_ENC_PRESET_HP_GUID
     105    GUID NV_ENC_PRESET_HQ_GUID
     106    GUID NV_ENC_PRESET_HQ_GUID
     107    GUID NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID
     108    GUID NV_ENC_PRESET_LOW_LATENCY_HQ_GUID
     109    GUID NV_ENC_PRESET_LOW_LATENCY_HQ_GUID
     110    GUID NV_ENC_PRESET_LOW_LATENCY_HQ_GUID
     111
     112    ctypedef struct NV_ENC_CAPS_PARAM:
     113        uint32_t    version
     114        uint32_t    capsToQuery
     115        uint32_t    reserved[62]
     116
     117    ctypedef struct NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS:
     118        uint32_t    version         #[in]: Struct version. Must be set to ::NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER.
     119        int         deviceType      #[in]: (NV_ENC_DEVICE_TYPE) Specified the device Type
     120        void        *device         #[in]: Pointer to client device.
     121        GUID        *clientKeyPtr   #[in]: Pointer to a GUID key issued to the client.
     122        uint32_t    apiVersion      #[in]: API version. Should be set to NVENCAPI_VERSION.
     123        uint32_t    reserved1[253]  #[in]: Reserved and must be set to 0
     124        void        *reserved2[64]  #[in]: Reserved and must be set to NULL
     125
     126    ctypedef struct NV_ENC_CREATE_INPUT_BUFFER:
     127        uint32_t    version         #[in]: Struct version. Must be set to ::NV_ENC_CREATE_INPUT_BUFFER_VER
     128        uint32_t    width           #[in]: Input buffer width
     129        uint32_t    height          #[in]: Input buffer width
     130        CONSTANT    memoryHeap      #[in]: Input buffer memory heap (NV_ENC_MEMORY_HEAP)
     131        CONSTANT    bufferFmt       #[in]: Input buffer format (NV_ENC_BUFFER_FORMAT)
     132        uint32_t    reserved        #[in]: Reserved and must be set to 0
     133        void        *inputBuffer    #[out]: Pointer to input buffer
     134        void        *pSysMemBuffer  #[in]: Pointer to existing sysmem buffer
     135        uint32_t    reserved1[57]   #[in]: Reserved and must be set to 0
     136        void        *reserved2[63]  #[in]: Reserved and must be set to NULL
     137
     138    ctypedef struct NV_ENC_CREATE_BITSTREAM_BUFFER:
     139        uint32_t    version         #[in]: Struct version. Must be set to ::NV_ENC_CREATE_BITSTREAM_BUFFER_VER
     140        uint32_t    size            #[in]: Size of the bitstream buffer to be created
     141        CONSTANT    memoryHeap      #[in]: Output buffer memory heap
     142        uint32_t    reserved        #[in]: Reserved and must be set to 0
     143        void        *bitstreamBuffer#[out]: Pointer to the output bitstream buffer
     144        void        *bitstreamBufferPtr #[out]: Reserved and should not be used
     145        uint32_t    reserved1[58]   #[in]: Reserved and should be set to 0
     146        void*       reserved2[64]   #[in]: Reserved and should be set to NULL
     147
     148    ctypedef struct NV_ENC_QP:
     149        uint32_t    qpInterP
     150        uint32_t    qpInterB
     151        uint32_t    qpIntra
     152
     153    ctypedef struct NV_ENC_CONFIG_H264:
     154        uint32_t    enableTemporalSVC   #[in]: Set to 1 to enable SVC temporal
     155        uint32_t    enableStereoMVC     #[in]: Set to 1 to enable stereo MVC
     156        uint32_t    hierarchicalPFrames #[in]: Set to 1 to enable hierarchical PFrames
     157        uint32_t    hierarchicalBFrames #[in]: Set to 1 to enable hierarchical BFrames
     158        uint32_t    outputBufferingPeriodSEI    #[in]: Set to 1 to write SEI buffering period syntax in the bitstream
     159        uint32_t    outputPictureTimingSEI      #[in]: Set to 1 to write SEI picture timing syntax in the bitstream
     160        uint32_t    outputAUD                   #[in]: Set to 1 to write access unit delimiter syntax in bitstream
     161        uint32_t    disableSPSPPS               #[in]: Set to 1 to disable writing of Sequence and Picture parameter info in bitstream
     162        uint32_t    outputFramePackingSEI       #[in]: Set to 1 to enable writing of frame packing arrangement SEI messages to bitstream
     163        uint32_t    outputRecoveryPointSEI      #[in]: Set to 1 to enable writing of recovery point SEI message
     164        uint32_t    enableIntraRefresh          #[in]: Set to 1 to enable gradual decoder refresh or intra refresh. If the GOP structure uses B frames this will be ignored
     165        uint32_t    enableConstrainedEncoding   #[in]: Set this to 1 to enable constrainedFrame encoding where each slice in the constarined picture is independent of other slices
     166                                                #Check support for constrained encoding using ::NV_ENC_CAPS_SUPPORT_CONSTRAINED_ENCODING caps.
     167        uint32_t    repeatSPSPPS        #[in]: Set to 1 to enable writing of Sequence and Picture parameter for every IDR frame
     168        uint32_t    enableVFR           #[in]: Set to 1 to enable variable frame rate.
     169        uint32_t    enableLTR           #[in]: Set to 1 to enable LTR support and auto-mark the first
     170        uint32_t    reservedBitFields   #[in]: Reserved bitfields and must be set to 0
     171        uint32_t    level               #[in]: Specifies the encoding level. Client is recommended to set this to NV_ENC_LEVEL_AUTOSELECT in order to enable the NvEncodeAPI interface to select the correct level.
     172        uint32_t    idrPeriod           #[in]: Specifies the IDR interval. If not set, this is made equal to gopLength in NV_ENC_CONFIG.Low latency application client can set IDR interval to NVENC_INFINITE_GOPLENGTH so that IDR frames are not inserted automatically.
     173        uint32_t    separateColourPlaneFlag     #[in]: Set to 1 to enable 4:4:4 separate colour planes
     174        uint32_t    disableDeblockingFilterIDC  #[in]: Specifies the deblocking filter mode. Permissible value range: [0,2]
     175        uint32_t    numTemporalLayers   #[in]: Specifies max temporal layers to be used for hierarchical coding. Valid value range is [1,::NV_ENC_CAPS_NUM_MAX_TEMPORAL_LAYERS]
     176        uint32_t    spsId               #[in]: Specifies the SPS id of the sequence header. Currently reserved and must be set to 0.
     177        uint32_t    ppsId               #[in]: Specifies the PPS id of the picture header. Currently reserved and must be set to 0.
     178        CONSTANT    adaptiveTransformMode       #[in]: (NV_ENC_H264_ADAPTIVE_TRANSFORM_MODE) Specifies the AdaptiveTransform Mode. Check support for AdaptiveTransform mode using ::NV_ENC_CAPS_SUPPORT_ADAPTIVE_TRANSFORM caps.
     179        CONSTANT    fmoMode             #[in]: (NV_ENC_H264_FMO_MODE) Specified the FMO Mode. Check support for FMO using ::NV_ENC_CAPS_SUPPORT_FMO caps.
     180        CONSTANT    bdirectMode         #[in]: (NV_ENC_H264_BDIRECT_MODE) Specifies the BDirect mode. Check support for BDirect mode using ::NV_ENC_CAPS_SUPPORT_BDIRECT_MODE caps.
     181        CONSTANT    entropyCodingMode   #[in]: (NV_ENC_H264_ENTROPY_CODING_MODE) Specifies the entropy coding mode. Check support for CABAC mode using ::NV_ENC_CAPS_SUPPORT_CABAC caps.
     182        CONSTANT    stereoMode          #[in]: (NV_ENC_STEREO_PACKING_MODE) Specifies the stereo frame packing mode which is to be signalled in frame packing arrangement SEI
     183        CONSTANT    h264Extension       #[in]: (NV_ENC_CONFIG_H264_EXT) Specifies the H264 extension config
     184        uint32_t    intraRefreshPeriod  #[in]: Specifies the interval between successive intra refresh if enableIntrarefresh is set and one time intraRefresh configuration is desired.
     185                                        #When this is specified only first IDR will be encoded and no more key frames will be encoded. Client should set PIC_TYPE = NV_ENC_PIC_TYPE_INTRA_REFRESH
     186                                        #for first picture of every intra refresh period.
     187        uint32_t    intraRefreshCnt     #[in]: Specifies the number of frames over which intra refresh will happen
     188        uint32_t    maxNumRefFrames     #[in]: Specifies the DPB size used for encoding. Setting it to 0 will let driver use the default dpb size.
     189                                        #The low latency application which wants to invalidate reference frame as an error resilience tool
     190                                        #is recommended to use a large DPB size so that the encoder can keep old reference frames which can be used if recent
     191                                        #frames are invalidated.
     192        uint32_t    sliceMode           #[in]: This parameter in conjunction with sliceModeData specifies the way in which the picture is divided into slices
     193                                        #sliceMode = 0 MB based slices, sliceMode = 1 Byte based slices, sliceMode = 2 MB row based slices, sliceMode = 3, numSlices in Picture
     194                                        #When forceIntraRefreshWithFrameCnt is set it will have priority over sliceMode setting
     195                                        #When sliceMode == 0 and sliceModeData == 0 whole picture will be coded with one slice
     196        uint32_t    sliceModeData       #[in]: Specifies the parameter needed for sliceMode. For:
     197                                        #sliceMode = 0, sliceModeData specifies # of MBs in each slice (except last slice)
     198                                        #sliceMode = 1, sliceModeData specifies maximum # of bytes in each slice (except last slice)
     199                                        #sliceMode = 2, sliceModeData specifies # of MB rows in each slice (except last slice)
     200                                        #sliceMode = 3, sliceModeData specifies number of slices in the picture. Driver will divide picture into slices optimally
     201        CONSTANT    h264VUIParameters   #[in]: (NV_ENC_CONFIG_H264_VUI_PARAMETERS) Specifies the H264 video usability info pamameters
     202        uint32_t    ltrNumFrames        #[in]: Specifies the number of LTR frames used. Additionally, encoder will mark the first numLTRFrames base layer reference frames within each IDR interval as LTR
     203        uint32_t    ltrTrustMode        #[in]: Specifies the LTR operating mode. Set to 0 to disallow encoding using LTR frames until later specified. Set to 1 to allow encoding using LTR frames unless later invalidated.
     204        uint32_t    reserved1[272]      #[in]: Reserved and must be set to 0
     205        void        *reserved2[64]      #[in]: Reserved and must be set to NULL
     206
     207    ctypedef struct NV_ENC_CONFIG_MPEG2:
     208        uint32_t    profile             #[in]: Specifies the encoding profile
     209        uint32_t    level               #[in]: Specifies the encoding level
     210        uint32_t    alternateScanValue  #[in]: Specifies the AlternateScan value
     211        uint32_t    quantScaleType      #[in]: Specifies the QuantScale value
     212        uint32_t    intraDCPrecision    #[in]: Specifies the intra DC precision
     213        uint32_t    frameDCT            #[in]: Specifies the frame Discrete Cosine Transform
     214        uint32_t    reserved[250]       #[in]: Reserved and must be set to 0
     215        void        *reserved2[64]      #[in]: Reserved and must be set to NULL
     216
     217    ctypedef struct NV_ENC_CONFIG_JPEG:
     218        uint32_t    reserved[256]       #[in]: Reserved and must be set to 0
     219        void        *reserved2[64]      #[in]: Reserved and must be set to NULL
     220
     221    ctypedef struct NV_ENC_CONFIG_VC1:
     222        uint32_t    level               #[in]: Specifies the encoding level
     223        uint32_t    disableOverlapSmooth#[in]: Set this to 1 for disabling overlap smoothing
     224        uint32_t    disableFastUVMC     #[in]: Set this to 1 for disabling fastUVMC mode
     225        uint32_t    disableInloopFilter #[in]: Set this to 1 for disabling in-loop filtering
     226        uint32_t    disable4MV          #[in]: Set this to 1 for disabling 4MV mode
     227        uint32_t    reservedBitFields   #[in]: Reserved bitfields and must be set to 0
     228        uint32_t    numSlices           #[in]: Specifies number of slices to encode. This field is applicable only for Advanced Profile.
     229                                        #If set to 0, NvEncodeAPI interface will choose optimal number of slices. Currently we support only a maximum of three slices
     230        uint32_t    reserved[253]       #[in]: Reserved and must be set to 0
     231        void        *reserved2[64]      #[in]: Reserved and must be set to NULL
     232
     233    ctypedef struct NV_ENC_CONFIG_VP8:
     234        uint32_t    reserved[256]       #[in]: Reserved and must be set to 0
     235        void        *reserved2[64]      #[in]: Reserved and must be set to NULL
     236
     237    ctypedef struct NV_ENC_CODEC_CONFIG:
     238        NV_ENC_CONFIG_H264  h264Config  #[in]: Specifies the H.264-specific encoder configuration
     239        NV_ENC_CONFIG_VC1   vc1Config   #[in]: Specifies the VC1-specific encoder configuration. Currently unsupported and must not to be used.
     240        NV_ENC_CONFIG_JPEG  jpegConfig  #[in]: Specifies the JPEG-specific encoder configuration. Currently unsupported and must not to be used.
     241        NV_ENC_CONFIG_MPEG2 mpeg2Config #[in]: Specifies the MPEG2-specific encoder configuration. Currently unsupported and must not to be used.
     242        NV_ENC_CONFIG_VP8   vp8Config   #[in]: Specifies the VP8-specific encoder configuration. Currently unsupported and must not to be used.
     243        uint32_t            reserved[256]       #[in]: Reserved and must be set to 0
     244
     245    ctypedef struct NV_ENC_CONFIG:
     246        uint32_t    version             #[in]: Struct version. Must be set to ::NV_ENC_CONFIG_VER.
     247        GUID        profileGUID         #[in]: Specifies the codec profile guid. If client specifies \p NV_ENC_CODEC_PROFILE_AUTOSELECT_GUID the NvEncodeAPI interface will select the appropriate codec profile.
     248        uint32_t    gopLength           #[in]: Specifies the number of pictures in one GOP. Low latency application client can set goplength to NVENC_INFINITE_GOPLENGTH so that keyframes are not inserted automatically.
     249        int32_t     frameIntervalP      #[in]: Specifies the GOP pattern as follows: \p frameIntervalP = 0: I, 1: IPP, 2: IBP, 3: IBBP  If goplength is set to NVENC_INFINITE_GOPLENGTH \p frameIntervalP should be set to 1.
     250        uint32_t    monoChromeEncoding  #[in]: Set this to 1 to enable monochrome encoding for this session.
     251        CONSTANT    frameFieldMode      #[in]: (NV_ENC_PARAMS_FRAME_FIELD_MODE) Specifies the frame/field mode. Check support for field encoding using ::NV_ENC_CAPS_SUPPORT_FIELD_ENCODING caps.
     252        CONSTANT    mvPrecision         #[in]: (NV_ENC_MV_PRECISION) Specifies the desired motion vector prediction precision.
     253        CONSTANT    rcParams            #[in]: (NV_ENC_RC_PARAMS) Specifies the rate control parameters for the current encoding session.
     254        CONSTANT    encodeCodecConfig   #[in]: (NV_ENC_CODEC_CONFIG) Specifies the codec specific config parameters through this union.
     255        uint32_t    reserved[278]       #[in]: Reserved and must be set to 0
     256        void        *reserved2[64]      #[in]: Reserved and must be set to NULL
     257
     258
     259    ctypedef struct NVENC_EXTERNAL_ME_HINT_COUNTS_PER_BLOCKTYPE:
     260        uint32_t    numCandsPerBlk16x16 #[in]: Specifies the number of candidates per 16x16 block.
     261        uint32_t    numCandsPerBlk16x8  #[in]: Specifies the number of candidates per 16x8 block.
     262        uint32_t    numCandsPerBlk8x16  #[in]: Specifies the number of candidates per 8x16 block.
     263        uint32_t    numCandsPerBlk8x8   #[in]: Specifies the number of candidates per 8x8 block.
     264        uint32_t    reserved            #[in]: Reserved for padding.
     265        uint32_t    reserved1[3]        #[in]: Reserved for future use.
     266
     267    ctypedef struct NV_ENC_INITIALIZE_PARAMS:
     268        uint32_t    version             #[in]: Struct version. Must be set to ::NV_ENC_INITIALIZE_PARAMS_VER.
     269        GUID        encodeGUID          #[in]: Specifies the Encode GUID for which the encoder is being created. ::NvEncInitializeEncoder() API will fail if this is not set, or set to unsupported value.
     270        GUID        presetGUID          #[in]: Specifies the preset for encoding. If the preset GUID is set then , the preset configuration will be applied before any other parameter.
     271        uint32_t    encodeWidth         #[in]: Specifies the encode width. If not set ::NvEncInitializeEncoder() API will fail.
     272        uint32_t    encodeHeight        #[in]: Specifies the encode height. If not set ::NvEncInitializeEncoder() API will fail.
     273        uint32_t    darWidth            #[in]: Specifies the display aspect ratio Width.
     274        uint32_t    darHeight           #[in]: Specifies the display aspect ratio height.
     275        uint32_t    frameRateNum        #[in]: Specifies the numerator for frame rate used for encoding in frames per second ( Frame rate = frameRateNum / frameRateDen ).
     276        uint32_t    frameRateDen        #[in]: Specifies the denominator for frame rate used for encoding in frames per second ( Frame rate = frameRateNum / frameRateDen ).
     277        uint32_t    enableEncodeAsync   #[in]: Set this to 1 to enable asynchronous mode and is expected to use events to get picture completion notification.
     278        uint32_t    enablePTD           #[in]: Set this to 1 to enable the Picture Type Decision is be taken by the NvEncodeAPI interface.
     279        uint32_t    reportSliceOffsets  #[in]: Set this to 1 to enable reporting slice offsets in ::_NV_ENC_LOCK_BITSTREAM. Currently supported only for H264. Client must set this to 0 if NV_ENC_CONFIG_H264::sliceMode is 1
     280        uint32_t    enableSubFrameWrite #[in]: Set this to 1 to write out available bitstream to memory at subframe intervals
     281        uint32_t    enableExternalMEHints   #[in]: Set to 1 to enable external ME hints for the current frame. Currently this feature is supported only if NV_ENC_INITIALIZE_PARAMS::enablePTD to 0 or\p frameIntervalP = 1 (i.e no B frames).
     282        uint32_t    reservedBitFields   #[in]: Reserved bitfields and must be set to 0
     283        uint32_t    privDataSize        #[in]: Reserved private data buffer size and must be set to 0
     284        void        *privData           #[in]: Reserved private data buffer and must be set to NULL
     285        NV_ENC_CONFIG *encodeConfig     #[in]: Specifies the advanced codec specific structure. If client has sent a valid codec config structure, it will override parameters set by the NV_ENC_INITIALIZE_PARAMS::presetGUID parameter. If set to NULL the NvEncodeAPI interface will use the NV_ENC_INITIALIZE_PARAMS::presetGUID to set the codec specific parameters.
     286                                        #Client can also optionally query the NvEncodeAPI interface to get codec specific parameters for a presetGUID using ::NvEncGetEncodePresetConfig() API. It can then modify (if required) some of the codec config parameters and send down a custom config structure as part of ::_NV_ENC_INITIALIZE_PARAMS.
     287                                        #Even in this case client is recommended to pass the same preset guid it has used in ::NvEncGetEncodePresetConfig() API to query the config structure; as NV_ENC_INITIALIZE_PARAMS::presetGUID. This will not override the custom config structure but will be used to determine other Encoder HW specific parameters not exposed in the API.
     288        uint32_t    maxEncodeWidth      #[in]: Maximum encode width to be used for current Encode session.
     289                                        #Client should allocate output buffers according to this dimension for dynamic resolution change. If set to 0, Encoder will not allow dynamic resolution change.
     290        uint32_t    maxEncodeHeight     #[in]: Maximum encode height to be allowed for current Encode session.
     291                                        #Client should allocate output buffers according to this dimension for dynamic resolution change. If set to 0, Encode will not allow dynamic resolution change.
     292        NVENC_EXTERNAL_ME_HINT_COUNTS_PER_BLOCKTYPE maxMEHintCountsPerBlock[2]  #[in]: If Client wants to pass external motion vectors in NV_ENC_PIC_PARAMS::meExternalHints buffer it must specify the maximum number of hint candidates per block per direction for the encode session.
     293                                        #The NV_ENC_INITIALIZE_PARAMS::maxMEHintCountsPerBlock[0] is for L0 predictors and NV_ENC_INITIALIZE_PARAMS::maxMEHintCountsPerBlock[1] is for L1 predictors.
     294                                        #This client must also set NV_ENC_INITIALIZE_PARAMS::enableExternalMEHints to 1.
     295        uint32_t    reserved[289]       #[in]: Reserved and must be set to 0
     296        void        *reserved2[64]      #[in]: Reserved and must be set to NULL
     297
     298    ctypedef struct NV_ENC_RECONFIGURE_PARAMS:
     299        uint32_t    version             #[in]: Struct version. Must be set to ::NV_ENC_RECONFIGURE_PARAMS_VER.
     300        NV_ENC_INITIALIZE_PARAMS reInitEncodeParams
     301        uint32_t    resetEncoder        #[in]: This resets the rate control states and other internal encoder states. This should be used only with an IDR frame.
     302                                        #If NV_ENC_INITIALIZE_PARAMS::enablePTD is set to 1, encoder will force the frame type to IDR
     303        uint32_t    forceIDR            #[in]: Encode the current picture as an IDR picture. This flag is only valid when Picture type decision is taken by the Encoder
     304                                        #[_NV_ENC_INITIALIZE_PARAMS::enablePTD == 1].
     305        uint32_t    reserved
     306
     307    ctypedef struct NV_ENC_PRESET_CONFIG:
     308        uint32_t    version             #[in]:  Struct version. Must be set to ::NV_ENC_PRESET_CONFIG_VER.
     309        NV_ENC_CONFIG presetCfg         #[out]: preset config returned by the Nvidia Video Encoder interface.
     310        uint32_t    reserved1[255]      #[in]: Reserved and must be set to 0
     311        void*       reserved2[64]       #[in]: Reserved and must be set to NULL
     312
     313    ctypedef struct NV_ENC_PIC_PARAMS_MVC:
     314        uint32_t    viewID              #[in]: Specifies the view ID associated with the current input view.
     315        uint32_t    temporalID          #[in]: Specifies the temporal ID associated with the current input view.
     316        uint32_t    priorityID          #[in]: Specifies the priority ID associated with the current input view. Reserved and ignored by the NvEncodeAPI interface.
     317        uint32_t    reserved1[253]      #[in]: Reserved and must be set to 0.
     318        void        *reserved2[64]      #[in]: Reserved and must be set to NULL.
     319
     320    ctypedef struct NV_ENC_PIC_PARAMS_SVC:
     321        uint32_t    priorityID          #[in]: Specifies the priority id associated with the current input.
     322        uint32_t    temporalID          #[in]: Specifies the temporal id associated with the current input.
     323        uint32_t    dependencyID        #[in]: Specifies the dependency id  associated with the current input.
     324        uint32_t    qualityID           #[in]: Specifies the quality id associated with the current input.
     325        uint32_t    reserved1[252]      #[in]: Reserved and must be set to 0.
     326        void        *reserved2[64]      #[in]: Reserved and must be set to NULL.
     327
     328    ctypedef struct NV_ENC_PIC_PARAMS_H264_EXT:
     329        NV_ENC_PIC_PARAMS_MVC mvcPicParams   #[in]: Specifies the MVC picture parameters.
     330        NV_ENC_PIC_PARAMS_SVC svcPicParams   #[in]: Specifies the SVC picture parameters.
     331        uint32_t    reserved1[256]      #[in]: Reserved and must be set to 0.
     332
     333    NVENCSTATUS NvEncodeAPICreateInstance(NV_ENCODE_API_FUNCTION_LIST *functionList)
     334
     335    ctypedef NVENCSTATUS (*PNVENCOPENENCODESESSION)         (void* device, uint32_t deviceType, void** encoder)
     336    ctypedef NVENCSTATUS (*PNVENCGETENCODEGUIDCOUNT)        (void* encoder, uint32_t* encodeGUIDCount)
     337    ctypedef NVENCSTATUS (*PNVENCGETENCODEGUIDS)            (void* encoder, GUID* GUIDs, uint32_t guidArraySize, uint32_t* GUIDCount)
     338    ctypedef NVENCSTATUS (*PNVENCGETENCODEPROFILEGUIDCOUNT) (void* encoder, GUID encodeGUID, uint32_t* encodeProfileGUIDCount)
     339    ctypedef NVENCSTATUS (*PNVENCGETENCODEPROFILEGUIDS)     (void* encoder, GUID encodeGUID, GUID* profileGUIDs, uint32_t guidArraySize, uint32_t* GUIDCount)
     340    ctypedef NVENCSTATUS (*PNVENCGETINPUTFORMATCOUNT)       (void* encoder, GUID encodeGUID, uint32_t* inputFmtCount)
     341    ctypedef NVENCSTATUS (*PNVENCGETINPUTFORMATS)           (void* encoder, GUID encodeGUID, int* inputFmts, uint32_t inputFmtArraySize, uint32_t* inputFmtCount)
     342    ctypedef NVENCSTATUS (*PNVENCGETENCODECAPS)             (void* encoder, GUID encodeGUID, NV_ENC_CAPS_PARAM* capsParam, int* capsVal)
     343    ctypedef NVENCSTATUS (*PNVENCGETENCODEPRESETCOUNT)      (void* encoder, GUID encodeGUID, uint32_t* encodePresetGUIDCount)
     344    ctypedef NVENCSTATUS (*PNVENCGETENCODEPRESETGUIDS)      (void* encoder, GUID encodeGUID, GUID* presetGUIDs, uint32_t guidArraySize, uint32_t* encodePresetGUIDCount)
     345    ctypedef NVENCSTATUS (*PNVENCGETENCODEPRESETCONFIG)     (void* encoder, GUID encodeGUID, GUID  presetGUID, NV_ENC_PRESET_CONFIG* presetConfig)
     346    ctypedef NVENCSTATUS (*PNVENCINITIALIZEENCODER)         (void* encoder, NV_ENC_INITIALIZE_PARAMS* createEncodeParams)
     347    ctypedef NVENCSTATUS (*PNVENCCREATEINPUTBUFFER)         (void* encoder, NV_ENC_CREATE_INPUT_BUFFER* createInputBufferParams)
     348    ctypedef NVENCSTATUS (*PNVENCDESTROYINPUTBUFFER)        (void* encoder, NV_ENC_INPUT_PTR inputBuffer)
     349    ctypedef NVENCSTATUS (*PNVENCCREATEBITSTREAMBUFFER)     (void* encoder, NV_ENC_CREATE_BITSTREAM_BUFFER* createBitstreamBufferParams)
     350    ctypedef NVENCSTATUS (*PNVENCDESTROYBITSTREAMBUFFER)    (void* encoder, NV_ENC_OUTPUT_PTR bitstreamBuffer)
     351    ctypedef NVENCSTATUS (*PNVENCENCODEPICTURE)             (void* encoder, NV_ENC_PIC_PARAMS* encodePicParams)
     352    ctypedef NVENCSTATUS (*PNVENCLOCKBITSTREAM)             (void* encoder, NV_ENC_LOCK_BITSTREAM* lockBitstreamBufferParams)
     353    ctypedef NVENCSTATUS (*PNVENCUNLOCKBITSTREAM)           (void* encoder, NV_ENC_OUTPUT_PTR bitstreamBuffer)
     354    ctypedef NVENCSTATUS (*PNVENCLOCKINPUTBUFFER)           (void* encoder, NV_ENC_LOCK_INPUT_BUFFER* lockInputBufferParams)
     355    ctypedef NVENCSTATUS (*PNVENCUNLOCKINPUTBUFFER)         (void* encoder, NV_ENC_INPUT_PTR inputBuffer)
     356    ctypedef NVENCSTATUS (*PNVENCGETENCODESTATS)            (void* encoder, NV_ENC_STAT* encodeStats)
     357    ctypedef NVENCSTATUS (*PNVENCGETSEQUENCEPARAMS)         (void* encoder, NV_ENC_SEQUENCE_PARAM_PAYLOAD* sequenceParamPayload)
     358    ctypedef NVENCSTATUS (*PNVENCREGISTERASYNCEVENT)        (void* encoder, NV_ENC_EVENT_PARAMS* eventParams)
     359    ctypedef NVENCSTATUS (*PNVENCUNREGISTERASYNCEVENT)      (void* encoder, NV_ENC_EVENT_PARAMS* eventParams)
     360    ctypedef NVENCSTATUS (*PNVENCMAPINPUTRESOURCE)          (void* encoder, NV_ENC_MAP_INPUT_RESOURCE* mapInputResParams)
     361    ctypedef NVENCSTATUS (*PNVENCUNMAPINPUTRESOURCE)        (void* encoder, NV_ENC_INPUT_PTR mappedInputBuffer)
     362    ctypedef NVENCSTATUS (*PNVENCDESTROYENCODER)            (void* encoder)
     363    ctypedef NVENCSTATUS (*PNVENCINVALIDATEREFFRAMES)       (void* encoder, uint64_t invalidRefFrameTimeStamp)
     364    ctypedef NVENCSTATUS (*PNVENCOPENENCODESESSIONEX)       (NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS *openSessionExParams, void** encoder)
     365    ctypedef NVENCSTATUS (*PNVENCREGISTERRESOURCE)          (void* encoder, NV_ENC_REGISTER_RESOURCE* registerResParams)
     366    ctypedef NVENCSTATUS (*PNVENCUNREGISTERRESOURCE)        (void* encoder, NV_ENC_REGISTERED_PTR registeredRes)
     367    ctypedef NVENCSTATUS (*PNVENCRECONFIGUREENCODER)        (void* encoder, NV_ENC_RECONFIGURE_PARAMS* reInitEncodeParams)
     368
     369    ctypedef struct NV_ENCODE_API_FUNCTION_LIST:
     370        uint32_t    version         #[in]: Client should pass NV_ENCODE_API_FUNCTION_LIST_VER.
     371        uint32_t    reserved        #[in]: Reserved and should be set to 0.
     372        PNVENCOPENENCODESESSION         nvEncOpenEncodeSession          #[out]: Client should access ::NvEncOpenEncodeSession() API through this pointer.
     373        PNVENCGETENCODEGUIDCOUNT        nvEncGetEncodeGUIDCount         #[out]: Client should access ::NvEncGetEncodeGUIDCount() API through this pointer.
     374        PNVENCGETENCODEPRESETCOUNT      nvEncGetEncodeProfileGUIDCount  #[out]: Client should access ::NvEncGetEncodeProfileGUIDCount() API through this pointer.*/
     375        PNVENCGETENCODEPRESETGUIDS      nvEncGetEncodeProfileGUIDs      #[out]: Client should access ::NvEncGetEncodeProfileGUIDs() API through this pointer.     */
     376        PNVENCGETENCODEGUIDS            nvEncGetEncodeGUIDs                 #[out]: Client should access ::NvEncGetEncodeGUIDs() API through this pointer.           */
     377        PNVENCGETINPUTFORMATCOUNT       nvEncGetInputFormatCount            #[out]: Client should access ::NvEncGetInputFormatCount() API through this pointer.      */
     378        PNVENCGETINPUTFORMATS           nvEncGetInputFormats            #[out]: Client should access ::NvEncGetInputFormats() API through this pointer.          */
     379        PNVENCGETENCODECAPS             nvEncGetEncodeCaps                  #[out]: Client should access ::NvEncGetEncodeCaps() API through this pointer.            */
     380        PNVENCGETENCODEPRESETCOUNT      nvEncGetEncodePresetCount           #[out]: Client should access ::NvEncGetEncodePresetCount() API through this pointer.     */
     381        PNVENCGETENCODEPRESETGUIDS      nvEncGetEncodePresetGUIDs           #[out]: Client should access ::NvEncGetEncodePresetGUIDs() API through this pointer.     */
     382        PNVENCGETENCODEPRESETCONFIG     nvEncGetEncodePresetConfig          #[out]: Client should access ::NvEncGetEncodePresetConfig() API through this pointer.    */
     383        PNVENCINITIALIZEENCODER         nvEncInitializeEncoder          #[out]: Client should access ::NvEncInitializeEncoder() API through this pointer.        */
     384        PNVENCCREATEINPUTBUFFER         nvEncCreateInputBuffer          #[out]: Client should access ::NvEncCreateInputBuffer() API through this pointer.        */
     385        PNVENCDESTROYINPUTBUFFER        nvEncDestroyInputBuffer         #[out]: Client should access ::NvEncDestroyInputBuffer() API through this pointer.       */
     386        PNVENCCREATEBITSTREAMBUFFER     nvEncCreateBitstreamBuffer          #[out]: Client should access ::NvEncCreateBitstreamBuffer() API through this pointer.    */
     387        PNVENCDESTROYBITSTREAMBUFFER    nvEncDestroyBitstreamBuffer         #[out]: Client should access ::NvEncDestroyBitstreamBuffer() API through this pointer.   */
     388        PNVENCENCODEPICTURE             nvEncEncodePicture                  #[out]: Client should access ::NvEncEncodePicture() API through this pointer.            */
     389        PNVENCLOCKBITSTREAM             nvEncLockBitstream                  #[out]: Client should access ::NvEncLockBitstream() API through this pointer.            */
     390        PNVENCUNLOCKBITSTREAM           nvEncUnlockBitstream            #[out]: Client should access ::NvEncUnlockBitstream() API through this pointer.          */
     391        PNVENCLOCKINPUTBUFFER           nvEncLockInputBuffer            #[out]: Client should access ::NvEncLockInputBuffer() API through this pointer.          */
     392        PNVENCUNLOCKINPUTBUFFER         nvEncUnlockInputBuffer          #[out]: Client should access ::NvEncUnlockInputBuffer() API through this pointer.        */
     393        PNVENCGETENCODESTATS            nvEncGetEncodeStats                 #[out]: Client should access ::NvEncGetEncodeStats() API through this pointer.           */
     394        PNVENCGETSEQUENCEPARAMS         nvEncGetSequenceParams          #[out]: Client should access ::NvEncGetSequenceParams() API through this pointer.        */
     395        PNVENCREGISTERASYNCEVENT        nvEncRegisterAsyncEvent         #[out]: Client should access ::NvEncRegisterAsyncEvent() API through this pointer.       */
     396        PNVENCUNREGISTERASYNCEVENT      nvEncUnregisterAsyncEvent           #[out]: Client should access ::NvEncUnregisterAsyncEvent() API through this pointer.     */
     397        PNVENCMAPINPUTRESOURCE          nvEncMapInputResource           #[out]: Client should access ::NvEncMapInputResource() API through this pointer.         */
     398        PNVENCUNMAPINPUTRESOURCE        nvEncUnmapInputResource         #[out]: Client should access ::NvEncUnmapInputResource() API through this pointer.       */
     399        PNVENCDESTROYENCODER            nvEncDestroyEncoder                 #[out]: Client should access ::NvEncDestroyEncoder() API through this pointer.           */
     400        PNVENCINVALIDATEREFFRAMES       nvEncInvalidateRefFrames            #[out]: Client should access ::NvEncInvalidateRefFrames() API through this pointer.      */
     401        PNVENCOPENENCODESESSIONEX       nvEncOpenEncodeSessionEx            #[out]: Client should access ::NvEncOpenEncodeSession() API through this pointer.        */
     402        PNVENCREGISTERRESOURCE          nvEncRegisterResource           #[out]: Client should access ::NvEncRegisterResource() API through this pointer.         */
     403        PNVENCUNREGISTERRESOURCE        nvEncUnregisterResource         #[out]: Client should access ::NvEncUnregisterResource() API through this pointer.       */
     404        PNVENCRECONFIGUREENCODER        nvEncReconfigureEncoder         #[out]: Client should access ::NvEncReconfigureEncoder() API through this pointer.       */
     405        void*                           reserved2[285]                  #[in]:  Reserved and must be set to NULL                #[
     406
     407include "constants.pxi"
    6408from xpra.codecs.codec_constants import codec_spec
    7409
    8 COLORSPACES = ("YUV420P", )
     410STATUS_TXT = {
     411    NV_ENC_SUCCESS : "This indicates that API call returned with no errors.",
     412    NV_ENC_ERR_NO_ENCODE_DEVICE       : "This indicates that no encode capable devices were detected",
     413    NV_ENC_ERR_UNSUPPORTED_DEVICE     : "This indicates that devices pass by the client is not supported.",
     414    NV_ENC_ERR_INVALID_ENCODERDEVICE  : "This indicates that the encoder device supplied by the client is not valid.",
     415    NV_ENC_ERR_INVALID_DEVICE         : "This indicates that device passed to the API call is invalid.",
     416    NV_ENC_ERR_DEVICE_NOT_EXIST       : """This indicates that device passed to the API call is no longer available and
     417 needs to be reinitialized. The clients need to destroy the current encoder
     418 session by freeing the allocated input output buffers and destroying the device
     419 and create a new encoding session.""",
     420    NV_ENC_ERR_INVALID_PTR            : "This indicates that one or more of the pointers passed to the API call is invalid.",
     421    NV_ENC_ERR_INVALID_EVENT          : "This indicates that completion event passed in ::NvEncEncodePicture() call is invalid.",
     422    NV_ENC_ERR_INVALID_PARAM          : "This indicates that one or more of the parameter passed to the API call is invalid.",
     423    NV_ENC_ERR_INVALID_CALL           : "This indicates that an API call was made in wrong sequence/order.",
     424    NV_ENC_ERR_OUT_OF_MEMORY          : "This indicates that the API call failed because it was unable to allocate enough memory to perform the requested operation.",
     425    NV_ENC_ERR_ENCODER_NOT_INITIALIZED: """This indicates that the encoder has not been initialized with
     426::NvEncInitializeEncoder() or that initialization has failed.
     427The client cannot allocate input or output buffers or do any encoding
     428related operation before successfully initializing the encoder.""",
     429    NV_ENC_ERR_UNSUPPORTED_PARAM      : "This indicates that an unsupported parameter was passed by the client.",
     430    NV_ENC_ERR_LOCK_BUSY              : """This indicates that the ::NvEncLockBitstream() failed to lock the output
     431buffer. This happens when the client makes a non blocking lock call to
     432access the output bitstream by passing NV_ENC_LOCK_BITSTREAM::doNotWait flag.
     433This is not a fatal error and client should retry the same operation after
     434few milliseconds.""",
     435    NV_ENC_ERR_NOT_ENOUGH_BUFFER      : "This indicates that the size of the user buffer passed by the client is insufficient for the requested operation.",
     436    NV_ENC_ERR_INVALID_VERSION        : "This indicates that an invalid struct version was used by the client.",
     437    NV_ENC_ERR_MAP_FAILED             : "This indicates that ::NvEncMapInputResource() API failed to map the client provided input resource.",
     438    NV_ENC_ERR_NEED_MORE_INPUT        : """
     439This indicates encode driver requires more input buffers to produce an output
     440bitstream. If this error is returned from ::NvEncEncodePicture() API, this
     441is not a fatal error. If the client is encoding with B frames then,
     442::NvEncEncodePicture() API might be buffering the input frame for re-ordering.
     443A client operating in synchronous mode cannot call ::NvEncLockBitstream()
     444API on the output bitstream buffer if ::NvEncEncodePicture() returned the
     445::NV_ENC_ERR_NEED_MORE_INPUT error code.
     446The client must continue providing input frames until encode driver returns
     447::NV_ENC_SUCCESS. After receiving ::NV_ENC_SUCCESS status the client can call
     448::NvEncLockBitstream() API on the output buffers in the same order in which
     449it has called ::NvEncEncodePicture().
     450""",
     451    NV_ENC_ERR_ENCODER_BUSY : """This indicates that the HW encoder is busy encoding and is unable to encode
     452the input. The client should call ::NvEncEncodePicture() again after few milliseconds.""",
     453    NV_ENC_ERR_EVENT_NOT_REGISTERD : """This indicates that the completion event passed in ::NvEncEncodePicture()
     454API has not been registered with encoder driver using ::NvEncRegisterAsyncEvent().""",
     455    NV_ENC_ERR_GENERIC : "This indicates that an unknown internal error has occurred.",
     456    NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY  : "This indicates that the client is attempting to use a feature that is not available for the license type for the current system.",
     457    NV_ENC_ERR_UNIMPLEMENTED : "This indicates that the client is attempting to use a feature that is not implemented for the current version.",
     458    NV_ENC_ERR_RESOURCE_REGISTER_FAILED : "This indicates that the ::NvEncRegisterResource API failed to register the resource.",
     459    NV_ENC_ERR_RESOURCE_NOT_REGISTERED : "This indicates that the client is attempting to unregister a resource that has not been successfuly registered.",
     460    NV_ENC_ERR_RESOURCE_NOT_MAPPED : "This indicates that the client is attempting to unmap a resource that has not been successfuly mapped.",
     461      }
     462
     463
     464COLORSPACES = ("YUV444P", )
    9465def get_colorspaces():
    10466    return COLORSPACES
    11467
     
    14470    #ratings: quality, speed, setup cost, cpu cost, gpu cost, latency, max_w, max_h, max_pixels
    15471    return codec_spec(Encoder, quality=60, setup_cost=100, cpu_cost=10, gpu_cost=100)
    16472
     473
     474def get_version():
     475    return NVENCAPI_VERSION
     476
    17477def get_type():
    18478    return "nvenc"
    19479
    20480
    21 class Encoder(object):
     481def statusInfo(ret):
     482    if ret in STATUS_TXT:
     483        return "%s: %s" % (ret, STATUS_TXT[ret])
     484    return str(ret)
    22485
    23     def init_context(self, width, height, src_format, quality, speed, options):
    24         raise Exception("this is a fake encoder!")
     486def checkCuda(ret, msg=""):
     487    if ret!=0:
     488        log.warn("error during %s: %s", msg, statusInfo(ret))
     489def raiseCuda(ret, msg=""):
     490    if ret!=0:
     491        raise Exception("%s - returned %s" % (msg, statusInfo(ret)))
     492
     493cdef cuda_init(deviceId=0):
     494    cdef int deviceCount, i
     495    cdef CUdevice cuDevice
     496    cdef char gpu_name[100]
     497    cdef int SMminor, SMmajor
     498    raiseCuda(cuInit(0), "cuInit")
     499    raiseCuda(cuDeviceGetCount(&deviceCount), "failed to get device count")
     500    log.info("cuda_init() found %s devices", deviceCount)
     501    for i in range(deviceCount):
     502        checkCuda(cuDeviceGet(&cuDevice, i), "cuDeviceGet")
     503        checkCuda(cuDeviceGetName(gpu_name, 100, cuDevice), "cuDeviceGetName")
     504        log.info("device[%s]=%s", i, gpu_name)
     505        checkCuda(cuDeviceComputeCapability(&SMmajor, &SMminor, i))
     506        has_nvenc = ((SMmajor<<4) + SMminor) >= 0x30
     507        log.info("capability: %s.%s (nvenc=%s)", SMmajor, SMminor, has_nvenc)
     508    if deviceId<0:
     509        deviceId = 0
     510    if deviceId>=deviceCount:
     511        raise Exception("invalid deviceId %s: only %s devices found" % (deviceId, deviceCount))
     512
     513    raiseCuda(cuDeviceGet(&cuDevice, deviceId), "cuDeviceGet")
     514    raiseCuda(cuDeviceGetName(gpu_name, 100, cuDevice), "cuDeviceGetName")
     515    log.info("using device %s: %s", deviceId, gpu_name)
     516    raiseCuda(cuDeviceComputeCapability(&SMmajor, &SMminor, deviceId))
     517    has_nvenc = ((SMmajor<<4) + SMminor) >= 0x30
     518    if FORCE and not has_nvenc:
     519        log.warn("selected device %s does not have NVENC capability!" % gpu_name)
     520    else:
     521        assert has_nvenc, "selected device %s does not have NVENC capability!" % gpu_name
     522
     523    return cuDevice
     524
     525def guidstr(guid):
     526    #really ugly!
     527    b = bytearray((4+2+2+1))
     528    i = 0
     529    vi = 0
     530    for s in (4, 2, 2, 1):
     531        v = bytearray(guid.values()[vi])
     532        vi += 1
     533        for j in range(s):
     534            b[i] = v[j]
     535            i += 1
     536    return binascii.hexlify(b)
     537
     538
     539def nvenc_init():
     540    cdef CUcontext context
     541    cdef int cuDevice
     542    cuDevice = cuda_init()
     543
     544    raiseCuda(cuCtxCreate(&context, 0, cuDevice))
     545    raiseCuda(cuCtxPopCurrent(&context))
     546
     547    log.info("NV_ENC_CODEC_H264_GUID=%s" % guidstr(NV_ENC_CODEC_H264_GUID))
     548#nvenc_init()
     549
     550def open_encode_session():
     551    cdef NV_ENCODE_API_FUNCTION_LIST functionList
     552    cdef NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params
     553    cdef CUcontext context          #@DuplicatedSignature
     554    cdef int cuDevice               #@DuplicatedSignature
     555    cdef GUID clientKeyPtr
     556    cdef void **encoder = NULL
     557
     558    #cuda init:
     559    cuDevice = cuda_init()
     560    raiseCuda(cuCtxCreate(&context, 0, cuDevice))
     561    raiseCuda(cuCtxPopCurrent(&context))
     562
     563    #get NVENC function pointers:
     564    memset(&functionList, 0, sizeof(NV_ENCODE_API_FUNCTION_LIST))
     565    raiseCuda(NvEncodeAPICreateInstance(&functionList), "getting API function list")
     566
     567    #NVENC init:
     568    if False:
     569        #new API:
     570        memset(&params, 0, sizeof(NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS))
     571        params.version = 0
     572        params.deviceType = NV_ENC_DEVICE_TYPE_CUDA
     573        params.device = <void*> context
     574        params.clientKeyPtr = &clientKeyPtr
     575        params.apiVersion = NVENCAPI_VERSION
     576        log.info("calling nvEncOpenEncodeSessionEx @ %s", hex(<long> functionList.nvEncOpenEncodeSessionEx))
     577        raiseCuda(functionList.nvEncOpenEncodeSessionEx(&params, encoder), "opening session")
     578    else:
     579        log.info("calling nvEncOpenEncodeSession @ %s", hex(<long> functionList.nvEncOpenEncodeSession))
     580        raiseCuda(functionList.nvEncOpenEncodeSession(<void*> context, NV_ENC_DEVICE_TYPE_CUDA, encoder), "opening session")
     581    log.info("encoder=%s", hex(<long> encoder))
     582
     583    cdef uint32_t GUIDCount
     584    raiseCuda(functionList.nvEncGetEncodeGUIDCount(encoder, &GUIDCount))
     585    log.info("found %s encode GUIDs", GUIDCount)
     586
     587open_encode_session()
     588
     589"""cdef query_encoder_caps(CNvEncoder *encoder):
     590    cdef int val
     591    for k in {}.items():
     592        #NvEncGetEncodeCaps
     593        pass
     594    pass
     595"""
     596
     597
     598cdef class Encoder:
     599    cdef int width
     600    cdef int height
     601    cdef object src_format
     602    cdef void *context
     603
     604    def init_context(self, int width, int height, src_format, int quality, int speed, options):    #@DuplicatedSignature
     605        self.width = width
     606        self.height = height
     607        self.src_format = src_format
     608
     609    def get_info(self):
     610        cdef float pps
     611        info = {"width"     : self.width,
     612                "height"    : self.height,
     613                "src_format": self.src_format}
     614        return info
     615
     616    def __str__(self):
     617        return "nvenc(%s - %sx%s)" % (self.src_format, self.width, self.height)
     618
     619    def is_closed(self):
     620        return self.context==NULL
     621
     622    def __dealloc__(self):
     623        self.clean()
     624
     625    def clean(self):                        #@DuplicatedSignature
     626        if self.context!=NULL:
     627            #x264_encoder_close(self.context)
     628            self.context = NULL
     629
     630    def get_width(self):
     631        return self.width
     632
     633    def get_height(self):
     634        return self.height
     635
     636    def get_type(self):                     #@DuplicatedSignature
     637        return  "nvenc"
     638
     639    def get_src_format(self):
     640        return self.src_format
     641
     642    def get_client_options(self, options):
     643        return {}
     644
     645    def compress_image(self, image, options={}):
     646        return None
  • setup.py

     
    471471                   "xpra/net/rencode/rencode.c",
    472472                   "xpra/codecs/vpx/encoder.c",
    473473                   "xpra/codecs/vpx/decoder.c",
     474                   "xpra/codecs/nvenc/encoder.c",
     475                   "xpra/codecs/nvenc/constants.pxi",
    474476                   "xpra/codecs/enc_x264/encoder.c",
    475477                   "xpra/codecs/enc_x264/constants.pxi",
    476478                   "xpra/codecs/dec_avcodec/decoder.c",
     
    954956
    955957
    956958
    957 toggle_packages(nvenc_ENABLED, "xpra.codecs.nvenc")
    958959toggle_packages(csc_opencl_ENABLED, "xpra.codecs.csc_opencl")
    959960toggle_packages(csc_nvcuda_ENABLED, "xpra.codecs.csc_nvcuda")
    960961
     962toggle_packages(nvenc_ENABLED, "xpra.codecs.nvenc")
     963if nvenc_ENABLED:
     964    make_constants("xpra", "codecs", "nvenc", "constants")
     965    nvenc_pkgconfig = pkgconfig("nvenc", "cuda")
     966    cython_add(Extension("xpra.codecs.nvenc.encoder",
     967                         ["xpra/codecs/nvenc/encoder.pyx"],
     968                         **nvenc_pkgconfig), min_version=(0, 16))
     969
    961970toggle_packages(enc_x264_ENABLED, "xpra.codecs.enc_x264")
    962971if enc_x264_ENABLED:
    963972    make_constants("xpra", "codecs", "enc_x264", "constants")
  • tests/xpra/codecs/test_nvenc.py

     
     1#!/usr/bin/env python
     2# This file is part of Xpra.
     3# Copyright (C) 2013 Antoine Martin <antoine@devloop.org.uk>
     4# Xpra is released under the terms of the GNU GPL v2, or, at your option, any
     5# later version. See the file COPYING for details.
     6
     7TEST_DIMENSIONS = ((1920, 1080), (512, 512))
     8
     9def test_csc_nvenc():
     10    print("test_csc_nvenc()")
     11    from xpra.codecs.nvenc import encoder #@UnresolvedImport
     12    print("encoder module=%s" % encoder)
     13    print("colorspaces=%s" % encoder.get_colorspaces())
     14    for c in encoder.get_colorspaces():
     15        print("spec(%s)=%s" % (c, encoder.get_spec(c)))
     16    print("version=%s" % str(encoder.get_version()))
     17    print("type=%s" % encoder.get_type())
     18    ec = getattr(encoder, "Encoder")
     19    print("encoder class=%s" % ec)
     20
     21    from tests.xpra.codecs.test_codec import make_planar_input
     22    from xpra.codecs.image_wrapper import ImageWrapper
     23   
     24    for src_format in encoder.get_colorspaces():
     25        for w,h in TEST_DIMENSIONS:
     26            print("* %s @ %sx%s" % (src_format, w, h))
     27            e = ec()
     28            print("instance=%s" % e)
     29            e.init_context(w, h, src_format, 100, 100, {})
     30            print("initialiazed instance=%s" % e)
     31            #create a dummy ImageWrapper to compress:
     32            strides, pixels = make_planar_input(src_format, w, h, use_strings=False, populate=True)
     33            image = ImageWrapper(0, 0, w, h, pixels, src_format, 24, strides, planes=ImageWrapper._3_PLANES)
     34            print("calling %s(%s)" % (e.compress_image, image))
     35            c = e.compress_image(image)
     36            print("output=%s" % c)
     37            assert c is not None
     38
     39
     40def main():
     41    import logging
     42    import sys
     43    logging.root.setLevel(logging.INFO)
     44    logging.root.addHandler(logging.StreamHandler(sys.stdout))
     45    test_csc_nvenc()
     46
     47
     48if __name__ == "__main__":
     49    main()