-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXDecode.cpp
More file actions
90 lines (76 loc) · 2.21 KB
/
Copy pathXDecode.cpp
File metadata and controls
90 lines (76 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include "XDecode.h"
#include "AVFrameRAII.h"
#include "AVPacketRAII.h"
#include<iostream>
extern "C" {
#include <libavcodec/avcodec.h>
}
using namespace std;
void XDecode::Close() {
std::lock_guard<std::mutex> lck(mux_);
if (codecContext) {
avcodec_close(codecContext);
avcodec_free_context(&codecContext);
}
pts = 0;
}
void XDecode::Clear() {
std::lock_guard<std::mutex> lck(mux_);
// 清理解码缓冲
if (codecContext) avcodec_flush_buffers(codecContext);
}
bool XDecode::Open(AVCodecParameters* para) {
if (!para) return false;
// 打开视频解码器
AVCodec* codec = avcodec_find_decoder(para->codec_id);
if (!codec) {
avcodec_parameters_free(¶);
std::cout << "can't find the codec id " << para->codec_id << std::endl;
return false;
}
std::cout << "codec found! " << para->codec_id << std::endl;
// 加锁,保证codecContext访问互斥
std::unique_lock<std::mutex> lck(mux_, std::try_to_lock);
if (!lck.owns_lock()) return false;
// 构建解码器上下文
codecContext = avcodec_alloc_context3(codec);
// 配置解码器上下文参数
avcodec_parameters_to_context(codecContext, para);
codecContext->thread_count = 8;
int ret = avcodec_open2(codecContext, nullptr, nullptr);
if (ret != 0) {
avcodec_free_context(&codecContext);
lck.unlock();
char buf[1024] = { 0 };
av_strerror(ret, buf, sizeof(buf) - 1);
std::cout << "avcodec_open2 failed! :" << buf << std::endl;
return false;
}
avcodec_parameters_free(¶);
return true;
}
bool XDecode::Send(shared_ptr<AVPacketRAII> pkt) {
if (!pkt || pkt->get_avpacket()->size <= 0 || !pkt->get_avpacket()->data) return false;
{
std::lock_guard<std::mutex> lck(mux_);
if (!codecContext) return false;
int ret = avcodec_send_packet(codecContext, pkt->get_avpacket());
// 释放空间
if (ret != 0)return false;
}
return true;
}
shared_ptr<AVFrameRAII> XDecode::Recv() {
std::lock_guard<std::mutex> lck(mux_);
if (!codecContext) return nullptr;
shared_ptr<AVFrameRAII> frame = make_shared<AVFrameRAII>();
int re = avcodec_receive_frame(codecContext, frame->get_frame());
if (re != 0) {
return nullptr;
}
// std::cout << "[" << frame->linesize[0] << "] " << std::flush;
pts = frame->get_frame()->pts;
return frame;
}
XDecode::XDecode() {};
XDecode::~XDecode() {};