
Recherche avancée
Autres articles (40)
-
La file d’attente de SPIPmotion
28 novembre 2010, parUne file d’attente stockée dans la base de donnée
Lors de son installation, SPIPmotion crée une nouvelle table dans la base de donnée intitulée spip_spipmotion_attentes.
Cette nouvelle table est constituée des champs suivants : id_spipmotion_attente, l’identifiant numérique unique de la tâche à traiter ; id_document, l’identifiant numérique du document original à encoder ; id_objet l’identifiant unique de l’objet auquel le document encodé devra être attaché automatiquement ; objet, le type d’objet auquel (...) -
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 -
Contribute to documentation
13 avril 2011Documentation is vital to the development of improved technical capabilities.
MediaSPIP welcomes documentation by users as well as developers - including : critique of existing features and functions articles contributed by developers, administrators, content producers and editors screenshots to illustrate the above translations of existing documentation into other languages
To contribute, register to the project users’ mailing (...)
Sur d’autres sites (7950)
-
What's wrong with how I save a vector of AVFrames as mp4 video using the h264 encoder ?
8 avril 2023, par noklaI am trying to encode a vector of AVFrames to an MP4 file using the h264 codec.


The code runs without errors but both when I try to open the saved video file with the windows media and adobe Media Encoded they it says that it is in an unsupported format.


I went through it with a debugger and everything seemed to work fine.



This is the function I used to saved the video :


