
Recherche avancée
Médias (1)
-
Rennes Emotion Map 2010-11
19 octobre 2011, par
Mis à jour : Juillet 2013
Langue : français
Type : Texte
Autres articles (95)
-
Personnaliser en ajoutant son logo, sa bannière ou son image de fond
5 septembre 2013, parCertains thèmes prennent en compte trois éléments de personnalisation : l’ajout d’un logo ; l’ajout d’une bannière l’ajout d’une image de fond ;
-
Ecrire une actualité
21 juin 2013, parPrésentez les changements dans votre MédiaSPIP ou les actualités de vos projets sur votre MédiaSPIP grâce à la rubrique actualités.
Dans le thème par défaut spipeo de MédiaSPIP, les actualités sont affichées en bas de la page principale sous les éditoriaux.
Vous pouvez personnaliser le formulaire de création d’une actualité.
Formulaire de création d’une actualité Dans le cas d’un document de type actualité, les champs proposés par défaut sont : Date de publication ( personnaliser la date de publication ) (...) -
Publier sur MédiaSpip
13 juin 2013Puis-je poster des contenus à partir d’une tablette Ipad ?
Oui, si votre Médiaspip installé est à la version 0.2 ou supérieure. Contacter au besoin l’administrateur de votre MédiaSpip pour le savoir
Sur d’autres sites (11800)
-
Rust Win32 FFI : User-mode data execution prevention (DEP) violation
28 avril 2022, par TheElixI'm trying to pass a ID3D11Device instance from Rust to a C FFI Library (FFMPEG).


I made this sample code :


pub fn create_d3d11_device(&mut self, device: &mut Box, context: &mut Box) {
 let av_device : Box<avbufferref> = self.alloc(HwDeviceType::D3d11va);
 unsafe {
 let device_context = Box::from_raw(av_device.data as *mut AVHWDeviceContext);
 let mut d3d11_device_context = Box::from_raw(device_context.hwctx as *mut AVD3D11VADeviceContext);
 d3d11_device_context.device = device.as_mut() as *mut _;
 d3d11_device_context.device_context = context.as_mut() as *mut _;
 let avp = Box::into_raw(av_device);
 av_hwdevice_ctx_init(avp);
 self.av_hwdevice = Some(Box::from_raw(avp));
 }
 }
</avbufferref>


On the Rust side the Device does work, but on the C side, when FFMEPG calls
ID3D11DeviceContext_QueryInterface
the app crashes with the following error :Exception 0xc0000005 encountered at address 0x7ff9fb99ad38: User-mode data execution prevention (DEP) violation at location 0x7ff9fb99ad38


The address is actually the pointer for the lpVtbl of QueryInterface, like seen here :


The disassembly of the address also looks correct (this is done on an another debugging session) :


(lldb) disassemble --start-address 0x00007ffffdf3ad38
 0x7ffffdf3ad38: addb %ah, 0x7ffffd(%rdi,%riz,8)
 0x7ffffdf3ad3f: addb %al, (%rax)
 0x7ffffdf3ad41: movabsl -0x591fffff80000219, %eax
 0x7ffffdf3ad4a: outl %eax, $0xfd



Do you have any pointer to debug this further ?


EDIT : I made a Minimal Reproducion Sample. Interestingly this does not causes a DEP Violation, but simply a Segfault.


On the C side :


int test_ffi(ID3D11Device *device){
 ID3D11DeviceContext *context;
 device->lpVtbl->GetImmediateContext(device, &context);
 if (!context) return 1;
 return 0;
}



On the Rust side :


unsafe fn main_rust(){
 let mut device = None;
 let mut device_context = None;
 let _ = match windows::Win32::Graphics::Direct3D11::D3D11CreateDevice(None, D3D_DRIVER_TYPE_HARDWARE, OtherHinstance::default(), D3D11_CREATE_DEVICE_DEBUG, &[], D3D11_SDK_VERSION, &mut device, std::ptr::null_mut(), &mut device_context) {
 Ok(e) => e,
 Err(e) => panic!("Creation Failed: {}", e)
 };
 let mut device = match device {
 Some(e) => e,
 None => panic!("Creation Failed2")
 };
 let mut f2 : ID3D11Device = transmute_copy(&device); //Transmuting the WinAPI into a bindgen ID3D11Device
 test_ffi(&mut f2);
}



