Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > C/C++ программирование > Общие вопросы C/C++
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 22.03.2023, 23:59   #1
p985850@ya.ru
Новичок
Джуниор
 
Регистрация: 22.03.2023
Сообщений: 1
Вопрос Захват видео с IP камеры С++ FFMPEG

Нужна помощь спецов, получаю изображение кривое но не могу записать в файл h.264 желательно.
Но судя по тому что почти некто не знает по этому вопросу, а задаю его уже 3 месяца - ответа еще нет.

#include <Windows.h>

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <cstring>
#include <math.h>
#include <string.h>

extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libavformat/avio.h>

#include "libavutil/imgutils.h"
#include "libavutil/opt.h"

#include <libavutil/imgutils.h>
#include <libavutil/samplefmt.h>
#include <libavutil/timestamp.h>
#include <libavformat/avformat.h>
#include <libswresample/swresample.h>

//============================

#include "libavcodec/avcodec.h"
#include "libavcodec/avfft.h"

#include "libavdevice/avdevice.h"

#include "libavfilter/avfilter.h"
//#include "libavfilter/avfiltergraph.h"
#include "libavfilter/buffersink.h"
#include "libavfilter/buffersrc.h"

#include "libavformat/avformat.h"
#include "libavformat/avio.h"

//libav resample

#include "libavutil/opt.h"
#include "libavutil/common.h"
#include "libavutil/channel_layout.h"
#include "libavutil/imgutils.h"
#include "libavutil/mathematics.h"
#include "libavutil/samplefmt.h"
#include "libavutil/time.h"
#include "libavutil/opt.h"
#include "libavutil/pixdesc.h"
#include "libavutil/file.h"

//lib swresample

#include "libswscale/swscale.h"

#include <libavutil/imgutils.h>
#include <libavutil/samplefmt.h>
#include <libavutil/timestamp.h>
#include <libavformat/avformat.h>

}
#define INBUF_SIZE 4096


static void save_gray_frame (unsigned char * buf, int wrap, int xsize, int ysize, char * filename)
{
FILE * f = NULL;
int i;
f = fopen (filename, "w");
if (f == NULL) {
fprintf (stderr, "ffmpeg: It was not succeeded to create the new file \n");
}
//writing the minimal required header for a pgm file format
//portable graymap format-> https://en.wikipedia.org/wiki/Netpbm_format#PGM_example
fprintf (f, "P5\n%d %d\n%d\n", xsize, ysize, 255);

//writing line by line
for (i = 0; i <ysize; i ++)
fwrite (buf + i * wrap, 1, xsize, f);
fclose(f);
}



