-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXDecode.cpp
More file actions
141 lines (116 loc) · 2.69 KB
/
XDecode.cpp
File metadata and controls
141 lines (116 loc) · 2.69 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#include "XDecode.h"
#include <iostream>
using namespace std;
extern "C" {
#include <libavcodec/avcodec.h>
}
void XFreePacket(AVPacket **pkt)
{
if(!pkt || !(*pkt))
return;
av_packet_free(pkt);
}
void XFreeFrame(AVFrame **frame)
{
if(!frame || !(*frame))
return;
av_frame_free(frame);
}
XDecode::XDecode()
{
}
bool XDecode::Open(AVCodecParameters *para)
{
if(!para)
return false;
Close();
int ret = -1;
///////////////////////////////////////////////////////////////////
/// 寻找解码器
AVCodec const *vcodec = avcodec_find_decoder(para->codec_id);
if(!vcodec) {
avcodec_parameters_free(¶);
cout << "can't find codec id" << endl;
return false;
}
cout << "Find codec id = " << para->codec_id << endl;
//创建解码器上下文
mux.lock();
codec = avcodec_alloc_context3(vcodec);
// 配置解码器上下文参数
avcodec_parameters_to_context(codec, para);
avcodec_parameters_free(¶);
// 设置解码线程数
codec->thread_count = 8;
// 打开解码器上下文
ret = avcodec_open2(codec, 0, 0);
if(ret != 0) {
avcodec_free_context(&codec);
mux.unlock();
char buf[1024] = {0};
av_strerror(ret, buf, sizeof(buf) - 1);
cout << "avcodec_open2 failed : " << buf << endl;
return false;
}
cout << "video avcodec_open2 success" << endl;
avcodec_parameters_free(¶);
mux.unlock();
return true;
}
bool XDecode::Send(AVPacket *pkt)
{
// 容错处理
if(!pkt || pkt->size <= 0 || !pkt->data)
return false;
mux.lock();
if(!codec)
{
mux.unlock();
return false;
}
int ret = avcodec_send_packet(codec, pkt);
mux.unlock();
av_packet_free(&pkt);
if(ret != 0)
return false;
return true;
}
AVFrame *XDecode::Recv()
{
mux.lock();
if(!codec)
{
mux.unlock();
return nullptr;
}
AVFrame *frame = av_frame_alloc();
int ret = avcodec_receive_frame(codec, frame);
mux.unlock();
if(ret != 0)
{
av_frame_free(&frame);
return nullptr;
}
// cout << "[" << frame->linesize[0] << "]" << endl;
// 记录取到的pts
pts = frame->pts;
return frame;
}
void XDecode::Close()
{
mux.lock();
if(codec)
{
avcodec_close(codec);
avcodec_free_context(&codec);
}
pts = 0;
mux.unlock();
}
void XDecode::Clear()
{
mux.lock();
if(codec)
avcodec_flush_buffers(codec);
mux.unlock();
}