The bindgen build.rs :


extern crate bindgen;

use std::env;
use std::path::PathBuf;

fn main() {
 // Tell cargo to tell rustc to link the system bzip2
 // shared library.
 println!("cargo:rustc-link-lib=ffi_demoLIB");
 println!("cargo:rustc-link-lib=d3d11");

 // Tell cargo to invalidate the built crate whenever the wrapper changes
 println!("cargo:rerun-if-changed=library.h");

 // The bindgen::Builder is the main entry point
 // to bindgen, and lets you build up options for
 // the resulting bindings.
 let bindings = bindgen::Builder::default()
 // The input header we would like to generate
 // bindings for.
 .header("library.h")
 // Tell cargo to invalidate the built crate whenever any of the
 // included header files changed.
 .parse_callbacks(Box::new(bindgen::CargoCallbacks))
 .blacklist_type("_IMAGE_TLS_DIRECTORY64")
 .blacklist_type("IMAGE_TLS_DIRECTORY64")
 .blacklist_type("PIMAGE_TLS_DIRECTORY64")
 .blacklist_type("IMAGE_TLS_DIRECTORY")
 .blacklist_type("PIMAGE_TLS_DIRECTORY")
 // Finish the builder and generate the bindings.
 .generate()
 // Unwrap the Result and panic on failure.
 .expect("Unable to generate bindings");

 // Write the bindings to the $OUT_DIR/bindings.rs file.
 let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
 bindings
 .write_to_file(out_path.join("bindings.rs"))
 .expect("Couldn't write bindings!");
}



The Complete Repo can be found over here : https://github.com/TheElixZammuto/demo-ffi


-
I want to take any Audio from a file and encode it as PCM_ALAW. My Example is a .m4a file to .wav file
22 novembre 2023, par ClockmanI have been working on this for a while now while am generally new to ffmpeg library, I have studied it a bit. The challenge I have that at the point of witting to file I get the following exception.


"Exception thrown at 0x00007FFACA8305B3 (avformat-60.dll) in FfmpegPractice.exe : 0xC0000005 : Access violation writing location 0x0000000000000000.". I understand this means am writing to an uninitialized buffer am unable to discover why this is happening. The exception call stack shows the following


avformat-60.dll!avformat_write_header() C
avformat-60.dll!ff_write_chained() C
avformat-60.dll!ff_write_chained() C
avformat-60.dll!av_write_frame() C
FfmpegPractice.exe!main() Line 215 C++



Some things I have tried


This code is part of a larger project built with CMake but for some reason I could no step into ffmpeg library while debugging, So I recompiled ffmpeg ensured debugging was enabled so I could drill down to the root cause but I still could not step into the ffmpeg library.


I then created a minimal project using visual studio c++ console project and I still could not step into the code.


I have read through many ffmpeg docs and some I could find on the internet and I still could not solve it.


This is the code


#include <iostream>

extern "C" {
#include <libavcodec></libavcodec>avcodec.h>
#include <libavformat></libavformat>avformat.h>
#include <libswresample></libswresample>swresample.h>
#include <libavutil></libavutil>opt.h>
#include <libavutil></libavutil>audio_fifo.h>
}

using namespace std;

//in audio file
string filename{ "rapid_caller_test.m4a" };
AVFormatContext* pFormatCtx{};
AVCodecContext* pCodecCtx{};
AVStream* pStream{};

