forked from Bouix86/decoder_wasm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode_video.c
More file actions
502 lines (432 loc) · 12 KB
/
decode_video.c
File metadata and controls
502 lines (432 loc) · 12 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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
/**
* @file
* video decoding with libavcodec API example
*
* decode_video.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef void(*VideoCallback)(unsigned char* data_y, unsigned char* data_u, unsigned char* data_v, int line1, int line2, int line3, int width, int height, long pts, int qp_cur, int size_pkt);
#include <libavcodec/h264dec.h>
#include <libavcodec/hevcdec.h>
#include <libavutil/imgutils.h>
#include <libavcodec/avcodec.h>
#define INBUF_SIZE 4096
typedef enum ErrorCode {
kErrorCode_Success = 0,
kErrorCode_Invalid_Param,
kErrorCode_Invalid_State,
kErrorCode_Invalid_Data,
kErrorCode_Invalid_Format,
kErrorCode_NULL_Pointer,
kErrorCode_Open_File_Error,
kErrorCode_Eof,
kErrorCode_FFmpeg_Error
}ErrorCode;
typedef enum LogLevel {
kLogLevel_None, //Not logging.
kLogLevel_Core, //Only logging core module(without ffmpeg).
kLogLevel_All //Logging all, with ffmpeg.
}LogLevel;
typedef enum DecoderType {
kDecoderType_H264,
kDecoderType_H265
}DecoderType;
// 定义节点结构体
struct Node {
int data;
struct Node* next;
};
// 定义队列结构体
struct Queue {
struct Node* front; // 队头指针
struct Node* rear; // 队尾指针
};
LogLevel logLevel = kLogLevel_None;
DecoderType decoderType = kDecoderType_H265;
struct Node* createNode(int data);
struct Queue* createQueue(void);
void enqueue(struct Queue* queue, int data);
int dequeue(struct Queue* queue);
int isEmpty(struct Queue* queue);
int frame_count = 0;
struct Queue *qp_queue = NULL, *size_queue = NULL;
// 创建一个新节点
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 创建空队列
struct Queue* createQueue(void) {
struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->front = queue->rear = NULL;
return queue;
}
// 入队操作
void enqueue(struct Queue* queue, int data) {
struct Node* newNode = createNode(data);
if (queue->rear == NULL) {
// 如果队列为空,新节点作为队头和队尾
queue->front = queue->rear = newNode;
return;
}
// 将新节点添加到队尾,并更新队尾指针
queue->rear->next = newNode;
queue->rear = newNode;
}
// 出队操作
int dequeue(struct Queue* queue) {
int data = 0;
struct Node* temp = NULL;
if (queue->front == NULL) {
printf("Queue is empty!\n");
return -1; // 返回 -1 表示队列为空
}
// 获取队头节点的数据
data = queue->front->data;
temp = queue->front;
queue->front = queue->front->next;
// 如果队头变为空,更新队尾指针
if (queue->front == NULL) {
queue->rear = NULL;
}
free(temp); // 释放出队的节点
return data;
}
// 检查队列是否为空
int isEmpty(struct Queue* queue) {
return queue->front == NULL;
}
void simpleLog(const char* format, ...) {
if (logLevel == kLogLevel_None) {
return;
}
char szBuffer[1024] = { 0 };
char szTime[32] = { 0 };
char* p = NULL;
int prefixLength = 0;
const char* tag = "Core";
// 获取当前时间并格式化
time_t now = time(NULL);
struct tm* local = localtime(&now);
strftime(szTime, sizeof(szTime), "%Y-%m-%d %H:%M:%S", local); // 格式化时间
prefixLength = sprintf(szBuffer, "[%s][%s][DT] ", szTime, tag);
p = szBuffer + prefixLength;
if (1) {
va_list ap;
va_start(ap, format);
vsnprintf(p, 1024 - prefixLength, format, ap);
va_end(ap);
}
printf("%s\n", szBuffer);
}
void ffmpegLogCallback(void* ptr, int level, const char* fmt, va_list vl) {
static int printPrefix = 1;
static int count = 0;
static char prev[1024] = { 0 };
char line[1024] = { 0 };
static int is_atty;
AVClass* avc = ptr ? *(AVClass**)ptr : NULL;
if (level > AV_LOG_DEBUG) {
return;
}
line[0] = 0;
if (printPrefix && avc) {
if (avc->parent_log_context_offset) {
AVClass** parent = *(AVClass***)(((uint8_t*)ptr) + avc->parent_log_context_offset);
if (parent && *parent) {
snprintf(line, sizeof(line), "[%s @ %p] ", (*parent)->item_name(parent), parent);
}
}
snprintf(line + strlen(line), sizeof(line) - strlen(line), "[%s @ %p] ", avc->item_name(ptr), ptr);
}
vsnprintf(line + strlen(line), sizeof(line) - strlen(line), fmt, vl);
line[strlen(line) + 1] = 0;
simpleLog("%s", line);
}
VideoCallback videoCallback = NULL;
ErrorCode copyFrameData(AVFrame* src, AVFrame* dst, long ptslist[]) {
ErrorCode ret = kErrorCode_Success;
memcpy(dst->data, src->data, sizeof(src->data));
dst->linesize[0] = src->linesize[0];
dst->linesize[1] = src->linesize[1];
dst->linesize[2] = src->linesize[2];
dst->width = src->width;
dst->height = src->height;
long pts = LONG_MAX;
int index = -1;
for (int i = 0; i < 10; i++) {
if (ptslist[i] < pts) {
pts = ptslist[i];
index = i;
}
}
if (index > -1) {
ptslist[index] = LONG_MAX;
}
dst->pts = pts;
return ret;
}
unsigned char* yuvBuffer;
int videoSize = 0;
int initBuffer(int width, int height) {
videoSize = av_image_get_buffer_size(AV_PIX_FMT_YUV420P, width, height, 1);
int bufferSize = 3 * videoSize;
yuvBuffer = (unsigned char*)av_mallocz(bufferSize);
return bufferSize;
}
static ErrorCode decode(AVCodecContext* dec_ctx, AVFrame* frame, AVPacket* pkt, AVFrame* outFrame, long ptslist[])
{
ErrorCode res = kErrorCode_Success;
char buf[1024];
int ret;
ret = avcodec_send_packet(dec_ctx, pkt);
if (ret < 0) {
simpleLog("Error sending a packet for decoding\n");
res = kErrorCode_FFmpeg_Error;
}
else {
if (dec_ctx->codec_id == AV_CODEC_ID_H264) {
H264Context *h = dec_ctx->priv_data;
H264SliceContext *sl = h->slice_ctx + h->nb_slice_ctx_queued;
enqueue(qp_queue, sl->qp_trans);
// printf("QP read: H264 QP: addr %p, value %d\n", &sl->qp_trans, sl->qp_trans);
} else if (dec_ctx->codec_id == AV_CODEC_ID_HEVC) {
HEVCContext *s = dec_ctx->priv_data;
SliceHeader *sh = &s->sh;
enqueue(qp_queue, sh->slice_qp);
// printf("QP read: HEVC QP: addr %p, value %d\n", &sh->slice_qp, sh->slice_qp);
} else {
fprintf(stderr, "Unsupported codec\n");
exit(1);
}
while (ret >= 0) {
ret = avcodec_receive_frame(dec_ctx, frame);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
break;
}
else if (ret < 0) {
simpleLog("Error during decoding\n");
res = kErrorCode_FFmpeg_Error;
break;
}
// printf("============================ current frame qp %d, size %d\n", dequeue(qp_queue), dequeue(size_queue));
res = copyFrameData(frame, outFrame, ptslist);
if (res != kErrorCode_Success) {
break;
}
int qp = dequeue(qp_queue),
size = dequeue(size_queue);
// simpleLog("qp %d, size %d\n", qp, size);
videoCallback(outFrame->data[0], outFrame->data[1], outFrame->data[2], outFrame->linesize[0], outFrame->linesize[1], outFrame->linesize[2], outFrame->width, outFrame->height, outFrame->pts, qp, size);
}
}
return res;
}
int isInit = 0;
const AVCodec* codec;
AVCodecParserContext* parser;
AVCodecContext* c = NULL;
AVPacket* pkt;
AVFrame* frame;
AVFrame* outFrame;
long ptslist[10];
ErrorCode openDecoder(int codecType, long callback, int logLv) {
ErrorCode ret = kErrorCode_Success;
do {
simpleLog("Initialize decoder.");
if (isInit != 0) {
break;
}
qp_queue = createQueue();
size_queue = createQueue();
decoderType = codecType;
logLevel = logLv;
if (logLevel == kLogLevel_All) {
av_log_set_callback(ffmpegLogCallback);
}
/* find the video decoder */
if (decoderType == kDecoderType_H264) {
codec = avcodec_find_decoder(AV_CODEC_ID_H264);
} else {
codec = avcodec_find_decoder(AV_CODEC_ID_H265);
}
if (!codec) {
simpleLog("Codec not found\n");
ret = kErrorCode_FFmpeg_Error;
break;
}
parser = av_parser_init(codec->id);
if (!parser) {
simpleLog("parser not found\n");
ret = kErrorCode_FFmpeg_Error;
break;
}
c = avcodec_alloc_context3(codec);
if (!c) {
simpleLog("Could not allocate video codec context\n");
ret = kErrorCode_FFmpeg_Error;
break;
}
if (avcodec_open2(c, codec, NULL) < 0) {
simpleLog("Could not open codec\n");
ret = kErrorCode_FFmpeg_Error;
break;
}
frame = av_frame_alloc();
if (!frame) {
simpleLog("Could not allocate video frame\n");
ret = kErrorCode_FFmpeg_Error;
break;
}
outFrame = av_frame_alloc();
if (!outFrame) {
simpleLog("Could not allocate video frame\n");
ret = kErrorCode_FFmpeg_Error;
break;
}
pkt = av_packet_alloc();
if (!pkt) {
simpleLog("Could not allocate video packet\n");
ret = kErrorCode_FFmpeg_Error;
break;
}
for (int i = 0; i < 10; i++) {
ptslist[i] = LONG_MAX;
}
videoCallback = (VideoCallback)callback;
} while (0);
simpleLog("Decoder initialized %s.", ret == 0 ? "success":"failed");
return ret;
}
ErrorCode decodeData(unsigned char* data, size_t data_size, long pts) {
ErrorCode ret = kErrorCode_Success;
for (int i = 0; i < 10; i++) {
if (ptslist[i] == LONG_MAX) {
ptslist[i] = pts;
break;
}
}
while (data_size > 0) {
int size = av_parser_parse2(parser, c, &pkt->data, &pkt->size,
data, data_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);
if (size < 0) {
simpleLog("Error while parsing\n");
ret = kErrorCode_FFmpeg_Error;
break;
}
data += size;
data_size -= size;
if (pkt->size) {
// printf("decoded frame num %d, size=%d\n", c->frame_number, pkt->size);
enqueue(size_queue, pkt->size);
ret = decode(c, frame, pkt, outFrame, ptslist);
if (ret != kErrorCode_Success) {
break;
}
}
}
return ret;
}
ErrorCode flushDecoder() {
/* flush the decoder */
return decode(c, frame, NULL, outFrame, ptslist);
}
ErrorCode closeDecoder() {
ErrorCode ret = kErrorCode_Success;
do {
if (parser != NULL) {
av_parser_close(parser);
simpleLog("Video codec context closed.");
}
if (c != NULL) {
avcodec_free_context(&c);
simpleLog("Video codec context closed.");
}
if (frame != NULL) {
av_frame_free(&frame);
}
if (pkt != NULL) {
av_packet_free(&pkt);
}
if (yuvBuffer != NULL) {
av_freep(&yuvBuffer);
}
if (outFrame != NULL) {
av_frame_free(&outFrame);
}
simpleLog("All buffer released.");
} while (0);
return ret;
}
int callbackIndex = 0;
void vcb_frame(unsigned char* data_y, unsigned char* data_u, unsigned char* data_v, int line1, int line2, int line3, int width, int height, long pts) {
simpleLog("[%d]In video call back, size = %d * %d, pts = %ld\n", ++callbackIndex, width, height, pts);
int i = 0;
unsigned char* src = NULL;
FILE* dst = fopen("vcb.yuv", "a");
for (i = 0; i < height; i++) {
src = data_y + i * line1;
fwrite(src, width, 1, dst);
}
for (i = 0; i < height / 2; i++) {
src = data_u + i * line2;
fwrite(src, width/2, 1, dst);
}
for (i = 0; i < height / 2; i++) {
src = data_v + i * line3;
fwrite(src, width/2, 1, dst);
}
fclose(dst);
}
int main(int argc, char** argv)
{
// openDecoder(1, vcb_frame, kLogLevel_Core);
//
// //const char* filename = "Forrest_Gump_IMAX.h264";
// const char* filename = "FourPeople_1280x720_60_1M.265";
//
// FILE* f;
//
// // uint8_t *data;
// size_t data_size;
//
// //uint8_t inbuf[INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
// ///* set end of buffer to 0 (this ensures that no overreading happens for damaged MPEG streams) */
// //memset(inbuf + INBUF_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
//
// char* buffer;
// buffer = (char*)malloc(sizeof(char) * (INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE));
// if (buffer == NULL) {
// simpleLog("Memory error");
// exit(2);
// }
//
// f = fopen(filename, "rb");
// if (!f) {
// simpleLog("Could not open %s\n", filename);
// exit(1);
// }
//
// while (!feof(f)) {
// /* read raw data from the input file */
// //data_size = fread(inbuf, 1, INBUF_SIZE, f);
// data_size = fread(buffer, 1, INBUF_SIZE, f);
//
// if (!data_size)
// break;
//
// /* use the parser to split the data into frames */
// //data = inbuf;
// decodeData(buffer, data_size, 0);
// }
// fclose(f);
// free(buffer);
//
// flushDecoder();
// closeDecoder();
return 0;
}