void SaveVideo(std::string& output_filename, std::vector<avframe> video)
{
 // Initialize FFmpeg
 avformat_network_init();

 // Open the output file context
 AVFormatContext* format_ctx = nullptr;
 int ret = avformat_alloc_output_context2(&format_ctx, nullptr, nullptr, output_filename.c_str());
 if (ret < 0) {
 wxMessageBox("Error creating output context: ");
 wxMessageBox(av_err2str(ret));
 return;
 }

 // Open the output file
 ret = avio_open(&format_ctx->pb, output_filename.c_str(), AVIO_FLAG_WRITE);
 if (ret < 0) {
 std::cerr << "Error opening output file: " << av_err2str(ret) << std::endl;
 avformat_free_context(format_ctx);
 return;
 }

 // Create the video stream
 const AVCodec* codec = avcodec_find_encoder(AV_CODEC_ID_H264);
 if (!codec) {
 std::cerr << "Error finding H.264 encoder" << std::endl;
 avformat_free_context(format_ctx);
 return;
 }

 AVStream* stream = avformat_new_stream(format_ctx, codec);
 if (!stream) {
 std::cerr << "Error creating output stream" << std::endl;
 avformat_free_context(format_ctx);
 return;
 }

 // Set the stream parameters
 stream->codecpar->codec_id = AV_CODEC_ID_H264;
 stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
 stream->codecpar->width =video.front().width;
 stream->codecpar->height = video.front().height;
 stream->codecpar->format = AV_PIX_FMT_YUV420P;
 stream->codecpar->bit_rate = 400000;
 AVRational framerate = { 1, 30};
 stream->time_base = av_inv_q(framerate);

 // Open the codec context
 AVCodecContext* codec_ctx = avcodec_alloc_context3(codec);
 codec_ctx->codec_tag = 0;
 codec_ctx->time_base = stream->time_base;
 codec_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
 if (!codec_ctx) {
 std::cout << "Error allocating codec context" << std::endl;
 avformat_free_context(format_ctx);
 return;
 }

 ret = avcodec_parameters_to_context(codec_ctx, stream->codecpar);
 if (ret < 0) {
 std::cout << "Error setting codec context parameters: " << av_err2str(ret) << std::endl;
 avcodec_free_context(&codec_ctx);
 avformat_free_context(format_ctx);
 return;
 }
 AVDictionary* opt = NULL;
 ret = avcodec_open2(codec_ctx, codec, &opt);
 if (ret < 0) {
 wxMessageBox("Error opening codec: ");
 wxMessageBox(av_err2str(ret));
 avcodec_free_context(&codec_ctx);
 avformat_free_context(format_ctx);
 return;
 }

 // Allocate a buffer for the frame data
 AVFrame* frame = av_frame_alloc();
 if (!frame) {
 std::cerr << "Error allocating frame" << std::endl;
 avcodec_free_context(&codec_ctx);
 avformat_free_context(format_ctx);
 return;
 }

 frame->format = codec_ctx->pix_fmt;
 frame->width = codec_ctx->width;
 frame->height = codec_ctx->height;

 ret = av_frame_get_buffer(frame, 0);
 if (ret < 0) {
 std::cerr << "Error allocating frame buffer: " << av_err2str(ret) << std::endl;
 av_frame_free(&frame);
 avcodec_free_context(&codec_ctx);
 avformat_free_context(format_ctx);
 return;
 }

 // Allocate a buffer for the converted frame data
 AVFrame* converted_frame = av_frame_alloc();
 if (!converted_frame) {
 std::cerr << "Error allocating converted frame" << std::endl;
 av_frame_free(&frame);
 avcodec_free_context(&codec_ctx);
 avformat_free_context(format_ctx);
 return;
 }

 converted_frame->format = AV_PIX_FMT_YUV420P;
 converted_frame->width = codec_ctx->width;
 converted_frame->height = codec_ctx->height;

 ret = av_frame_get_buffer(converted_frame, 0);
 if (ret < 0) {
 std::cerr << "Error allocating converted frame buffer: " << av_err2str(ret) << std::endl;
 av_frame_free(&frame);
 av_frame_free(&converted_frame);
 avcodec_free_context(&codec_ctx);
 avformat_free_context(format_ctx);
 return;
 }

 // Initialize the converter
 SwsContext* converter = sws_getContext(
 codec_ctx->width, codec_ctx->height, codec_ctx->pix_fmt,
 codec_ctx->width, codec_ctx->height, AV_PIX_FMT_YUV420P,
 SWS_BICUBIC, nullptr, nullptr, nullptr
 );
 if (!converter) {
 std::cerr << "Error initializing converter" << std::endl;
 av_frame_free(&frame);
 av_frame_free(&converted_frame);
 avcodec_free_context(&codec_ctx);
 avformat_free_context(format_ctx);
 return;
 }

 // Write the header to the output file
 ret = avformat_write_header(format_ctx, nullptr);
 if (ret < 0) {
 std::cerr << "Error writing header to output file: " << av_err2str(ret) << std::endl;
 av_frame_free(&frame);
 av_frame_free(&converted_frame);
 sws_freeContext(converter);
 avcodec_free_context(&codec_ctx);
 avformat_free_context(format_ctx);
 return;
 }

 // Iterate over the frames and write them to the output file
 int frame_count = 0;
 for (auto& frame: video) {
 {
 // Convert the frame to the output format
 sws_scale(converter,
 srcFrame.data, srcFrame.linesize, 0, srcFrame.height,
 converted_frame->data, converted_frame->linesize
 );

 // Set the frame properties
 converted_frame->pts = av_rescale_q(frame_count, stream->time_base, codec_ctx->time_base);
 frame_count++;
 //converted_frame->time_base.den = codec_ctx->time_base.den;
 //converted_frame->time_base.num = codec_ctx->time_base.num;
 // Encode the frame and write it to the output
 ret = avcodec_send_frame(codec_ctx, converted_frame);
 if (ret < 0) {
 std::cerr << "Error sending frame for encoding: " << av_err2str(ret) << std::endl;
 av_frame_free(&frame);
 av_frame_free(&converted_frame);
 sws_freeContext(converter);
 avcodec_free_context(&codec_ctx);
 avformat_free_context(format_ctx);
 return;
 }
 AVPacket* pkt = av_packet_alloc();
 if (!pkt) {
 std::cerr << "Error allocating packet" << std::endl;
 return;
 }
 while (ret >= 0) {
 ret = avcodec_receive_packet(codec_ctx, pkt);
 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
 std::string a = av_err2str(ret);
 break;
 }
 else if (ret < 0) {
 wxMessageBox("Error during encoding");
 wxMessageBox(av_err2str(ret));
 av_packet_unref(pkt);
 av_frame_free(&frame);
 av_frame_free(&converted_frame);
 sws_freeContext(converter);
 avcodec_free_context(&codec_ctx);
 avformat_free_context(format_ctx);
 return;
 }

 // Write the packet to the output file
 av_packet_rescale_ts(pkt, codec_ctx->time_base, stream->time_base);
 pkt->stream_index = stream->index;
 ret = av_interleaved_write_frame(format_ctx, pkt);
 av_packet_unref(pkt);
 if (ret < 0) {
 std::cerr << "Error writing packet to output file: " << av_err2str(ret) << std::endl;
 av_frame_free(&frame);
 av_frame_free(&converted_frame);
 sws_freeContext(converter);
 avcodec_free_context(&codec_ctx);
 avformat_free_context(format_ctx);
 return;
 }
 }
 }
 }

 // Flush the encoder
 ret = avcodec_send_frame(codec_ctx, nullptr);
 if (ret < 0) {
 std::cerr << "Error flushing encoder: " << av_err2str(ret) << std::endl;
 av_frame_free(&frame);
 av_frame_free(&converted_frame);
 sws_freeContext(converter);
 avcodec_free_context(&codec_ctx);
 avformat_free_context(format_ctx);
 return;
 }

 while (ret >= 0) {
 AVPacket* pkt = av_packet_alloc();
 if (!pkt) {
 std::cerr << "Error allocating packet" << std::endl;
 return;
 }
 ret = avcodec_receive_packet(codec_ctx, pkt);
 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
 wxMessageBox("Error recieving packet");
 wxMessageBox(av_err2str(ret));
 break;
 }
 else if (ret < 0) {
 std::cerr << "Error during encoding: " << av_err2str(ret) << std::endl;
 av_packet_unref(pkt);
 av_frame_free(&frame);
 av_frame_free(&converted_frame);
 sws_freeContext(converter);
 avcodec_free_context(&codec_ctx);
 avformat_free_context(format_ctx);
 return;
 }

 // Write the packet to the output file
 av_packet_rescale_ts(pkt, codec_ctx->time_base, stream->time_base);
 pkt->stream_index = stream->index;
 ret = av_interleaved_write_frame(format_ctx, pkt);
 av_packet_unref(pkt);
 if (ret < 0) {
 std::cerr << "Error writing packet to output file: " << av_err2str(ret) << std::endl;
 av_frame_free(&frame);
 av_frame_free(&converted_frame);
 sws_freeContext(converter);
 avcodec_free_context(&codec_ctx);
 avformat_free_context(format_ctx);
 return;
 }
 }

 // Write the trailer to the output file
 ret = av_write_trailer(format_ctx);
 if (ret < 0) {
 std::cerr << "Error writing trailer to output file: " << av_err2str(ret) << std::endl;
 }

 // Free all resources
 av_frame_free(&frame);
 av_frame_free(&converted_frame);
 sws_freeContext(converter);
 avcodec_free_context(&codec_ctx);
 avformat_free_context(format_ctx);
}