//out audio file
string outFilename{ "output.wav" };
AVFormatContext* pOutFormatCtx{ nullptr };
AVCodecContext* pOutCodecCtx{ nullptr };
AVIOContext* pOutIoContext{ nullptr };
const AVCodec* pOutCodec{ nullptr };
AVStream* pOutStream{ nullptr };
const int OUTPUT_CHANNELS = 1;
const int SAMPLE_RATE = 8000;
const int OUT_BIT_RATE = 64000;
uint8_t** convertedSamplesBuffer{ nullptr };
int64_t dstNmbrSamples{ 0 };
int dstLineSize{ 0 };
static int64_t pts{ 0 };

//conversion context;
SwrContext* swr{};

uint32_t i{ 0 };
int audiostream{ -1 };


void cleanUp() 
{
 avcodec_free_context(&pOutCodecCtx);;
 avio_closep(&(pOutFormatCtx)->pb);
 avformat_free_context(pOutFormatCtx);
 pOutFormatCtx = nullptr;
}

int main()
{

/*
* section to setup input file
*/
if (avformat_open_input(&pFormatCtx, filename.data(), nullptr, nullptr) != 0) {
 cout << "could not open file " << filename << endl;
 return -1;
}
if (avformat_find_stream_info(pFormatCtx, nullptr) < 0) {
 cout << "Could not retrieve stream information from file " << filename << endl;
 return -1;
}
av_dump_format(pFormatCtx, 0, filename.c_str(), 0);

for (i = 0; i < pFormatCtx->nb_streams; i++) {
 if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
 audiostream = i;
 break;
 }
}
if (audiostream == -1) {
 cout << "did not find audio stream" << endl;
 return -1;
}

pStream = pFormatCtx->streams[audiostream];
const AVCodec* pCodec{ avcodec_find_decoder(pStream->codecpar->codec_id) };
pCodecCtx = avcodec_alloc_context3(pCodec);
avcodec_parameters_to_context(pCodecCtx, pStream->codecpar);
if (avcodec_open2(pCodecCtx, pCodec, nullptr)) {
 cout << "could not open codec" << endl;
 return -1;
}

/*
* section to set up output file which is a G711 audio
*/
if (avio_open(&pOutIoContext, outFilename.data(), AVIO_FLAG_WRITE)) {
 cout << "could not open out put file" << endl;
 return -1;
}
if (!(pOutFormatCtx = avformat_alloc_context())) {
 cout << "could not create format conext" << endl;
 cleanUp();
 return -1;
}
pOutFormatCtx->pb = pOutIoContext;
if (!(pOutFormatCtx->oformat = av_guess_format(nullptr, outFilename.data(), nullptr))) {
 cout << "could not find output file format" << endl;
 cleanUp();
 return -1;
}
if (!(pOutFormatCtx->url = av_strdup(outFilename.data()))) {
 cout << "could not allocate file name" << endl;
 cleanUp();
 return -1;
}
if (!(pOutCodec = avcodec_find_encoder(AV_CODEC_ID_PCM_ALAW))) {
 cout << "codec not found" << endl;
 cleanUp();
 return -1;
}
if (!(pOutStream = avformat_new_stream(pOutFormatCtx, nullptr))) {
 cout << "could not create new stream" << endl;
 cleanUp();
 return -1;
}
if (!(pOutCodecCtx = avcodec_alloc_context3(pOutCodec))) {
 cout << "could not allocate codec context" << endl;
 return -1;
}
av_channel_layout_default(&pOutCodecCtx->ch_layout, OUTPUT_CHANNELS);
pOutCodecCtx->sample_rate = SAMPLE_RATE;
pOutCodecCtx->sample_fmt = pOutCodec->sample_fmts[0];
pOutCodecCtx->bit_rate = OUT_BIT_RATE;

//setting sample rate for the container
pOutStream->time_base.den = SAMPLE_RATE;
pOutStream->time_base.num = 1;
if (pOutFormatCtx->oformat->flags & AVFMT_GLOBALHEADER)
 pOutCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;