int main (int argc, char * argv [])
{
setlocale (LC_ALL, "Rus");

const char * filename, * outfilename;
const AVCodec * codec = NULL;
AVCodecParserContext * parser;

//contains data on a configuration of media content, such as bitrate,
//frame rate, sampling frequency, channels, height and many other things.
AVCodecContext * AVCodecContext_ = NULL;
AVCodecParameters * AVCodecParametr_ = NULL;
FILE * f;
//This structure describes decoded (raw) audio- or video this.
AVFrame * frame;
uint8_t inbuf [INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
uint8_t * data;
size_t data_size;
int ret;
int eof;
AVFormatContext * AVfc = NULL;
int ERRORS;
//AVCodec * codec;
char buf [1024];
const char * FileName;

//https://habr.com/ru/post/137793/
//Stores the compressed one shot.
AVPacket * pkt;

//*********************************** ***********************************
//Beginning of reading video from the camera.
//*********************************** ***********************************

avdevice_register_all ();

filename = "rtsp://admin: 754HG@192.168.1.75:554/11";
//filename = "c:\\1.avi";
outfilename = "C:\\2.MP4";

//We open a flow of video (it is the file or the camera).
ERRORS = avformat_open_input (& AVfc, filename, NULL, NULL);
if (ERRORS <0) {
fprintf (stderr, "ffmpeg: could not open file \n");
return-1;
}

//After opening, we can print out information on the video file (iformat = the name of a format;
//duration = duration). But as I connected the camera to me wrote: Duration: N/A,
//start: 0.000000, bitrate: N/A
printf ("Format %s, duration %lld us", AVfc-> iformat-> long_name, AVfc-> duration);


ERRORS = avformat_find_stream_info (AVfc, NULL);
if (ERRORS <0) {
fprintf (stderr, "ffmpeg: Unable to find stream info\n");
return-1;
}


int CountStream;

//We learn quantity of streams.
CountStream = AVfc-> nb_streams;

//Let's look for the codec.
int video_stream;
for (video_stream = 0; video_stream <AVfc-> nb_streams; ++ video_stream) {
if (AVfc-> streams[video_stream]-> codecpar-> codec_type == AVMEDIA_TYPE_VIDEO) {
break;
}

}

if (video_stream == AVfc-> nb_streams) {
fprintf (stderr, "ffmpeg: Unable to find video stream\n");
return-1;
}

//Here we define a type of the codec, for my camera it is equal as AV_CODEC_ID_HEVC (This that in what is broadcast by my camera)
codec = avcodec_find_decoder(AVfc-> streams [video_stream]-> codecpar-> codec_id);
//--------------------------------------------------------------------------------------

//Functions for inquiry of opportunities of libavcodec,
AVCodecContext_ = avcodec_alloc_context3(codec);
if (! AVCodecContext _) {
fprintf (stderr, "Was not succeeded to allocate a video codec context, since it not poddrerzhivayetsya\n");
exit(1);
}

//This function is used for initialization
//AVCodecContext of video and audio of the codec. The announcement of avcodec_open2 () is in libavcodecavcodec.h
//We open the codec.

ERRORS = avcodec_open2 (AVCodecContext _, codec, NULL);
if (ERRORS <0) {
fprintf (stderr, "ffmpeg: It is not possible to open codec \n");
return-1;
}

//It for processing of a sound - a reserve.
//swr_alloc_set_opts ()
//swr_init ();

//To output all information on the video file.
av_dump_format (AVfc, 0, argv[1], 0);

//=================================== =================================== ===================
//Further, we receive frames. before we only received all infomration about the entering video.
//=================================== =================================== ===================

//Now we are going to read packages from a stream and to decode them in shots, but at first
//we need to mark out memory for both components (AVPacket and AVFrame).
frame = av_frame_alloc ();

if (! frame) {
fprintf (stderr, "Is not possible to mark out memory for video footage \n");
exit(1);
}
//We mark out memory for a package
pkt = av_packet_alloc ();
//We define a file name for saving the picture.
const char * FileName1 = "C:\\Users\\Павел\\Desktop\\NyFile. PGM";
//Data reading if they is.
while (av_read_frame (AVfc, pkt)> = 0) {
//It is a package from a video stream? Because there is still a soundtrack.
if (pkt-> stream_index == video_stream) {
int ret;

//Transfer of the raw package data as input data in the decoder
ret = avcodec_send_packet (AVCodecContext _, pkt);
if (ret <0 | | ret == AVERROR(EAGAIN) | | ret == AVERROR_EOF) {
std:: cout <<"avcodec_send_packet:" <<ret <<std:: endl;
break;
}

while (ret> = 0) {

//Returns the decoded output data from the decoder or the encoder
ret = avcodec_receive_frame (AVCodecContext _, frame);
if (ret == AVERROR(EAGAIN) | | ret == AVERROR_EOF) {
//std:: cout <<"avcodec_receive_frame:" <<ret <<std:: endl;
break;
}
std:: cout <<"frame:" <<AVCodecContext_-> of frame_number <<std:: endl;

//=================================== =================================== ======================

//Experimentally - we will keep a shot in the picture.

save_gray_frame(frame-> data [0], frame-> linesize [0], frame-> width, frame-> height, (char *) FileName1);
}





}

}


//av_parser_close(parser);
avcodec_free_context (& AVCodecContext _);
av_frame_free (& frame);
av_packet_free (& pkt);

return 0;
}
p985850@ya.ru вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Захват изображений с веб-камеры brutalis Qt и кроссплатформенное программирование С/С++ 12 04.03.2013 20:46
Пример захват видео с веб-камеры Ёжик в тумане Win Api 9 02.10.2012 19:46
Захват видео с веб камеры maks5 Общие вопросы Delphi 0 08.10.2011 15:22
Захват видео с веб-камеры alexprey Мультимедиа в Delphi 8 09.07.2010 15:28
C#/C++ Захват видео с камеры через WiFi или Bluetooth yurban Общие вопросы C/C++ 2 02.10.2008 09:22