</avframe>


** I know it is not the prettiest way to write this code, I just wanted to try and do something like that.


** This is an altered version of the function as the original one was inside class. I changed it so you could compile it, but it might has some errors if I forgot to change something


Any help would be appreciated.


-
Sending raw h264 video and aac audio frames to an RTMP server using ffmpeg
7 décembre 2022, par codeimpalerI am receiving raw h264 and aac audio frames from an even driven source. I am trying to send these frames to an rtmp server. 
I started working from the ffmpeg example muxing.c which successfully sends a custom stream to the rtmp server. I figure I just need to replace their frame data with my own.I found this suggestion online. I have tried How to pack raw h264 stream to flv container and send over rtmp using ffmpeg (not command) 
and
How to publish selfmade stream with ffmpeg and c++ to rtmp server ?
and a few other suggestions but none have worked for me. 
I have tried to directly memcpy my byte buffer but my code keeps failing
at ret = avcodec_encode_video2(c, &pkt, frame, &got_packet).
Specifically, I get an invalid access error.
For a little more context, anytime I receive a frame (which is event driven), void RTMPWriter::WriteVideoFrame(...) is called. Assume the constructor has already been called before the first frame is received. 
I am not that familiar with ffmpeg and there could be several things wrong with the code. Any input will be really appreciated.