if (avcodec_open2(pOutCodecCtx, pOutCodec, nullptr)) {
 cout << "could not open output codec" << endl;
 cleanUp();
 return -1;
}
if ((avcodec_parameters_from_context(pOutStream->codecpar, pOutCodecCtx)) < 0) {
 cout << "could not initialize stream parameters" << endl;
} 

AVPacket* packet = av_packet_alloc();

swr = swr_alloc();
swr_alloc_set_opts2(&swr, &pOutCodecCtx->ch_layout, pOutCodecCtx->sample_fmt, pOutCodecCtx->sample_rate,&pCodecCtx->ch_layout, pCodecCtx->sample_fmt, pCodecCtx->sample_rate, 0, nullptr);
swr_init(swr);

int ret{};
int bSize{};
while (av_read_frame(pFormatCtx, packet) >= 0) {
 AVFrame* pFrame = av_frame_alloc();
 AVFrame* pOutFrame = av_frame_alloc();
 if (packet->stream_index == audiostream) {
 ret = avcodec_send_packet(pCodecCtx, packet);
 while (ret >= 0) {
 ret = avcodec_receive_frame(pCodecCtx, pFrame);
 if (ret == AVERROR(EAGAIN))
 continue;
 else if (ret == AVERROR_EOF)
 break;
 dstNmbrSamples = av_rescale_rnd(swr_get_delay(swr, pCodecCtx->sample_rate) + pFrame->nb_samples, pOutCodecCtx->sample_rate, pCodecCtx->sample_rate, AV_ROUND_UP);
 if ((av_samples_alloc_array_and_samples(&convertedSamplesBuffer, &dstLineSize, pOutCodecCtx->ch_layout.nb_channels,dstNmbrSamples, pOutCodecCtx->sample_fmt, 0)) < 0) {
 cout << "coult not allocate samples array and buffer" << endl;
 }
 int channel_samples_count{ 0 };
 channel_samples_count = swr_convert(swr, convertedSamplesBuffer, dstNmbrSamples, (const uint8_t**)pFrame->data, pFrame->nb_samples);
 bSize = av_samples_get_buffer_size(&dstLineSize, pOutCodecCtx->ch_layout.nb_channels, channel_samples_count, pOutCodecCtx->sample_fmt, 0);
 cout << "no of samples is " << channel_samples_count << " the buffer size " << bSize << endl;
 pOutFrame->nb_samples = channel_samples_count;
 av_channel_layout_copy(&pOutFrame->ch_layout, &pOutCodecCtx->ch_layout);
 pOutFrame->format = pOutCodecCtx->sample_fmt;
 pOutFrame->sample_rate = pOutCodecCtx->sample_rate;
 if ((av_frame_get_buffer(pOutFrame, 0)) < 0) {
 cout << "could not allocate output frame samples " << endl;
 av_frame_free(&pOutFrame);
 }
 
 //populate out frame buffer
 av_frame_make_writable(pOutFrame);
 for (int i{ 0 }; i < bSize; i++) {
 pOutFrame->data[0][i] = convertedSamplesBuffer[0][i];
 cout << pOutFrame->data[0][i];
 }
 if (pOutFrame) {
 pOutFrame->pts = pts;
 pts += pOutFrame->nb_samples;
 }
 int res = avcodec_send_frame(pOutCodecCtx, pOutFrame);
 if (res < 0) {
 cout << "error sending frame to encoder" << endl;
 cleanUp();
 return -1;
 }
 //int er = avformat_write_header(pOutFormatCtx,nullptr);
 AVPacket* pOutPacket = av_packet_alloc();
 pOutPacket->time_base.num = 1;
 pOutPacket->time_base.den = 8000;
 if (pOutPacket == nullptr) {
 cout << "unable to allocate packet" << endl;
 }
 while (res >= 0) {
 res = avcodec_receive_packet(pOutCodecCtx, pOutPacket);
 if (res == AVERROR(EAGAIN))
 continue;
 else if (ret == AVERROR_EOF)
 break;
 av_packet_rescale_ts(pOutPacket, pOutCodecCtx->time_base, pOutFormatCtx->streams[0]->time_base);
 //av_dump_format(pOutFormatCtx, 0, outFilename.c_str(), 1);
 if (av_write_frame(pOutFormatCtx, pOutPacket) < 0) {
 cout << "could not write frame" << endl;
 }
 }
 }
}
 av_frame_free(&pFrame);
 av_frame_free(&pOutFrame);
}
if (av_write_trailer(pOutFormatCtx) < 0) {
 cout << "could not write file trailer" << endl;
}
swr_free(&swr);
avcodec_free_context(&pOutCodecCtx);
av_packet_free(&packet);
}
</iostream>


