protected virtual int FindTSHeadFlag(byte[] data) { var ms = new MemoryStream(data); var tsms = new TSProgramManage(); int pos = 0; while (pos++ < data.Length) { // var index = ms.Position; if (ms.ReadByte() == 0x47) { int offset = (int)ms.Position - 1; if (!CheckOffsetIsPacketFlag(data, offset)) { continue; } ms.Seek(-1, SeekOrigin.Current); byte[] buf = new byte[188]; ms.Read(buf, 0, buf.Length); try { TSPacket pack = new TSPacket() { ProgramManage = tsms }; pack.SetBytes(buf); pack.Decode(); ms.Seek(-188, SeekOrigin.Current); return((int)ms.Position); } catch (Exception) { return(-1); } } } return(-1); }
protected virtual void TSStreamResolveThread() { byte[] buffer_ts = new byte[188 * 2]; //两个包的空间,这里需要读取两个188字节的ts packet 而不是读取一个的原因是, //读取两个,当可以检验前后ts packet标识字段是否为0x47,如果不是则当前位置不是处理ts packet的开头, //则需要重新找到ts packet的头 byte[] part_ts = null;//当检测到当前ts packet错误的时候 part_ts用来保存正确的ts packet中的一部分 while (_isworking) { int readSize = 188 * 2 - (part_ts != null ? part_ts.Length : 0);//如果上一次没有残留数据则长度为 2个ts packet 的长度 if (_ioStream.Length >= readSize) { if (part_ts != null) { Array.Copy(part_ts, 0, buffer_ts, 0, part_ts.Length); //残留数据 } _ioStream.Read(buffer_ts, buffer_ts.Length - readSize, readSize); //读取到缓冲区 if (buffer_ts[0] != 0x47) { //当前为非 ts packet的头,则找到下一个ts packet的头的偏移 int offset = FindTSHeadFlag(buffer_ts); if (offset == -1)//没有找到头则返回起点 { continue; } //从2*188字节中减去偏移,再减去一个ts packet的长度得到残余的数据长度 part_ts = new byte[buffer_ts.Length - 188 - offset]; Array.Copy(buffer_ts, offset + 188, part_ts, 0, part_ts.Length); //新建一个临时的缓冲区,并将完整 的ts数据copy到这个临时缓冲区中 var tmp_buffer = new byte[188]; Array.Copy(buffer_ts, offset, tmp_buffer, 0, tmp_buffer.Length); try { var pack = new TSPacket() { ProgramManage = _tsms }; pack.SetBytes(tmp_buffer); pack.Decode(); if (pack.PacketType == TSPacketType.DATA) { pack.ProgramManage.WriteMediaTSPacket(pack); } } catch (Exception e) { _DebugEx.Trace("TSStreamInput", "解析TS失败 1" + e.ToString()); } } else { //当前为 ts packet的头,则找到下一个ts packet的头的偏移 try { //判断前后两个ts packet是否开头均正确 if (buffer_ts[0] == 0x47 && buffer_ts[188] == 0x47) { //将两个ts packet 分别解析 var tmp_buffer = new byte[188]; Array.Copy(buffer_ts, 0, tmp_buffer, 0, tmp_buffer.Length); TSPacket pack = new TSPacket() { ProgramManage = _tsms }; pack.SetBytes(tmp_buffer); pack.Decode(); if (pack.PacketType == TSPacketType.DATA) { pack.ProgramManage.WriteMediaTSPacket(pack); } Array.Copy(buffer_ts, 188, tmp_buffer, 0, tmp_buffer.Length); pack = new TSPacket() { ProgramManage = _tsms }; pack.SetBytes(tmp_buffer); pack.Decode(); if (pack.PacketType == TSPacketType.DATA) { pack.ProgramManage.WriteMediaTSPacket(pack); } } else { _DebugEx.Trace("TSStreamInput", "TS Packet HeadFlag Error"); throw new Exception("TS Packet HeadFlag Error"); } } catch (Exception e) { _DebugEx.Trace("TSStreamInput", "解析TS失败 2" + e.ToString()); } part_ts = null; } } else { Thread.Sleep(10); } } }