#define STREAM_FRAME_RATE 25 /* 25 images/s */
 #define STREAM_PIX_FMT AV_PIX_FMT_YUV420P /* default pix_fmt */
 #define SCALE_FLAGS SWS_BICUBIC
 RTMPWriter::RTMPWriter()
 : seenKeyFrame(false),
 video_st({ 0 }), 
 audio_st({ 0 }),
 have_video(0), 
 have_audio(0)
 {

 const char *filename;
 AVCodec *audio_codec = NULL, *video_codec = NULL;
 int ret;

 int encode_video = 0, encode_audio = 0;
 AVDictionary *opt = NULL;
 int i;

 /* Initialize libavcodec, and register all codecs and formats. */
 av_register_all();

 avformat_network_init();

 String^ StreamURL = "StreamURL";
 String^ out_uri = safe_cast(ApplicationData::Current->LocalSettings->Values->Lookup(StreamURL));
 std::wstring out_uriW(out_uri->Begin());
 std::string out_uriA(out_uriW.begin(), out_uriW.end());
 filename = out_uriA.c_str(); 

 /* allocate the output media context */
 avformat_alloc_output_context2(&oc, NULL, "flv", filename);
 if (!oc)
 {
 OutputDebugString(L"Could not deduce output format from file extension: using MPEG.\n");
 avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
 }
 if (!oc)
 {
 OutputDebugString(L"Could not allocate using MPEG.\n");
 }


 fmt = oc->oformat;

 /* Add the audio and video streams using the default format codecs
 * and initialize the codecs. */
 if (fmt->video_codec != AV_CODEC_ID_NONE) {
 add_stream(&video_st, oc, &video_codec, fmt->video_codec);
 have_video = 1;
 encode_video = 1;
 }
 if (fmt->audio_codec != AV_CODEC_ID_NONE) {
 add_stream(&audio_st, oc, &audio_codec, fmt->audio_codec);
 have_audio = 1;
 encode_audio = 1;
 }

 /* Now that all the parameters are set, we can open the audio and
 * video codecs and allocate the necessary encode buffers. */
 if (have_video)
 {
 open_video(oc, video_codec, &video_st, opt);
 }

 if (have_audio)
 {
 open_audio(oc, audio_codec, &audio_st, opt);
 }

 av_dump_format(oc, 0, filename, 1);

 /* open the output file, if needed */
 if (!(fmt->flags & AVFMT_NOFILE))
 {
 ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
 if (ret < 0)
 {
 OutputDebugString(L"Could not open ");
 OutputDebugString(out_uri->Data());
 }
 }

 /* Write the stream header, if any. */
 ret = avformat_write_header(oc, &opt);
 if (ret < 0)
 {
 OutputDebugString(L"Error occurred when writing stream header \n");
 }

 }

 void RTMPWriter::WriteVideoFrame(
 boolean isKeyFrame,
 boolean hasDiscontinuity,
 UINT64 frameId,
 UINT32 videoBufferLength,
 BYTE *videoBytes)
 {

 int ret;
 AVCodecContext *c;
 AVFrame* frame;
 int got_packet = 0;
 AVPacket pkt = { 0 };

 c = video_st.enc;

 frame = get_video_frame(videoBufferLength, videoBytes);

 /* encode the image */
 ret = avcodec_encode_video2(c, &pkt, frame, &got_packet);
 if (ret < 0) {
 OutputDebugString(L"Error encoding video frame: \n")
 }

 if (got_packet) 
 {
 ret = write_frame(oc, &c->time_base, video_st.st, &pkt);
 }
 else {
 ret = 0;
 }

 if (ret < 0) {
 OutputDebugString(L"Error while writing video frame: %s\n");
 }
 }

 AVFrame * RTMPWriter::get_video_frame(
 UINT32 videoBufferLength,
 BYTE *videoBytes)
 {
 AVCodecContext *c = video_st.enc;

 if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
 /* as we only generate a YUV420P picture, we must convert it
 * to the codec pixel format if needed */
 if (!video_st.sws_ctx) {
 video_st.sws_ctx = sws_getContext(c->width, c->height,
 AV_PIX_FMT_YUV420P,
 c->width, c->height,
 c->pix_fmt,
 SCALE_FLAGS, NULL, NULL, NULL);
 if (!video_st.sws_ctx) {
 fprintf(stderr,
 "Could not initialize the conversion context\n");
 exit(1);
 }
 }
 fill_yuv_image(video_st.tmp_frame, video_st.next_pts, c->width, c->height, videoBufferLength, videoBytes);
 sws_scale(video_st.sws_ctx,
 (const uint8_t * const *)video_st.tmp_frame->data, video_st.tmp_frame->linesize,
 0, c->height, video_st.frame->data, video_st.frame->linesize);
 }
 else {
 fill_yuv_image(video_st.frame, video_st.next_pts, c->width, c->height, videoBufferLength, videoBytes);
 }

 video_st.frame->pts = video_st.next_pts++;

 return video_st.frame;
 }

 /* Prepare a dummy image. */
 void RTMPWriter::fill_yuv_image(
 AVFrame *pict, 
 int frame_index,
 int width, 
 int height, 
 UINT32 videoBufferLength,
 BYTE *videoBytes)
 {
 //int x, y, i, ret;

 /* when we pass a frame to the encoder, it may keep a reference to it
 * internally;
 * make sure we do not overwrite it here
 */
 ret = av_frame_make_writable(pict);
 if (ret < 0) 
 {
 OutputDebugString(L"Unable to make piture writable");
 }

 memcpy(pict->data, videoBytes, videoBufferLength);

 //i = frame_index;

 ///* Y */
 //for (y = 0; y < height; y++)
 // for (x = 0; x < width; x++)
 // pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;

 ///* Cb and Cr */
 //for (y = 0; y < height / 2; y++) {
 // for (x = 0; x < width / 2; x++) {
 // pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
 // pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
 // }
 //}
 }

 void RTMPWriter::WriteAudioFrame()
 {

 }

 /* Add an output stream. */
 void RTMPWriter::add_stream(
 OutputStream *ost, 
 AVFormatContext *oc,
 AVCodec **codec,
 enum AVCodecID codec_id)
 {
 AVCodecContext *c;
 int i;

 /* find the encoder */
 *codec = avcodec_find_encoder(codec_id);
 if (!(*codec)) {
 OutputDebugString(L"Could not find encoder for '%s'\n");
 //avcodec_get_name(codec_id));
 exit(1);
 }

 ost->st = avformat_new_stream(oc, NULL);
 if (!ost->st) {
 OutputDebugString(L"Could not allocate stream\n");
 exit(1);
 }
 ost->st->id = oc->nb_streams - 1;
 c = avcodec_alloc_context3(*codec);
 if (!c) {
 OutputDebugString(L"Could not alloc an encoding context\n");
 exit(1);
 }
 ost->enc = c;

 switch ((*codec)->type) {
 case AVMEDIA_TYPE_AUDIO:
 c->sample_fmt = (*codec)->sample_fmts ?
 (*codec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP;
 c->bit_rate = 64000;
 c->sample_rate = 44100;
 if ((*codec)->supported_samplerates) {
 c->sample_rate = (*codec)->supported_samplerates[0];
 for (i = 0; (*codec)->supported_samplerates[i]; i++) {
 if ((*codec)->supported_samplerates[i] == 44100)
 c->sample_rate = 44100;
 }
 }
 c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
 c->channel_layout = AV_CH_LAYOUT_STEREO;
 if ((*codec)->channel_layouts) {
 c->channel_layout = (*codec)->channel_layouts[0];
 for (i = 0; (*codec)->channel_layouts[i]; i++) {
 if ((*codec)->channel_layouts[i] == AV_CH_LAYOUT_STEREO)
 c->channel_layout = AV_CH_LAYOUT_STEREO;
 }
 }
 c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
 ost->st->time_base = /*(AVRational)*/{ 1, c->sample_rate };
 break;

 case AVMEDIA_TYPE_VIDEO:
 c->codec_id = codec_id;

 c->bit_rate = 400000;
 /* Resolution must be a multiple of two. */
 c->width = 352;
 c->height = 288;
 /* timebase: This is the fundamental unit of time (in seconds) in terms
 * of which frame timestamps are represented. For fixed-fps content,
 * timebase should be 1/framerate and timestamp increments should be
 * identical to 1. */
 ost->st->time_base = /*(AVRational)*/{ 1, STREAM_FRAME_RATE };
 c->time_base = ost->st->time_base;

 c->gop_size = 12; /* emit one intra frame every twelve frames at most */
 c->pix_fmt = STREAM_PIX_FMT;
 if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
 /* just for testing, we also add B-frames */
 c->max_b_frames = 2;
 }
 if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
 /* Needed to avoid using macroblocks in which some coeffs overflow.
 * This does not happen with normal video, it just happens here as
 * the motion of the chroma plane does not match the luma plane. */
 c->mb_decision = 2;
 }
 break;

 default:
 break;
 }

 /* Some formats want stream headers to be separate. */
 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
 c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
 }