Error/Exception


The exception is thrown when I call


if (av_write_frame(pOutFormatCtx, pOutPacket) < 0) { cout << "could not write frame" << endl; }

I also called this line

//int er = avformat_write_header(pOutFormatCtx,nullptr);


to see if I will get an exception but it did not throw any exception.


I have spent weeks on this issue with no success.
My goal is to take any audio from a file an be able to resample it if need be, and transcode it to PCM_ALAW.
I will appreciate any help I can get.


-
SegFault while freeing nvenc hwdevice_ctx
23 février 2024, par camelCaseFor a project, I created a class encoding the output of an OpenGL
renderbuffer
object usingh264_nvenc
. Unfortunately, tidying up doesn't work, and the program crashes with a SegFault. The reason is accessing an unaccessable memory region, happening twice in the final lines (see below) when callingav_buffer_unref( &_hwDeviceRefCtx )
and implicitely also duringavcodec_free_context( &_pCodecCtx )
, but both calls are required for shutting down.

The (in this case relevant)
valgrind
-output is

Invalid read of size 8
 at 0x48AD987: UnknownInlinedFun (buffer.c:121)
 by 0x48AD987: UnknownInlinedFun (buffer.c:144)
 by 0x48AD987: av_buffer_unref (buffer.c:139)
 by 0x5D06D7A: avcodec_close (avcodec.c:486)
 by 0x628DD7D: avcodec_free_context (options.c:175)
 by 0x10A863: main (main.cpp:115)
 Address 0x17812700 is 0 bytes inside a block of size 24 free'd
 at 0x484488F: free (vg_replace_malloc.c:985)
 by 0x48AD98F: UnknownInlinedFun (buffer.c:127)
 by 0x48AD98F: UnknownInlinedFun (buffer.c:144)
 by 0x48AD98F: av_buffer_unref (buffer.c:139)
 by 0x48BE098: hwframe_ctx_free (hwcontext.c:240)
 by 0x48AD9A6: UnknownInlinedFun (buffer.c:133)
 by 0x48AD9A6: UnknownInlinedFun (buffer.c:144)
 by 0x48AD9A6: av_buffer_unref (buffer.c:139)
 by 0x5D06D0A: UnknownInlinedFun (decode.c:1261)
 by 0x5D06D0A: avcodec_close (avcodec.c:465)
 by 0x628DD7D: avcodec_free_context (options.c:175)
 by 0x10A863: main (main.cpp:115)
 Block was alloc'd at
 at 0x4849366: posix_memalign (vg_replace_malloc.c:2099)
 by 0x48D9BD5: av_malloc (mem.c:105)
 by 0x48D9DAD: av_mallocz (mem.c:256)
 by 0x48AD8DD: UnknownInlinedFun (buffer.c:44)
 by 0x48AD8DD: av_buffer_create (buffer.c:64)
 by 0x48BDDEB: av_hwdevice_ctx_alloc (hwcontext.c:179)
 by 0x48BDF29: av_hwdevice_ctx_create (hwcontext.c:622)
 by 0x10A482: main (main.cpp:43)

