AVPacket的数据是如何拷贝的?
多个AVPacket 对象共享一个缓存空间,采用引用计数机制,初始化引用计数count= 0
当分配 AVBufferRef *buf内存的时候,count+1;当有新的Packet引用共享的缓存空间时,count+1;当释放了引用共享空间的Packet,count -1, 当count=0,释放buffer。

av_packet_move_ref 和 av_packet_move_ref 使用图例:

代码分析:引用计数:
int av_buffer_get_ref_count(const AVBufferRef *buf); // 查看引用计数的值
AVPacket *pkt = NULL;
AVPacket *pkt2 = NULL;
pkt = av_packet_alloc();
int ret = av_new_packet(pkt, MEM_ITEM_SIZE);
if(pkt->buf)
{ printf("1 : count(pkt) = %d\n",
av_buffer_get_ref_count(pkt->buf)); // count:1
}
memccpy(pkt->data, (void *)&av_packet_test1, 1, MEM_ITEM_SIZE);
pkt2 = av_packet_alloc();
av_packet_move_ref(pkt2, pkt); // count:1 pkt2:buffer不为空 pkt1: buffer为空
av_packet_ref(pkt, pkt2); // count:2 将pkt2数据拷贝到pkt1中, pkt 和 pkt2的引用计数相同
// av_packet_ref(pkt, pkt2); // av_packet_ref 拷贝相同的数据,不能连续使用此函数, 需av_packet_unref 后在使用,否则会内存泄露
if(pkt->buf)
{ printf("2 : count(pkt) = %d\n",
av_buffer_get_ref_count(pkt->buf)); // 2
}
if(pkt2->buf)
{ printf("2 : count(pkt2) = %d\n",
av_buffer_get_ref_count(pkt2->buf)); // 2
}
av_packet_unref(pkt); // count:1
// printf("count= %d\n", av_buffer_get_ref_count(pkt->buf)); // 不可打印,buffer已经释放
if( !(pkt->buf))
printf("pkt->buf is NULL\n"); // is null
av_packet_unref(pkt2); // count:1
av_packet_free(&pkt); // count:0
av_packet_free(&pkt2);
2326

被折叠的 条评论
为什么被折叠?