AVFrame * RTMPWriter::alloc_audio_frame(
 enum AVSampleFormat sample_fmt,
 uint64_t channel_layout,
 int sample_rate, int nb_samples)
{
 AVFrame *frame = av_frame_alloc();
 int ret;

 if (!frame) {
 OutputDebugString(L"Error allocating an audio frame\n");
 exit(1);
 }

 frame->format = sample_fmt;
 frame->channel_layout = channel_layout;
 frame->sample_rate = sample_rate;
 frame->nb_samples = nb_samples;

 if (nb_samples) {
 ret = av_frame_get_buffer(frame, 0);
 if (ret < 0) {
 OutputDebugString(L"Error allocating an audio buffer\n");
 exit(1);
 }
 }

 return frame;
 }




void RTMPWriter::open_audio(
 AVFormatContext *oc, 
 AVCodec *codec, 
 OutputStream *ost, 
 AVDictionary *opt_arg)
{
 AVCodecContext *c;
 int nb_samples;
 int ret;
 AVDictionary *opt = NULL;

 c = ost->enc;

 /* open it */
 av_dict_copy(&opt, opt_arg, 0);
 ret = avcodec_open2(c, codec, &opt);
 av_dict_free(&opt);
 if (ret < 0) {
 OutputDebugString(L"Could not open audio codec: %s\n");// , av_err2str(ret));
 exit(1);
 }

 /* init signal generator */
 ost->t = 0;
 ost->tincr = 2 * M_PI * 110.0 / c->sample_rate;
 /* increment frequency by 110 Hz per second */
 ost->tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;

 if (c->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE)
 nb_samples = 10000;
 else
 nb_samples = c->frame_size;

 ost->frame = alloc_audio_frame(c->sample_fmt, c->channel_layout,
 c->sample_rate, nb_samples);
 ost->tmp_frame = alloc_audio_frame(AV_SAMPLE_FMT_S16, c->channel_layout,
 c->sample_rate, nb_samples);

 /* copy the stream parameters to the muxer */
 ret = avcodec_parameters_from_context(ost->st->codecpar, c);
 if (ret < 0) {
 OutputDebugString(L"Could not copy the stream parameters\n");
 exit(1);
 }

 /* create resampler context */
 ost->swr_ctx = swr_alloc();
 if (!ost->swr_ctx) {
 OutputDebugString(L"Could not allocate resampler context\n");
 exit(1);
 }

 /* set options */
 av_opt_set_int(ost->swr_ctx, "in_channel_count", c->channels, 0);
 av_opt_set_int(ost->swr_ctx, "in_sample_rate", c->sample_rate, 0);
 av_opt_set_sample_fmt(ost->swr_ctx, "in_sample_fmt", AV_SAMPLE_FMT_S16, 0);
 av_opt_set_int(ost->swr_ctx, "out_channel_count", c->channels, 0);
 av_opt_set_int(ost->swr_ctx, "out_sample_rate", c->sample_rate, 0);
 av_opt_set_sample_fmt(ost->swr_ctx, "out_sample_fmt", c->sample_fmt, 0);

 /* initialize the resampling context */
 if ((ret = swr_init(ost->swr_ctx)) < 0) {
 OutputDebugString(L"Failed to initialize the resampling context\n");
 exit(1);
 }
}

