ts的包大小:188字节
ts包的开始字节:0x47
TS包头定义:
(包头定义转载自:http://blog.csdn.net/shuyong1999/article/details/7095032)
typedef struct TS_packet_header
{
unsigned sync_byte : 8; //同步字节, 固定为0x47,表示后面的是一个TS分组
unsigned transport_error_indicator : 1; //传输误码指示符
unsigned payload_unit_start_indicator : 1; //有效荷载单元起始指示符
unsigned transport_priority : 1; //传输优先, 1表示高优先级,传输机制可能用到,解码用不着
unsigned PID : 13; //PID
unsigned transport_scrambling_control : 2; //传输加扰控制
unsigned adaption_field_control : 2; //自适应控制 01仅含有效负载,10仅含调整字段,11含有调整字段和有效负载。为00解码器不进行处理
unsigned continuity_counter : 4; //连续计数器 一个4bit的计数器,范围0-15
} TS_packet_header;
因为要分离出ts文件中每个pid的数据,所以,最重要的当然是先获取pid的值:
int pid = ((buf[1] & 0x1f) << 8) + buf[2];
其它就是逻辑问题了,详细代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <map>
using namespace std;
#define TS_SIZE 188
bool dir_exists (const string &dir)
{
struct stat statx = {0};
int ret = stat (dir.c_str(), &statx);
if (ret == 0) {
if (S_ISDIR (statx.st_mode))
return true;
}
return false;
}
string i2str(int i)
{
char buffer[20];
sprintf (buffer, "%d", i);
return buffer;
}
int main(int argc, char **argv)
{
if (argc != 3) {
cout << argv[0] << " ts_file save_dir" << endl;
return 0;
}
const string ts_file = argv[1];
const string save_dir = argv[2];
if (!dir_exists (save_dir)) {
mkdir (save_dir.c_str (), 0777);
}
FILE *stream = NULL; //to fopen input ts file
FILE *save_file_fp = NULL;// to fopen save ts file
unsigned char buf[TS_SIZE];
int len;
string pid_file = save_dir + "/pid.file"; //init ts save file
if ((stream = fopen (ts_file.c_str (), "rb"))== NULL) {
fclose (stream);
cout << "ts file open error" << endl;
return -1;
}
while (!feof (stream)) {
len = fread (buf, sizeof (unsigned char), TS_SIZE, stream);
cout << "read len:" << len << endl;
if (buf[0] != 0x47) {
cout << "Sync byte of TS isn't 0x47!, skip it." << endl;
//long curpos = ftell (stream);
fseek (stream, (1 - TS_SIZE), SEEK_CUR);
continue;
}
int pid = ((buf[1] & 0x1f) << 8) + buf[2];
cout << "pid: " << pid << endl;
pid_file = save_dir + "/" + i2str(pid) + ".file";
save_file_fp = fopen (pid_file.c_str (), "ab");
len = fwrite (buf, sizeof (unsigned char), TS_SIZE, save_file_fp);
cout << "write len:" << len << endl;
fclose (save_file_fp);
}
fclose (stream);
return 0;
}