
Recherche avancée
Autres articles (34)
-
MediaSPIP v0.2
21 juin 2013, parMediaSPIP 0.2 est la première version de MediaSPIP stable.
Sa date de sortie officielle est le 21 juin 2013 et est annoncée ici.
Le fichier zip ici présent contient uniquement les sources de MediaSPIP en version standalone.
Comme pour la version précédente, il est nécessaire d’installer manuellement l’ensemble des dépendances logicielles sur le serveur.
Si vous souhaitez utiliser cette archive pour une installation en mode ferme, il vous faudra également procéder à d’autres modifications (...) -
Mise à disposition des fichiers
14 avril 2011, parPar défaut, lors de son initialisation, MediaSPIP ne permet pas aux visiteurs de télécharger les fichiers qu’ils soient originaux ou le résultat de leur transformation ou encodage. Il permet uniquement de les visualiser.
Cependant, il est possible et facile d’autoriser les visiteurs à avoir accès à ces documents et ce sous différentes formes.
Tout cela se passe dans la page de configuration du squelette. Il vous faut aller dans l’espace d’administration du canal, et choisir dans la navigation (...) -
MediaSPIP version 0.1 Beta
16 avril 2011, parMediaSPIP 0.1 beta est la première version de MediaSPIP décrétée comme "utilisable".
Le fichier zip ici présent contient uniquement les sources de MediaSPIP en version standalone.
Pour avoir une installation fonctionnelle, il est nécessaire d’installer manuellement l’ensemble des dépendances logicielles sur le serveur.
Si vous souhaitez utiliser cette archive pour une installation en mode ferme, il vous faudra également procéder à d’autres modifications (...)
Sur d’autres sites (4006)
-
ffmpeg piped output producing incorrect metadata frame count with Python
6 décembre 2024, par XorgonUsing Python, I am attempting to use ffmpeg to compress videos and put them in a PowerPoint. This works great, however, the video files themselves have incorrect frame counts which can cause issues when I read from those videos in other code.


Edit for clarification : by "frame count" I mean the metadata frame count. The actual number of frames contained in the video is correct, but querying the metadata gives an incorrect frame count.


Having eliminated the PowerPoint aspect of the code, I've narrowed this down to the following minimal reproducing example of saving an output from an ffmpeg pipe :


from subprocess import Popen, PIPE

video_path = 'test_mp4.mp4'

ffmpeg_pipe = Popen(['ffmpeg',
 '-y', # Overwrite files
 '-i', f'{video_path}', # Input from file
 '-f', 'avi', # Output format
 '-c:v', 'libx264', # Codec
 '-'], # Output to pipe
 stdout=PIPE)

new_path = "piped_video.avi"
vid_file = open(new_path, "wb")
vid_file.write(ffmpeg_pipe.stdout.read())
vid_file.close()



I've tested several different videos. One small example video that I've tested can be found here.


I've tried a few different codecs with
avi
format and triedlibvpx
withwebm
format. For theavi
outputs, the frame count usually reads as1073741824
(2^30). Weirdly, for thewebm
format, the frame count read as-276701161105643264
.

This is a snippet I used to read the frame count, but one could also see the error by opening the video details in Windows Explorer and seeing the total time as something like 9942 hours, 3 minutes, and 14 seconds.


import cv2

video_path = 'test_mp4.mp4'
new_path = "piped_video.webm"

cap = cv2.VideoCapture(video_path)
print(f"Original video frame count: = {int(cap.get(cv2.CAP_PROP_FRAME_COUNT)):d}")
cap.release()

cap = cv2.VideoCapture(new_path)
print(f"Piped video frame count: = {int(cap.get(cv2.CAP_PROP_FRAME_COUNT)):d}")
cap.release()



For completeness, here is the ffmpeg output :