int RTMPWriter::write_frame(
 AVFormatContext *fmt_ctx, 
 const AVRational *time_base, 
 AVStream *st, 
 AVPacket *pkt)
{
 /* rescale output packet timestamp values from codec to stream timebase */
 av_packet_rescale_ts(pkt, *time_base, st->time_base);
 pkt->stream_index = st->index;

 /* Write the compressed frame to the media file. */
 //log_packet(fmt_ctx, pkt);
 OutputDebugString(L"Actually sending video frame: %s\n");
 return av_interleaved_write_frame(fmt_ctx, pkt);
}


AVFrame *RTMPWriter::alloc_picture(
 enum AVPixelFormat pix_fmt, 
 int width, 
 int height)
{
 AVFrame *picture;
 int ret;

 picture = av_frame_alloc();
 if (!picture)
 return NULL;

 picture->format = pix_fmt;
 picture->width = width;
 picture->height = height;

 /* allocate the buffers for the frame data */
 ret = av_frame_get_buffer(picture, 32);
 if (ret < 0) {
 fprintf(stderr, "Could not allocate frame data.\n");
 exit(1);
 }

 return picture;
}

void RTMPWriter::open_video(
 AVFormatContext *oc, 
 AVCodec *codec, 
 OutputStream *ost, 
 AVDictionary *opt_arg)
{
 int ret;
 AVCodecContext *c = ost->enc;
 AVDictionary *opt = NULL;

 av_dict_copy(&opt, opt_arg, 0);

 /* open the codec */
 ret = avcodec_open2(c, codec, &opt);
 av_dict_free(&opt);
 if (ret < 0) {
 OutputDebugString(L"Could not open video codec: %s\n");// , av_err2str(ret));
 exit(1);
 }

 /* allocate and init a re-usable frame */
 ost->frame = alloc_picture(c->pix_fmt, c->width, c->height);
 if (!ost->frame) {
 OutputDebugString(L"Could not allocate video frame\n");
 exit(1);
 }

 /* If the output format is not YUV420P, then a temporary YUV420P
 * picture is needed too. It is then converted to the required
 * output format. */
 ost->tmp_frame = NULL;
 if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
 ost->tmp_frame = alloc_picture(AV_PIX_FMT_YUV420P, c->width, c->height);
 if (!ost->tmp_frame) {
 OutputDebugString(L"Could not allocate temporary picture\n");
 exit(1);
 }
 }

 /* copy the stream parameters to the muxer */
 ret = avcodec_parameters_from_context(ost->st->codecpar, c);
 if (ret < 0) {
 OutputDebugString(L"Could not copy the stream parameters\n");
 exit(1);
 }
}

void RTMPWriter::close_stream(AVFormatContext *oc, OutputStream *ost)
{
 avcodec_free_context(&ost->enc);
 av_frame_free(&ost->frame);
 av_frame_free(&ost->tmp_frame);
 sws_freeContext(ost->sws_ctx);
 swr_free(&ost->swr_ctx);
}

RTMPWriter::~RTMPWriter()
{
 av_write_trailer(oc);
 /* Close each codec. */
 if (have_video)
 close_stream(oc, &video_st);
 if (have_audio)
 close_stream(oc, &audio_st);

 if (!(fmt->flags & AVFMT_NOFILE))
 /* Close the output file. */
 avio_closep(&oc->pb);

 /* free the stream */
 avformat_free_context(oc);
}



-
FFmpeg avcodec_open2 throws -22 ("Invalid Argument")
14 avril 2023, par stupidbutseekingI got stuck trying to write a simple video conversion using C++ and ffmpeg.


When trying to convert a video using FFmpeg, calling avcodec_open2 fails with the code "-22" which seems to be an "Invalid Argument"-error.


I can't figure out why it fails, nor what the invalid argument is. In the following snippet I create the output codec and pass its context the information from the source (code further down below).