Invalid free() / delete / delete[] / realloc()
 at 0x484488F: free (vg_replace_malloc.c:985)
 by 0x48AD98F: UnknownInlinedFun (buffer.c:127)
 by 0x48AD98F: UnknownInlinedFun (buffer.c:144)
 by 0x48AD98F: av_buffer_unref (buffer.c:139)
 by 0x5D06D7A: avcodec_close (avcodec.c:486)
 by 0x628DD7D: avcodec_free_context (options.c:175)
 by 0x10A863: main (main.cpp:115)
 Address 0x17812700 is 0 bytes inside a block of size 24 free'd
 at 0x484488F: free (vg_replace_malloc.c:985)
 by 0x48AD98F: UnknownInlinedFun (buffer.c:127)
 by 0x48AD98F: UnknownInlinedFun (buffer.c:144)
 by 0x48AD98F: av_buffer_unref (buffer.c:139)
 by 0x48BE098: hwframe_ctx_free (hwcontext.c:240)
 by 0x48AD9A6: UnknownInlinedFun (buffer.c:133)
 by 0x48AD9A6: UnknownInlinedFun (buffer.c:144)
 by 0x48AD9A6: av_buffer_unref (buffer.c:139)
 by 0x5D06D0A: UnknownInlinedFun (decode.c:1261)
 by 0x5D06D0A: avcodec_close (avcodec.c:465)
 by 0x628DD7D: avcodec_free_context (options.c:175)
 by 0x10A863: main (main.cpp:115)
 Block was alloc'd at
 at 0x4849366: posix_memalign (vg_replace_malloc.c:2099)
 by 0x48D9BD5: av_malloc (mem.c:105)
 by 0x48D9DAD: av_mallocz (mem.c:256)
 by 0x48AD8DD: UnknownInlinedFun (buffer.c:44)
 by 0x48AD8DD: av_buffer_create (buffer.c:64)
 by 0x48BDDEB: av_hwdevice_ctx_alloc (hwcontext.c:179)
 by 0x48BDF29: av_hwdevice_ctx_create (hwcontext.c:622)
 by 0x10A482: main (main.cpp:43)



that is also duplicated (due to the calls to
avcodec_free_context()
andav_buffer_unref()
).

The question is : How can I fix this ?


The (more or less) minimal (not) working example reads


#include <string>

extern "C" {
 #include <libavutil></libavutil>opt.h>
 #include <libavcodec></libavcodec>avcodec.h>
 #include <libavformat></libavformat>avformat.h>
 #include <libavutil></libavutil>hwcontext.h>
 #include <libavutil></libavutil>pixdesc.h>
 #include <libavutil></libavutil>hwcontext_cuda.h>
}

//(former) libx264 encoding based on https://github.com/FFmpeg/FFmpeg/blob/master/doc/examples/muxing.c
//update to h264_nvenc with a lot of help from https://stackoverflow.com/questions/49862610/opengl-to-ffmpeg-encode
//and some additional info of https://github.com/FFmpeg/FFmpeg/blob/master/doc/examples/vaapi_encode.c

