我使用SDP的profile-level-id et sprop-parameter-set设置了AvCodecContext的profile_idc,level_idc,extradata和extradata_size。
我将Coded Slice,SPS,PPS和NAL_IDR_SLICE数据包的解码分开:
uint8_t start_sequence [] = {0,0,1}; int size = recv(id_de_la_socket,(char *)rtpReceive,65535,0);
char *z = new char[size-16+sizeof(start_sequence)];
memcpy(z,&start_sequence,sizeof(start_sequence));
memcpy(z+sizeof(start_sequence),rtpReceive+16,size-16);
ConsumedBytes = avcodec_decode_video(codecContext,pFrame,&GotPicture,(uint8_t*)z,size-16+sizeof(start_sequence));
delete z;
结果:ConsumedBytes> 0和GotPicture> 0(经常)
我认为这是正常的
当我找到一对新的SPS / PPS时,我使用此数据包的有效负载及其大小更新extradata和extrada_size。
Nal单位类型是28 => idr帧被分段为此我尝试了两种方法来解码
1)我将第一个片段(没有RTP头)加上序列0x000001的前缀,并将其发送到avcodec_decode_video。然后我将剩下的片段发送到这个函数。
2)我在第一个片段(没有RTP头)前加上序列0x000001,并将其余片段连接到它。我把这个缓冲区发送给解码器。
在这两种情况下,我都没有错误(ConsumedBytes> 0)但我没有检测到任何帧(GotPicture = 0)......
有什么问题?
答案 0 :(得分:25)
在RTP中,所有H264 I帧(IDR)通常都是碎片化的。当您收到RTP时,首先必须跳过标题(通常是前12个字节),然后转到NAL单元(第一个有效负载字节)。如果NAL是28(1C)那么这意味着跟随有效载荷代表一个H264 IDR(I帧)片段,并且您需要收集所有这些片段以重建H264 IDR(I帧)。
由于有限的MTU和更大的IDR而发生碎片。一个片段可能如下所示:
START BIT = 1的片段
First byte: [ 3 NAL UNIT BITS | 5 FRAGMENT TYPE BITS]
Second byte: [ START BIT | END BIT | RESERVED BIT | 5 NAL UNIT BITS]
Other bytes: [... IDR FRAGMENT DATA...]
其他片段:
First byte: [ 3 NAL UNIT BITS | 5 FRAGMENT TYPE BITS]
Other bytes: [... IDR FRAGMENT DATA...]
要重建IDR,您必须收集此信息:
int fragment_type = Data[0] & 0x1F;
int nal_type = Data[1] & 0x1F;
int start_bit = Data[1] & 0x80;
int end_bit = Data[1] & 0x40;
如果fragment_type == 28
,那么它后面的有效载荷就是IDR的一个片段。接下来检查是start_bit
设置,如果是,则该片段是序列中的第一个。您可以通过从第一个有效负载字节(3 NAL UNIT BITS)
获取前3位来重建IDR的NAL字节,并将它们与来自第二个有效负载字节(5 NAL UNIT BITS)
的最后5位组合,这样您就可以得到像这样的字节{{1 }}。然后将该NAL字节首先写入一个清除缓冲区,该缓冲区包含该片段中的所有其他后续字节。请记住跳过序列中的第一个字节,因为它不是IDR的一部分,但只识别片段。
如果[3 NAL UNIT BITS | 5 NAL UNIT BITS]
和start_bit
为0,则只需将有效负载(跳过标识该片段的第一个有效负载字节)写入缓冲区。
如果start_bit为0且end_bit为1,则表示它是最后一个片段,您只需将其有效负载(跳过标识该片段的第一个字节)写入缓冲区,现在您重建了IDR。 / p>
如果您需要一些代码,请在评论中提问,我会发布,但我认为这很清楚如何做... =)
关于解码
今天我想到了为什么你在解码IDR时遇到错误(我认为你已经很好地重建了它)。您是如何构建AVC解码器配置记录的?您使用的lib是否具有自动化功能?如果没有,你还没有听说过,继续阅读......
指定AVCDCR允许解码器快速解析解码H264(AVC)视频流所需的所有数据。数据如下:
所有这些数据都在SDP的RTSP会话中在字段end_bit
和profile-level-id
下发送。
解码PROFILE-LEVEL-ID
Prifile级别ID字符串分为3个子字符串,每个字符串长2个字符:
sprop-parameter-sets
每个子字符串代表base16 中的一个字节!因此,如果Profile IDC为28,则表示它在base10中实际为40。稍后您将使用base10值来构建AVC解码器配置记录。
解码SPROP-PARAMETER-SETS
Sprops通常是以逗号分隔的2个字符串(可能更多), base64编码!你可以解码它们,但没有必要。你的工作就是将它们从base64字符串转换为字节数组供以后使用。现在你有2个字节的数组,第一个数组是SPS,第二个是PPS。
构建AVCDCR
现在,您已经拥有构建AVCDCR所需的一切,首先要创建新的干净缓冲区,现在按照此处说明的顺序将这些内容写入其中:
1 - 值 1 并表示版本
的字节2 - 配置文件IDC字节
3 - Prifile IOP字节
4 - 级别IDC字节
5 - 值为0xFF的字节(谷歌AVC解码器配置记录,看看这是什么)
6 - 值为0xE1的字节
7 - SPS数组长度的值短
8 - SPS字节数组
9 - 具有PPS阵列数量的字节(你可以在sprop-parameter-set中有更多它们)
10 - 跟随PPS阵列的长度
11 - PPS阵列
解码视频流
现在你有字节数组告诉解码器如何解码H264视频流。我相信你需要这个,如果你的lib不是自己从SDP构建它......
答案 1 :(得分:1)
我不知道你的其他实现,但你收到的'片段'似乎很可能是NAL单位。因此,在将比特流发送到ffmpeg之前,每个都可能需要附加NALU起始码(00 00 01
或00 00 00 01
)。
无论如何,您可能会发现H264 RTP打包的RFC非常有用:
http://www.rfc-editor.org/rfc/rfc3984.txt
希望这有帮助!
答案 2 :(得分:1)
我为c#实现了这个@ https://net7mma.codeplex.com/,但这个过程在任何地方都是一样的。
以下是相关代码
/// <summary>
/// Implements Packetization and Depacketization of packets defined in <see href="https://tools.ietf.org/html/rfc6184">RFC6184</see>.
/// </summary>
public class RFC6184Frame : Rtp.RtpFrame
{
/// <summary>
/// Emulation Prevention
/// </summary>
static byte[] NalStart = { 0x00, 0x00, 0x01 };
public RFC6184Frame(byte payloadType) : base(payloadType) { }
public RFC6184Frame(Rtp.RtpFrame existing) : base(existing) { }
public RFC6184Frame(RFC6184Frame f) : this((Rtp.RtpFrame)f) { Buffer = f.Buffer; }
public System.IO.MemoryStream Buffer { get; set; }
/// <summary>
/// Creates any <see cref="Rtp.RtpPacket"/>'s required for the given nal
/// </summary>
/// <param name="nal">The nal</param>
/// <param name="mtu">The mtu</param>
public virtual void Packetize(byte[] nal, int mtu = 1500)
{
if (nal == null) return;
int nalLength = nal.Length;
int offset = 0;
if (nalLength >= mtu)
{
//Make a Fragment Indicator with start bit
byte[] FUI = new byte[] { (byte)(1 << 7), 0x00 };
bool marker = false;
while (offset < nalLength)
{
//Set the end bit if no more data remains
if (offset + mtu > nalLength)
{
FUI[0] |= (byte)(1 << 6);
marker = true;
}
else if (offset > 0) //For packets other than the start
{
//No Start, No End
FUI[0] = 0;
}
//Add the packet
Add(new Rtp.RtpPacket(2, false, false, marker, PayloadTypeByte, 0, SynchronizationSourceIdentifier, HighestSequenceNumber + 1, 0, FUI.Concat(nal.Skip(offset).Take(mtu)).ToArray()));
//Move the offset
offset += mtu;
}
} //Should check for first byte to be 1 - 23?
else Add(new Rtp.RtpPacket(2, false, false, true, PayloadTypeByte, 0, SynchronizationSourceIdentifier, HighestSequenceNumber + 1, 0, nal));
}
/// <summary>
/// Creates <see cref="Buffer"/> with a H.264 RBSP from the contained packets
/// </summary>
public virtual void Depacketize() { bool sps, pps, sei, slice, idr; Depacketize(out sps, out pps, out sei, out slice, out idr); }
/// <summary>
/// Parses all contained packets and writes any contained Nal Units in the RBSP to <see cref="Buffer"/>.
/// </summary>
/// <param name="containsSps">Indicates if a Sequence Parameter Set was found</param>
/// <param name="containsPps">Indicates if a Picture Parameter Set was found</param>
/// <param name="containsSei">Indicates if Supplementatal Encoder Information was found</param>
/// <param name="containsSlice">Indicates if a Slice was found</param>
/// <param name="isIdr">Indicates if a IDR Slice was found</param>
public virtual void Depacketize(out bool containsSps, out bool containsPps, out bool containsSei, out bool containsSlice, out bool isIdr)
{
containsSps = containsPps = containsSei = containsSlice = isIdr = false;
DisposeBuffer();
this.Buffer = new MemoryStream();
//Get all packets in the frame
foreach (Rtp.RtpPacket packet in m_Packets.Values.Distinct())
ProcessPacket(packet, out containsSps, out containsPps, out containsSei, out containsSlice, out isIdr);
//Order by DON?
this.Buffer.Position = 0;
}
/// <summary>
/// Depacketizes a single packet.
/// </summary>
/// <param name="packet"></param>
/// <param name="containsSps"></param>
/// <param name="containsPps"></param>
/// <param name="containsSei"></param>
/// <param name="containsSlice"></param>
/// <param name="isIdr"></param>
internal protected virtual void ProcessPacket(Rtp.RtpPacket packet, out bool containsSps, out bool containsPps, out bool containsSei, out bool containsSlice, out bool isIdr)
{
containsSps = containsPps = containsSei = containsSlice = isIdr = false;
//Starting at offset 0
int offset = 0;
//Obtain the data of the packet (without source list or padding)
byte[] packetData = packet.Coefficients.ToArray();
//Cache the length
int count = packetData.Length;
//Must have at least 2 bytes
if (count <= 2) return;
//Determine if the forbidden bit is set and the type of nal from the first byte
byte firstByte = packetData[offset];
//bool forbiddenZeroBit = ((firstByte & 0x80) >> 7) != 0;
byte nalUnitType = (byte)(firstByte & Common.Binary.FiveBitMaxValue);
//o The F bit MUST be cleared if all F bits of the aggregated NAL units are zero; otherwise, it MUST be set.
//if (forbiddenZeroBit && nalUnitType <= 23 && nalUnitType > 29) throw new InvalidOperationException("Forbidden Zero Bit is Set.");
//Determine what to do
switch (nalUnitType)
{
//Reserved - Ignore
case 0:
case 30:
case 31:
{
return;
}
case 24: //STAP - A
case 25: //STAP - B
case 26: //MTAP - 16
case 27: //MTAP - 24
{
//Move to Nal Data
++offset;
//Todo Determine if need to Order by DON first.
//EAT DON for ALL BUT STAP - A
if (nalUnitType != 24) offset += 2;
//Consume the rest of the data from the packet
while (offset < count)
{
//Determine the nal unit size which does not include the nal header
int tmp_nal_size = Common.Binary.Read16(packetData, offset, BitConverter.IsLittleEndian);
offset += 2;
//If the nal had data then write it
if (tmp_nal_size > 0)
{
//For DOND and TSOFFSET
switch (nalUnitType)
{
case 25:// MTAP - 16
{
//SKIP DOND and TSOFFSET
offset += 3;
goto default;
}
case 26:// MTAP - 24
{
//SKIP DOND and TSOFFSET
offset += 4;
goto default;
}
default:
{
//Read the nal header but don't move the offset
byte nalHeader = (byte)(packetData[offset] & Common.Binary.FiveBitMaxValue);
if (nalHeader > 5)
{
if (nalHeader == 6)
{
Buffer.WriteByte(0);
containsSei = true;
}
else if (nalHeader == 7)
{
Buffer.WriteByte(0);
containsPps = true;
}
else if (nalHeader == 8)
{
Buffer.WriteByte(0);
containsSps = true;
}
}
if (nalHeader == 1) containsSlice = true;
if (nalHeader == 5) isIdr = true;
//Done reading
break;
}
}
//Write the start code
Buffer.Write(NalStart, 0, 3);
//Write the nal header and data
Buffer.Write(packetData, offset, tmp_nal_size);
//Move the offset past the nal
offset += tmp_nal_size;
}
}
return;
}
case 28: //FU - A
case 29: //FU - B
{
/*
Informative note: When an FU-A occurs in interleaved mode, it
always follows an FU-B, which sets its DON.
* Informative note: If a transmitter wants to encapsulate a single
NAL unit per packet and transmit packets out of their decoding
order, STAP-B packet type can be used.
*/
//Need 2 bytes
if (count > 2)
{
//Read the Header
byte FUHeader = packetData[++offset];
bool Start = ((FUHeader & 0x80) >> 7) > 0;
//bool End = ((FUHeader & 0x40) >> 6) > 0;
//bool Receiver = (FUHeader & 0x20) != 0;
//if (Receiver) throw new InvalidOperationException("Receiver Bit Set");
//Move to data
++offset;
//Todo Determine if need to Order by DON first.
//DON Present in FU - B
if (nalUnitType == 29) offset += 2;
//Determine the fragment size
int fragment_size = count - offset;
//If the size was valid
if (fragment_size > 0)
{
//If the start bit was set
if (Start)
{
//Reconstruct the nal header
//Use the first 3 bits of the first byte and last 5 bites of the FU Header
byte nalHeader = (byte)((firstByte & 0xE0) | (FUHeader & Common.Binary.FiveBitMaxValue));
//Could have been SPS / PPS / SEI
if (nalHeader > 5)
{
if (nalHeader == 6)
{
Buffer.WriteByte(0);
containsSei = true;
}
else if (nalHeader == 7)
{
Buffer.WriteByte(0);
containsPps = true;
}
else if (nalHeader == 8)
{
Buffer.WriteByte(0);
containsSps = true;
}
}
if (nalHeader == 1) containsSlice = true;
if (nalHeader == 5) isIdr = true;
//Write the start code
Buffer.Write(NalStart, 0, 3);
//Write the re-construced header
Buffer.WriteByte(nalHeader);
}
//Write the data of the fragment.
Buffer.Write(packetData, offset, fragment_size);
}
}
return;
}
default:
{
// 6 SEI, 7 and 8 are SPS and PPS
if (nalUnitType > 5)
{
if (nalUnitType == 6)
{
Buffer.WriteByte(0);
containsSei = true;
}
else if (nalUnitType == 7)
{
Buffer.WriteByte(0);
containsPps = true;
}
else if (nalUnitType == 8)
{
Buffer.WriteByte(0);
containsSps = true;
}
}
if (nalUnitType == 1) containsSlice = true;
if (nalUnitType == 5) isIdr = true;
//Write the start code
Buffer.Write(NalStart, 0, 3);
//Write the nal heaer and data data
Buffer.Write(packetData, offset, count - offset);
return;
}
}
}
internal void DisposeBuffer()
{
if (Buffer != null)
{
Buffer.Dispose();
Buffer = null;
}
}
public override void Dispose()
{
if (Disposed) return;
base.Dispose();
DisposeBuffer();
}
//To go to an Image...
//Look for a SliceHeader in the Buffer
//Decode Macroblocks in Slice
//Convert Yuv to Rgb
}
还有各种其他RFC的实现,它们有助于将媒体播放到MediaElement或其他软件中,或者只是将其保存到磁盘。
正在写入容器格式。