The check for the "outputCodec" works and does not throw an error. As far as I know an "AVDictionary"-argument is optional. So I guess the reason for the error is the context.


const AVCodec* outputCodec = avcodec_find_encoder_by_name(codecName.c_str());

 if (!outputCodec)
 {
 std::cout << "Zielformat-Codec nicht gefunden" << std::endl;
 return -1;
 }

 AVCodecContext* outputCodecContext = avcodec_alloc_context3(outputCodec);
 outputCodecContext->bit_rate = bitRate;
 outputCodecContext->width = inputCodecContext->width;
 outputCodecContext->height = inputCodecContext->height;
 outputCodecContext->pix_fmt = outputCodec->pix_fmts[0];
 outputCodecContext->time_base = inputCodecContext->time_base;

 **int errorCode = avcodec_open2(outputCodecContext, outputCodec, NULL); //THIS RETURNS -22**
 if (errorCode != 0)
 {
 std::cout << "Fehler beim Öffnen des Zielformat-Codecs" << std::endl;
 return -1;
 }



Here is the code for getting the input file & context :


std::string inputFilename = "input_video.mp4";
 std::string outputFilename = "output.avi";
 std::string codecName = "mpeg4";
 int bitRate = 400000;

 AVFormatContext* inputFormatContext = NULL;
 if (avformat_open_input(&inputFormatContext, inputFilename.c_str(), NULL, NULL) != 0)
 {
 std::cout << "Fehler beim Öffnen der Eingabedatei" << std::endl;
 return -1;
 }

 [Do Video Stream Search)

 AVCodecParameters* inputCodecParameters = inputFormatContext->streams[videoStreamIndex]->codecpar;
 const AVCodec* inputCodec = avcodec_find_decoder(inputCodecParameters->codec_id);
 AVCodecContext* inputCodecContext = avcodec_alloc_context3(inputCodec);
 if (avcodec_parameters_to_context(inputCodecContext, inputCodecParameters) != 0)
 {
 std::cout << "Fehler beim Setzen des Eingabecodecs" << std::endl;
 return -1;
 }
 if (avcodec_open2(inputCodecContext, inputCodec, NULL) != 0)
 {
 std::cout << "Fehler beim Öffnen des Eingabecodecs" << std::endl;
 return -1;
 }



The purpose was simply to get started with ffmpeg in an own C++ project.


If it is of any need, I downloaded the ffmpeg libs from here. I used the gpl shared ones. The architecture is win x64. I referenced them through the project properties (additional libraries and so on).


I tried to convert a .mp4 video to an .avi video with an "mpeg4" compression.
I also tried other compressions like "libx264" but none worked.


I searched for the problem on stackoverflow but could not find the exact same problem. While its purpose is different this post is about the same error code when calling avcodec_open2. But its solution is not working for me. I inspected the watch for the "outputContext" while running the code and the codec_id, codec_type and format is set. I use the time_base from the input file. According to my understanding, this should be equal to the source. So I can not find out what I am missing.


Thanks in advance and sorry for my english.


And for completion, here is the whole method :