ffmpeg version 2023-06-11-git-09621fd7d9-full_build-www.gyan.dev Copyright (c) 2000-2023 the FFmpeg developers
 built with gcc 12.2.0 (Rev10, Built by MSYS2 project)
 configuration: --enable-gpl --enable-version3 --enable-static --disable-w32threads --disable-autodetect --enable-fontconfig --enable-iconv --enable-gnutls --enable-libxml2 --enable-gmp --enable-bzlib --enable-lzma --enable-libsnappy --enable-zlib --enable-librist --enable-libsrt --enable-libssh --enable-libzmq --enable-avisynth --enable-libbluray --enable-libcaca --enable-sdl2 --enable-libaribb24 --enable-libaribcaption --enable-libdav1d --enable-libdavs2 --enable-libuavs3d --enable-libzvbi --enable-librav1e --enable-libsvtav1 --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libaom --enable-libjxl --enable-libopenjpeg --enable-libvpx --enable-mediafoundation --enable-libass --enable-frei0r --enable-libfreetype --enable-libfribidi --enable-liblensfun --enable-libvidstab --enable-libvmaf --enable-libzimg --enable-amf --enable-cuda-llvm --enable-cuvid --enable-ffnvcodec --enable-nvdec --enable-nvenc --enable-d3d11va --enable-dxva2 --enable-libvpl --enable-libshaderc --enable-vulkan --enable-libplacebo --enable-opencl --enable-libcdio --enable-libgme --enable-libmodplug --enable-libopenmpt --enable-libopencore-amrwb --enable-libmp3lame --enable-libshine --enable-libtheora --enable-libtwolame --enable-libvo-amrwbenc --enable-libcodec2 --enable-libilbc --enable-libgsm --enable-libopencore-amrnb --enable-libopus --enable-libspeex --enable-libvorbis --enable-ladspa --enable-libbs2b --enable-libflite --enable-libmysofa --enable-librubberband --enable-libsoxr --enable-chromaprint
 libavutil 58. 13.100 / 58. 13.100
 libavcodec 60. 17.100 / 60. 17.100
 libavformat 60. 6.100 / 60. 6.100
 libavdevice 60. 2.100 / 60. 2.100
 libavfilter 9. 8.101 / 9. 8.101
 libswscale 7. 3.100 / 7. 3.100
 libswresample 4. 11.100 / 4. 11.100
 libpostproc 57. 2.100 / 57. 2.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'test_mp4.mp4':
 Metadata:
 major_brand : mp42
 minor_version : 0
 compatible_brands: isommp42
 creation_time : 2022-08-10T12:54:09.000000Z
 Duration: 00:00:06.67, start: 0.000000, bitrate: 567 kb/s
 Stream #0:0[0x1](eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p(progressive), 384x264 [SAR 1:1 DAR 16:11], 563 kb/s, 30 fps, 30 tbr, 30k tbn (default)
 Metadata:
 creation_time : 2022-08-10T12:54:09.000000Z
 handler_name : Mainconcept MP4 Video Media Handler
 vendor_id : [0][0][0][0]
 encoder : AVC Coding
Stream mapping:
 Stream #0:0 -> #0:0 (h264 (native) -> h264 (libx264))
Press [q] to stop, [?] for help
[libx264 @ 0000018c68c8b9c0] using SAR=1/1
[libx264 @ 0000018c68c8b9c0] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 BMI2 AVX2
[libx264 @ 0000018c68c8b9c0] profile High, level 2.1, 4:2:0, 8-bit
Output #0, avi, to 'pipe:':
 Metadata:
 major_brand : mp42
 minor_version : 0
 compatible_brands: isommp42
 ISFT : Lavf60.6.100
 Stream #0:0(eng): Video: h264 (H264 / 0x34363248), yuv420p(progressive), 384x264 [SAR 1:1 DAR 16:11], q=2-31, 30 fps, 30 tbn (default)
 Metadata:
 creation_time : 2022-08-10T12:54:09.000000Z
 handler_name : Mainconcept MP4 Video Media Handler
 vendor_id : [0][0][0][0]
 encoder : Lavc60.17.100 libx264
 Side data:
 cpb: bitrate max/min/avg: 0/0/0 buffer size: 0 vbv_delay: N/A
[out#0/avi @ 0000018c687f47c0] video:82kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 3.631060%
frame= 200 fps=0.0 q=-1.0 Lsize= 85kB time=00:00:06.56 bitrate= 106.5kbits/s speed=76.2x 
[libx264 @ 0000018c68c8b9c0] frame I:1 Avg QP:16.12 size: 3659
[libx264 @ 0000018c68c8b9c0] frame P:80 Avg QP:21.31 size: 647
[libx264 @ 0000018c68c8b9c0] frame B:119 Avg QP:26.74 size: 243
[libx264 @ 0000018c68c8b9c0] consecutive B-frames: 3.0% 53.0% 0.0% 44.0%
[libx264 @ 0000018c68c8b9c0] mb I I16..4: 17.6% 70.6% 11.8%
[libx264 @ 0000018c68c8b9c0] mb P I16..4: 0.8% 1.7% 0.6% P16..4: 17.6% 4.6% 3.3% 0.0% 0.0% skip:71.4%
[libx264 @ 0000018c68c8b9c0] mb B I16..4: 0.1% 0.3% 0.2% B16..8: 11.7% 1.4% 0.4% direct: 0.6% skip:85.4% L0:32.0% L1:59.7% BI: 8.3%
[libx264 @ 0000018c68c8b9c0] 8x8 transform intra:59.6% inter:62.4%
[libx264 @ 0000018c68c8b9c0] coded y,uvDC,uvAC intra: 48.5% 0.0% 0.0% inter: 3.5% 0.0% 0.0%
[libx264 @ 0000018c68c8b9c0] i16 v,h,dc,p: 19% 39% 25% 17%
[libx264 @ 0000018c68c8b9c0] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 21% 25% 30% 3% 3% 4% 4% 4% 5%
[libx264 @ 0000018c68c8b9c0] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 22% 20% 16% 6% 8% 8% 8% 5% 6%
[libx264 @ 0000018c68c8b9c0] i8c dc,h,v,p: 100% 0% 0% 0%
[libx264 @ 0000018c68c8b9c0] Weighted P-Frames: Y:0.0% UV:0.0%
[libx264 @ 0000018c68c8b9c0] ref P L0: 76.2% 7.9% 11.2% 4.7%
[libx264 @ 0000018c68c8b9c0] ref B L0: 85.6% 12.9% 1.5%
[libx264 @ 0000018c68c8b9c0] ref B L1: 97.7% 2.3%
[libx264 @ 0000018c68c8b9c0] kb/s:101.19



So the question is : why does this happen, and how can one avoid it ?


-
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 !


-
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.