FFmpeg中从packet解析出h264的NAL,得到nal长度等信息代码。注意不要使用av_parser_parse2
时间: 2024-05-15 15:14:18 浏览: 19
可以使用以下代码从 `AVPacket` 解析出 H.264 NAL 单元:
```c
#include <stdint.h>
typedef struct {
uint8_t *data;
int size;
} NALUnit;
int findStartCode(uint8_t *buf, int size) {
int i;
for (i = 0; i < size - 3; i++) {
if (buf[i] == 0x00 && buf[i + 1] == 0x00 && buf[i + 2] == 0x01) {
return i;
}
}
return -1;
}
NALUnit *parseH264NalUnits(uint8_t *buf, int size, int *numNals) {
int i, j, offset = 0;
NALUnit *nals = NULL;
*numNals = 0;
while (offset < size) {
int startCode = findStartCode(buf + offset, size - offset);
if (startCode < 0) {
startCode = size - offset;
} else {
startCode += 3;
}
int end = 0;
for (i = startCode; i < size - offset; i++) {
if (buf[offset + i] == 0x00 && buf[offset + i + 1] == 0x00) {
if (buf[offset + i + 2] == 0x00) {
i += 2;
continue;
} else if (buf[offset + i + 2] == 0x01) {
end = i;
break;
}
}
}
if (end == 0) {
end = size - offset;
}
(*numNals)++;
nals = realloc(nals, (*numNals) * sizeof(NALUnit));
nals[(*numNals) - 1].data = buf + offset + startCode;
nals[(*numNals) - 1].size = end - startCode;
offset += end;
}
return nals;
}
```
`findStartCode` 函数用于查找 H.264 NAL 单元的起始码 `0x000001` 或 `0x00000001`,返回起始码在 `buf` 中的偏移量,如果找不到则返回 `-1`。
`parseH264NalUnits` 函数用于解析 `buf` 中的 H.264 NAL 单元,返回解析出的 NAL 单元数组和 NAL 单元数量,如果解析失败则返回 `NULL` 和 `0`。对于每个 NAL 单元,函数使用 `realloc` 动态分配内存,并将 NAL 数据和长度保存在 `NALUnit` 结构体中。注意,解析出的 NAL 单元不包括起始码,需要自行处理。
示例代码如下:
```c
AVPacket *pkt = ...;
uint8_t *buf = pkt->data;
int size = pkt->size;
int numNals;
NALUnit *nals = parseH264NalUnits(buf, size, &numNals);
if (nals != NULL) {
for (int i = 0; i < numNals; i++) {
uint8_t *nalData = nals[i].data;
int nalSize = nals[i].size;
// 处理 H.264 NAL 单元
...
}
free(nals);
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)