123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477 |
- #include "NetworkVideoDecode.h"
- #include "videodecode.h"
- #include <QDebug>
- #include <QDir>
- #include <QImage>
- #include <QMutex>
- #include <qdatetime.h>
- extern "C" {
- #include "libavcodec/avcodec.h"
- #include "libavformat/avformat.h"
- #include "libavutil/avutil.h"
- #include "libswscale/swscale.h"
- #include "libavutil/imgutils.h"
- }
- #define ERROR_LEN 1024
- #define PRINT_LOG 1
- VideoDecode::VideoDecode()
- {
- m_error = new char[ERROR_LEN];
- }
- VideoDecode::~VideoDecode()
- {
- close();
- }
- void VideoDecode::initFFmpeg()
- {
- static bool isFirst = true;
- static QMutex mutex;
- QMutexLocker locker(&mutex);
- if(isFirst)
- {
-
-
- avformat_network_init();
- isFirst = false;
- }
- }
- bool VideoDecode::open(const QString &url)
- {
- if(url.isNull()) return false;
- AVDictionary* dict = nullptr;
- av_dict_set(&dict, "rtsp_transport", "tcp", 0);
-
- int ret = avformat_open_input(&m_formatContext,
- url.toStdString().data(),
- nullptr,
- &dict);
-
- if(dict)
- {
- av_dict_free(&dict);
- }
-
- if(ret < 0)
- {
- showError(ret);
- free();
- return false;
- }
-
- ret = avformat_find_stream_info(m_formatContext, nullptr);
- if(ret < 0)
- {
- showError(ret);
- free();
- return false;
- }
- m_totalTime = m_formatContext->duration / (AV_TIME_BASE / 1000);
- #if PRINT_LOG
- qDebug() << QString("视频总时长:%1 ms,[%2]").arg(m_totalTime).arg(QTime::fromMSecsSinceStartOfDay(int(m_totalTime)).toString("HH:mm:ss zzz"));
- #endif
-
- m_videoIndex = av_find_best_stream(m_formatContext, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
- if(m_videoIndex < 0)
- {
- showError(m_videoIndex);
- free();
- return false;
- }
- AVStream* videoStream = m_formatContext->streams[m_videoIndex];
-
- m_size.setWidth(videoStream->codecpar->width);
- m_size.setHeight(videoStream->codecpar->height);
- m_frameRate = rationalToDouble(&videoStream->avg_frame_rate);
-
- const AVCodec* codec = avcodec_find_decoder(videoStream->codecpar->codec_id);
- m_totalFrames = videoStream->nb_frames;
- m_strCodecName = codec->name;
- #if PRINT_LOG
- qDebug() << QString("分辨率:[w:%1,h:%2] 帧率:%3 总帧数:%4 解码器:%5")
- .arg(m_size.width()).arg(m_size.height()).arg(m_frameRate).arg(m_totalFrames).arg(codec->name);
- #endif
-
- m_codecContext = avcodec_alloc_context3(codec);
- if(!m_codecContext)
- {
- #if PRINT_LOG
- qWarning() << "创建视频解码器上下文失败!";
- #endif
- free();
- return false;
- }
-
- ret = avcodec_parameters_to_context(m_codecContext, videoStream->codecpar);
- if(ret < 0)
- {
- showError(ret);
- free();
- return false;
- }
- m_codecContext->flags2 |= AV_CODEC_FLAG2_FAST;
- m_codecContext->thread_count = 8;
-
- ret = avcodec_open2(m_codecContext, nullptr, nullptr);
- if(ret < 0)
- {
- showError(ret);
- free();
- return false;
- }
-
- m_packet = av_packet_alloc();
- if(!m_packet)
- {
- #if PRINT_LOG
- qWarning() << "av_packet_alloc() Error!";
- #endif
- free();
- return false;
- }
-
- m_frame = av_frame_alloc();
- if(!m_frame)
- {
- #if PRINT_LOG
- qWarning() << "av_frame_alloc() Error!";
- #endif
- free();
- return false;
- }
-
- int size = av_image_get_buffer_size(AV_PIX_FMT_RGBA, m_size.width(), m_size.height(), 4);
-
- m_buffer = new uchar[size + 1000];
- m_end = false;
- return openSave();
- }
- QImage VideoDecode::read()
- {
-
- if(!m_formatContext)
- {
- return QImage();
- }
-
- int readRet = av_read_frame(m_formatContext, m_packet);
- if(readRet < 0)
- {
- avcodec_send_packet(m_codecContext, m_packet);
- }
- else
- {
- if(m_packet->stream_index == m_videoIndex)
- {
- if(m_formatContextSave)
- {
-
-
- m_packet->stream_index = 0;
- av_write_frame(m_formatContextSave, m_packet);
- }
-
- #if 1
- m_packet->pts = qRound64(m_packet->pts * (1000 * rationalToDouble(&m_formatContext->streams[m_videoIndex]->time_base)));
- m_packet->dts = qRound64(m_packet->dts * (1000 * rationalToDouble(&m_formatContext->streams[m_videoIndex]->time_base)));
- #else
- m_obtainFrames++;
- m_packet->pts = qRound64(m_obtainFrames * (qreal(m_totalTime) / m_totalFrames));
- #endif
-
- int ret = avcodec_send_packet(m_codecContext, m_packet);
- if(ret < 0)
- {
- showError(ret);
- }
- }
- }
- av_packet_unref(m_packet);
- int ret = avcodec_receive_frame(m_codecContext, m_frame);
- if(ret < 0)
- {
- av_frame_unref(m_frame);
- if(readRet < 0)
- {
- m_end = true;
- }
- return QImage();
- }
- m_pts = m_frame->pts;
-
- if(!m_swsContext)
- {
-
- m_swsContext = sws_getCachedContext(m_swsContext,
- m_frame->width,
- m_frame->height,
- (AVPixelFormat)m_frame->format,
- m_size.width(),
- m_size.height(),
- AV_PIX_FMT_RGBA,
- SWS_BILINEAR,
- nullptr,
- nullptr,
- nullptr);
- if(!m_swsContext)
- {
- #if PRINT_LOG
- qWarning() << "sws_getCachedContext() Error!";
- #endif
- free();
- return QImage();
- }
- }
-
- uchar* data[] = {m_buffer};
- int lines[4];
- av_image_fill_linesizes(lines, AV_PIX_FMT_RGBA, m_frame->width);
- ret = sws_scale(m_swsContext,
- m_frame->data,
- m_frame->linesize,
- 0,
- m_frame->height,
- data,
- lines);
- QImage image(m_buffer, m_frame->width, m_frame->height, QImage::Format_RGBA8888);
- av_frame_unref(m_frame);
- return image;
- }
- void VideoDecode::close()
- {
- clear();
- free();
- m_totalTime = 0;
- m_videoIndex = 0;
- m_totalFrames = 0;
- m_obtainFrames = 0;
- m_pts = 0;
- m_frameRate = 0;
- m_size = QSize(0, 0);
- }
- bool VideoDecode::isEnd()
- {
- return m_end;
- }
- const qint64 &VideoDecode::pts()
- {
- return m_pts;
- }
- void VideoDecode::showError(int err)
- {
- #if PRINT_LOG
- memset(m_error, 0, ERROR_LEN);
- av_strerror(err, m_error, ERROR_LEN);
- qWarning() << "DecodeVideo Error:" << m_error;
- #else
- Q_UNUSED(err)
- #endif
- }
- qreal VideoDecode::rationalToDouble(AVRational* rational)
- {
- qreal frameRate = (rational->den == 0) ? 0 : (qreal(rational->num) / rational->den);
- return frameRate;
- }
- void VideoDecode::clear()
- {
- if(m_formatContextSave && m_writeHeader)
- {
- av_write_trailer(m_formatContextSave);
- m_writeHeader = false;
- avformat_free_context(m_formatContextSave);
- m_formatContext = nullptr;
- m_videoStream = nullptr;
- }
-
- if(m_formatContext && m_formatContext->pb)
- {
- avio_flush(m_formatContext->pb);
- }
- if(m_formatContext)
- {
- avformat_flush(m_formatContext);
- }
- }
- void VideoDecode::free()
- {
-
- if(m_swsContext)
- {
- sws_freeContext(m_swsContext);
- m_swsContext = nullptr;
- }
-
- if(m_codecContext)
- {
- avcodec_free_context(&m_codecContext);
- }
-
- if(m_formatContext)
- {
- avformat_close_input(&m_formatContext);
- }
- if(m_packet)
- {
- av_packet_free(&m_packet);
- }
- if(m_frame)
- {
- av_frame_free(&m_frame);
- }
- if(m_buffer)
- {
- delete [] m_buffer;
- m_buffer = nullptr;
- }
- }
- bool VideoDecode::openSave()
- {
- QDir dir;
- if(!dir.exists("./Videos"))
- {
- dir.mkdir("./Videos");
- }
- QString strName = QString("./Videos/%1.h264").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH-mm-ss"));
- int ret = avformat_alloc_output_context2(&m_formatContextSave, nullptr, m_strCodecName.toStdString().data(), strName.toStdString().data());
- if(ret < 0)
- {
- free();
- showError(ret);
- return false;
- }
-
- ret = avio_open(&m_formatContextSave->pb, strName.toStdString().data(), AVIO_FLAG_WRITE);
- if(ret < 0)
- {
- free();
- showError(ret);
- return false;
- }
-
- m_videoStream = avformat_new_stream(m_formatContextSave, nullptr);
- if(!m_videoStream)
- {
- free();
- showError(AVERROR(ENOMEM));
- return false;
- }
-
- ret = avcodec_parameters_from_context(m_videoStream->codecpar, m_codecContext);
- if(ret < 0)
- {
- free();
- showError(ret);
- return false;
- }
-
- ret = avformat_write_header(m_formatContextSave, nullptr);
- if(ret < 0)
- {
- free();
- showError(ret);
- return false;
- }
- m_writeHeader = true;
- qDebug() << "开始录制视频!";
- return true;
- }
|