int main() {
 const int _SrcImageWidth=640;
 const int _SrcImageHeight=480;
 
 const AVOutputFormat *_oFmt = nullptr;
 AVFormatContext *_oFmtCtx = nullptr;
 
 const AVCodec *_pCodec = nullptr;
 AVCodecContext *_pCodecCtx = nullptr;
 
 AVFrame* _frame;
 AVPacket* _packet;
 AVStream* _stream;
 
 AVBufferRef *_hwDeviceRefCtx = nullptr;
 const CUcontext* _cudaCtx;
 
 const std::string _OutFileName = "output.mkv";
 
 //constructor part
 int ret;

 //output format context 
 avformat_alloc_output_context2( &_oFmtCtx, nullptr, nullptr, _OutFileName.c_str() );
 _oFmt = _oFmtCtx->oformat;

 //hardware format context
 ret = av_hwdevice_ctx_create( &_hwDeviceRefCtx, AV_HWDEVICE_TYPE_CUDA, "NVIDIA GeForce RTX 4070", nullptr, 0 );

 //hardware frame context for device buffer allocation
 AVBufferRef* hwFrameRefCtx = av_hwframe_ctx_alloc( _hwDeviceRefCtx );
 AVHWFramesContext* hwFrameCtx = (AVHWFramesContext*) (hwFrameRefCtx->data);
 hwFrameCtx->width = _SrcImageWidth;
 hwFrameCtx->height = _SrcImageHeight;
 hwFrameCtx->sw_format = AV_PIX_FMT_0BGR32;
 hwFrameCtx->format = AV_PIX_FMT_CUDA;
 hwFrameCtx->device_ref = _hwDeviceRefCtx;
 hwFrameCtx->device_ctx = (AVHWDeviceContext*) _hwDeviceRefCtx->data;

 ret = av_hwframe_ctx_init( hwFrameRefCtx );

 //get cuda context
 const AVHWDeviceContext* hwDeviceCtx = (AVHWDeviceContext*)(_hwDeviceRefCtx->data);
 const AVCUDADeviceContext* cudaDeviceCtx = (AVCUDADeviceContext*)(hwDeviceCtx->hwctx);
 _cudaCtx = &(cudaDeviceCtx->cuda_ctx);

 //codec context
 _pCodec = avcodec_find_encoder_by_name( "h264_nvenc" );

 _packet = av_packet_alloc();

 _stream = avformat_new_stream( _oFmtCtx, nullptr );
 _stream->id = _oFmtCtx->nb_streams - 1;
 _pCodecCtx = avcodec_alloc_context3( _pCodec );

 _pCodecCtx->qmin = 18;
 _pCodecCtx->qmax = 20;
 _pCodecCtx->width = _SrcImageWidth;
 _pCodecCtx->height = _SrcImageHeight;
 _pCodecCtx->framerate = (AVRational) {25,1};
 _pCodecCtx->time_base = (AVRational) {1,25};
 _stream->time_base = _pCodecCtx->time_base;
 _pCodecCtx->gop_size = 12; //I-Frame every at most 12 frames
 _pCodecCtx->max_b_frames = 2;
 _pCodecCtx->pix_fmt = AV_PIX_FMT_CUDA; //required to use renderbuffer as src
 _pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
 _pCodecCtx->sw_pix_fmt = AV_PIX_FMT_0BGR32; 
 _pCodecCtx->hw_device_ctx = _hwDeviceRefCtx;
 _pCodecCtx->hw_frames_ctx = av_buffer_ref( hwFrameRefCtx );
 av_opt_set(_pCodecCtx->priv_data, "preset", "p7", 0);
 av_opt_set(_pCodecCtx->priv_data, "rc", "vbr", 0);
 if( _oFmtCtx->oformat->flags & AVFMT_GLOBALHEADER ) {
 _pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
 }

 ret = avcodec_open2( _pCodecCtx, _pCodec, nullptr );
 avcodec_parameters_from_context( _stream->codecpar, _pCodecCtx );

 if (!(_oFmtCtx->oformat->flags & AVFMT_NOFILE)) {
 ret = avio_open(&_oFmtCtx->pb, _OutFileName.c_str(), AVIO_FLAG_WRITE);
 }
 ret = avformat_write_header( _oFmtCtx, nullptr );

 //use hardware frame from above
 _frame = av_frame_alloc();
 ret = av_hwframe_get_buffer( _pCodecCtx->hw_frames_ctx, _frame, 0 );
 _frame->pts = 1;

 av_buffer_unref( &hwFrameRefCtx );

 //destructor part
 av_frame_free( &_frame );
 av_packet_free( &_packet );

 av_write_trailer( _oFmtCtx );
 avio_closep( &_oFmtCtx->pb );

 avformat_free_context( _oFmtCtx );

 avcodec_free_context( &_pCodecCtx );
 av_buffer_unref( &_hwDeviceRefCtx );

 return 0;
}
</string>


and compiles with (linux user)


g++ -lavutil -lavformat -lavcodec -lz -lavutil -lswscale -lswresample -lm -ggdb3 -I/opt/cuda/include main.cpp



Thanks in advance !