int TestConvert()
{
 std::string inputFilename = "input_video.mp4";
 std::string outputFilename = "output.avi";
 std::string codecName = "mpeg4";
 int bitRate = 400000;

 AVFormatContext* inputFormatContext = NULL;
 if (avformat_open_input(&inputFormatContext, inputFilename.c_str(), NULL, NULL) != 0)
 {
 std::cout << "Fehler beim Öffnen der Eingabedatei" << std::endl;
 return -1;
 }

 int videoStreamIndex = -1;
 for (unsigned int i = 0; i < inputFormatContext->nb_streams; i++)
 {
 if (inputFormatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
 {
 videoStreamIndex = i;
 break;
 }
 }

 AVCodecParameters* inputCodecParameters = inputFormatContext->streams[videoStreamIndex]->codecpar;
 const AVCodec* inputCodec = avcodec_find_decoder(inputCodecParameters->codec_id);
 AVCodecContext* inputCodecContext = avcodec_alloc_context3(inputCodec);
 if (avcodec_parameters_to_context(inputCodecContext, inputCodecParameters) != 0)
 {
 std::cout << "Fehler beim Setzen des Eingabecodecs" << std::endl;
 return -1;
 }
 if (avcodec_open2(inputCodecContext, inputCodec, NULL) != 0)
 {
 std::cout << "Fehler beim Öffnen des Eingabecodecs" << std::endl;
 return -1;
 }

 const AVCodec* outputCodec = avcodec_find_encoder_by_name(codecName.c_str());

 if (!outputCodec)
 {
 std::cout << "Zielformat-Codec nicht gefunden" << std::endl;
 return -1;
 }

 AVCodecContext* outputCodecContext = avcodec_alloc_context3(outputCodec);
 outputCodecContext->bit_rate = bitRate;
 outputCodecContext->width = inputCodecContext->width;
 outputCodecContext->height = inputCodecContext->height;
 outputCodecContext->pix_fmt = outputCodec->pix_fmts[0];
 outputCodecContext->time_base = inputCodecContext->time_base;

 int errorCode = avcodec_open2(outputCodecContext, outputCodec, NULL);
 if (errorCode != 0)
 {
 std::cout << "Fehler beim Öffnen des Zielformat-Codecs" << std::endl;
 return -1;
 }

 AVFormatContext* outputFormatContext = NULL;
 if (avformat_alloc_output_context2(&outputFormatContext, NULL, NULL, outputFilename.c_str()) != 0)
 {
 std::cout << "Fehler beim Erstellen des Ausgabe-Formats" << std::endl;
 return -1;
 }

 AVStream* outputVideoStream = avformat_new_stream(outputFormatContext, outputCodec);
 if (outputVideoStream == NULL)
 {
 std::cout << "Fehler beim Hinzufügen des Video-Streams zum Ausgabe-Format" << std::endl;
 return -1;
 }
 outputVideoStream->id = outputFormatContext->nb_streams - 1;
 AVCodecParameters* outputCodecParameters = outputVideoStream->codecpar;
 if (avcodec_parameters_from_context(outputCodecParameters, outputCodecContext) != 0)
 {
 std::cout << "Fehler beim Setzen des Ausgabe-Codecs" << std::endl;
 return -1;
 }

 if (!(outputFormatContext->oformat->flags & AVFMT_NOFILE))
 {
 if (avio_open(&outputFormatContext->pb, outputFilename.c_str(), AVIO_FLAG_WRITE) != 0)
 {
 std::cout << "Fehler beim Öffnen der Ausgabedatei" << std::endl;
 return -1;
 }
 }

 if (avformat_write_header(outputFormatContext, NULL) != 0)
 {
 std::cout << "Fehler beim Schreiben des Ausgabe-Formats in die Ausgabedatei" << std::endl;
 return -1;
 }

 AVPacket packet;
 int response;
 AVFrame* frame = av_frame_alloc();
 AVFrame* outputFrame = av_frame_alloc();
 while (av_read_frame(inputFormatContext, &packet) == 0)
 {
 if (packet.stream_index == videoStreamIndex)
 {
 response = avcodec_send_packet(inputCodecContext, &packet);
 while (response >= 0)
 {
 response = avcodec_receive_frame(inputCodecContext, frame);
 if (response == AVERROR(EAGAIN) || response == AVERROR_EOF)
 {
 break;
 }
 else if (response < 0)
 {
 std::cout << "Fehler beim Dekodieren des Video-Pakets" << std::endl;
 return -1;
 }

 struct SwsContext* swsContext = sws_getContext(inputCodecContext->width, inputCodecContext->height, inputCodecContext->pix_fmt, outputCodecContext->width, outputCodecContext->height, outputCodecContext->pix_fmt, SWS_BILINEAR, NULL, NULL, NULL); if (!swsContext)
 {
 std::cout << "Fehler beim Erstellen des SwsContext" << std::endl;
 return -1;
 }
 sws_scale(swsContext, frame->data, frame->linesize, 0, inputCodecContext->height, outputFrame->data, outputFrame->linesize);
 sws_freeContext(swsContext);

 outputFrame->pts = frame->pts;
 outputFrame->pkt_dts = frame->pkt_dts;
 //outputFrame->pkt_duration = frame->pkt_duration;
 response = avcodec_send_frame(outputCodecContext, outputFrame);
 while (response >= 0)
 {
 response = avcodec_receive_packet(outputCodecContext, &packet);
 if (response == AVERROR(EAGAIN) || response == AVERROR_EOF)
 {
 break;
 }
 else if (response < 0)
 {
 std::cout << "Fehler beim Kodieren des Ausgabe-Frames" << std::endl;
 return -1;
 }

 packet.stream_index = outputVideoStream->id;
 av_packet_rescale_ts(&packet, outputCodecContext->time_base, outputVideoStream->time_base);
 if (av_interleaved_write_frame(outputFormatContext, &packet) != 0)
 {
 std::cout << "Fehler beim Schreiben des Ausgabe-Pakets" << std::endl;
 return -1;
 }
 av_packet_unref(&packet);
 }
 }
 }
 av_packet_unref(&packet);
 }

 av_write_trailer(outputFormatContext);
 avcodec_free_context(&inputCodecContext);
 avcodec_free_context(&outputCodecContext);
 avformat_close_input(&inputFormatContext);
 avformat_free_context(inputFormatContext);
 avformat_free_context(outputFormatContext);
 av_frame_free(&frame);
 av_frame_free(&outputFrame);

 return 0;

}