mpegts.c 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952
  1. /*
  2. * MPEG2 transport stream (aka DVB) demuxer
  3. * Copyright (c) 2002-2003 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. //#define USE_SYNCPOINT_SEARCH
  22. #include "libavutil/crc.h"
  23. #include "libavutil/intreadwrite.h"
  24. #include "libavutil/log.h"
  25. #include "libavutil/dict.h"
  26. #include "libavutil/mathematics.h"
  27. #include "libavutil/opt.h"
  28. #include "libavcodec/bytestream.h"
  29. #include "avformat.h"
  30. #include "mpegts.h"
  31. #include "internal.h"
  32. #include "avio_internal.h"
  33. #include "seek.h"
  34. #include "mpeg.h"
  35. #include "isom.h"
  36. /* maximum size in which we look for synchronisation if
  37. synchronisation is lost */
  38. #define MAX_RESYNC_SIZE 65536
  39. #define MAX_PES_PAYLOAD 200*1024
  40. enum MpegTSFilterType {
  41. MPEGTS_PES,
  42. MPEGTS_SECTION,
  43. };
  44. typedef struct MpegTSFilter MpegTSFilter;
  45. typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
  46. typedef struct MpegTSPESFilter {
  47. PESCallback *pes_cb;
  48. void *opaque;
  49. } MpegTSPESFilter;
  50. typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
  51. typedef void SetServiceCallback(void *opaque, int ret);
  52. typedef struct MpegTSSectionFilter {
  53. int section_index;
  54. int section_h_size;
  55. uint8_t *section_buf;
  56. unsigned int check_crc:1;
  57. unsigned int end_of_section_reached:1;
  58. SectionCallback *section_cb;
  59. void *opaque;
  60. } MpegTSSectionFilter;
  61. struct MpegTSFilter {
  62. int pid;
  63. int last_cc; /* last cc code (-1 if first packet) */
  64. enum MpegTSFilterType type;
  65. union {
  66. MpegTSPESFilter pes_filter;
  67. MpegTSSectionFilter section_filter;
  68. } u;
  69. };
  70. #define MAX_PIDS_PER_PROGRAM 64
  71. struct Program {
  72. unsigned int id; //program id/service id
  73. unsigned int nb_pids;
  74. unsigned int pids[MAX_PIDS_PER_PROGRAM];
  75. };
  76. struct MpegTSContext {
  77. const AVClass *class;
  78. /* user data */
  79. AVFormatContext *stream;
  80. /** raw packet size, including FEC if present */
  81. int raw_packet_size;
  82. int pos47;
  83. /** if true, all pids are analyzed to find streams */
  84. int auto_guess;
  85. /** compute exact PCR for each transport stream packet */
  86. int mpeg2ts_compute_pcr;
  87. int64_t cur_pcr; /**< used to estimate the exact PCR */
  88. int pcr_incr; /**< used to estimate the exact PCR */
  89. /* data needed to handle file based ts */
  90. /** stop parsing loop */
  91. int stop_parse;
  92. /** packet containing Audio/Video data */
  93. AVPacket *pkt;
  94. /** to detect seek */
  95. int64_t last_pos;
  96. /******************************************/
  97. /* private mpegts data */
  98. /* scan context */
  99. /** structure to keep track of Program->pids mapping */
  100. unsigned int nb_prg;
  101. struct Program *prg;
  102. /** filters for various streams specified by PMT + for the PAT and PMT */
  103. MpegTSFilter *pids[NB_PID_MAX];
  104. };
  105. static const AVOption options[] = {
  106. {"compute_pcr", "Compute exact PCR for each transport stream packet.", offsetof(MpegTSContext, mpeg2ts_compute_pcr), FF_OPT_TYPE_INT,
  107. {.dbl = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
  108. { NULL },
  109. };
  110. static const AVClass mpegtsraw_class = {
  111. .class_name = "mpegtsraw demuxer",
  112. .item_name = av_default_item_name,
  113. .option = options,
  114. .version = LIBAVUTIL_VERSION_INT,
  115. };
  116. /* TS stream handling */
  117. enum MpegTSState {
  118. MPEGTS_HEADER = 0,
  119. MPEGTS_PESHEADER,
  120. MPEGTS_PESHEADER_FILL,
  121. MPEGTS_PAYLOAD,
  122. MPEGTS_SKIP,
  123. };
  124. /* enough for PES header + length */
  125. #define PES_START_SIZE 6
  126. #define PES_HEADER_SIZE 9
  127. #define MAX_PES_HEADER_SIZE (9 + 255)
  128. typedef struct PESContext {
  129. int pid;
  130. int pcr_pid; /**< if -1 then all packets containing PCR are considered */
  131. int stream_type;
  132. MpegTSContext *ts;
  133. AVFormatContext *stream;
  134. AVStream *st;
  135. AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
  136. enum MpegTSState state;
  137. /* used to get the format */
  138. int data_index;
  139. int flags; /**< copied to the AVPacket flags */
  140. int total_size;
  141. int pes_header_size;
  142. int extended_stream_id;
  143. int64_t pts, dts;
  144. int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
  145. uint8_t header[MAX_PES_HEADER_SIZE];
  146. uint8_t *buffer;
  147. } PESContext;
  148. extern AVInputFormat ff_mpegts_demuxer;
  149. static void clear_program(MpegTSContext *ts, unsigned int programid)
  150. {
  151. int i;
  152. for(i=0; i<ts->nb_prg; i++)
  153. if(ts->prg[i].id == programid)
  154. ts->prg[i].nb_pids = 0;
  155. }
  156. static void clear_programs(MpegTSContext *ts)
  157. {
  158. av_freep(&ts->prg);
  159. ts->nb_prg=0;
  160. }
  161. static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
  162. {
  163. struct Program *p;
  164. void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
  165. if(!tmp)
  166. return;
  167. ts->prg = tmp;
  168. p = &ts->prg[ts->nb_prg];
  169. p->id = programid;
  170. p->nb_pids = 0;
  171. ts->nb_prg++;
  172. }
  173. static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
  174. {
  175. int i;
  176. struct Program *p = NULL;
  177. for(i=0; i<ts->nb_prg; i++) {
  178. if(ts->prg[i].id == programid) {
  179. p = &ts->prg[i];
  180. break;
  181. }
  182. }
  183. if(!p)
  184. return;
  185. if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
  186. return;
  187. p->pids[p->nb_pids++] = pid;
  188. }
  189. static void set_pcr_pid(AVFormatContext *s, unsigned int programid, unsigned int pid)
  190. {
  191. int i;
  192. for(i=0; i<s->nb_programs; i++) {
  193. if(s->programs[i]->id == programid) {
  194. s->programs[i]->pcr_pid = pid;
  195. break;
  196. }
  197. }
  198. }
  199. /**
  200. * @brief discard_pid() decides if the pid is to be discarded according
  201. * to caller's programs selection
  202. * @param ts : - TS context
  203. * @param pid : - pid
  204. * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
  205. * 0 otherwise
  206. */
  207. static int discard_pid(MpegTSContext *ts, unsigned int pid)
  208. {
  209. int i, j, k;
  210. int used = 0, discarded = 0;
  211. struct Program *p;
  212. for(i=0; i<ts->nb_prg; i++) {
  213. p = &ts->prg[i];
  214. for(j=0; j<p->nb_pids; j++) {
  215. if(p->pids[j] != pid)
  216. continue;
  217. //is program with id p->id set to be discarded?
  218. for(k=0; k<ts->stream->nb_programs; k++) {
  219. if(ts->stream->programs[k]->id == p->id) {
  220. if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
  221. discarded++;
  222. else
  223. used++;
  224. }
  225. }
  226. }
  227. }
  228. return !used && discarded;
  229. }
  230. /**
  231. * Assemble PES packets out of TS packets, and then call the "section_cb"
  232. * function when they are complete.
  233. */
  234. static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
  235. const uint8_t *buf, int buf_size, int is_start)
  236. {
  237. MpegTSSectionFilter *tss = &tss1->u.section_filter;
  238. int len;
  239. if (is_start) {
  240. memcpy(tss->section_buf, buf, buf_size);
  241. tss->section_index = buf_size;
  242. tss->section_h_size = -1;
  243. tss->end_of_section_reached = 0;
  244. } else {
  245. if (tss->end_of_section_reached)
  246. return;
  247. len = 4096 - tss->section_index;
  248. if (buf_size < len)
  249. len = buf_size;
  250. memcpy(tss->section_buf + tss->section_index, buf, len);
  251. tss->section_index += len;
  252. }
  253. /* compute section length if possible */
  254. if (tss->section_h_size == -1 && tss->section_index >= 3) {
  255. len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
  256. if (len > 4096)
  257. return;
  258. tss->section_h_size = len;
  259. }
  260. if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
  261. tss->end_of_section_reached = 1;
  262. if (!tss->check_crc ||
  263. av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
  264. tss->section_buf, tss->section_h_size) == 0)
  265. tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
  266. }
  267. }
  268. static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
  269. SectionCallback *section_cb, void *opaque,
  270. int check_crc)
  271. {
  272. MpegTSFilter *filter;
  273. MpegTSSectionFilter *sec;
  274. av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
  275. if (pid >= NB_PID_MAX || ts->pids[pid])
  276. return NULL;
  277. filter = av_mallocz(sizeof(MpegTSFilter));
  278. if (!filter)
  279. return NULL;
  280. ts->pids[pid] = filter;
  281. filter->type = MPEGTS_SECTION;
  282. filter->pid = pid;
  283. filter->last_cc = -1;
  284. sec = &filter->u.section_filter;
  285. sec->section_cb = section_cb;
  286. sec->opaque = opaque;
  287. sec->section_buf = av_malloc(MAX_SECTION_SIZE);
  288. sec->check_crc = check_crc;
  289. if (!sec->section_buf) {
  290. av_free(filter);
  291. return NULL;
  292. }
  293. return filter;
  294. }
  295. static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
  296. PESCallback *pes_cb,
  297. void *opaque)
  298. {
  299. MpegTSFilter *filter;
  300. MpegTSPESFilter *pes;
  301. if (pid >= NB_PID_MAX || ts->pids[pid])
  302. return NULL;
  303. filter = av_mallocz(sizeof(MpegTSFilter));
  304. if (!filter)
  305. return NULL;
  306. ts->pids[pid] = filter;
  307. filter->type = MPEGTS_PES;
  308. filter->pid = pid;
  309. filter->last_cc = -1;
  310. pes = &filter->u.pes_filter;
  311. pes->pes_cb = pes_cb;
  312. pes->opaque = opaque;
  313. return filter;
  314. }
  315. static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
  316. {
  317. int pid;
  318. pid = filter->pid;
  319. if (filter->type == MPEGTS_SECTION)
  320. av_freep(&filter->u.section_filter.section_buf);
  321. else if (filter->type == MPEGTS_PES) {
  322. PESContext *pes = filter->u.pes_filter.opaque;
  323. av_freep(&pes->buffer);
  324. /* referenced private data will be freed later in
  325. * av_close_input_stream */
  326. if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
  327. av_freep(&filter->u.pes_filter.opaque);
  328. }
  329. }
  330. av_free(filter);
  331. ts->pids[pid] = NULL;
  332. }
  333. static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
  334. int stat[TS_MAX_PACKET_SIZE];
  335. int i;
  336. int x=0;
  337. int best_score=0;
  338. memset(stat, 0, packet_size*sizeof(int));
  339. for(x=i=0; i<size-3; i++){
  340. if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
  341. stat[x]++;
  342. if(stat[x] > best_score){
  343. best_score= stat[x];
  344. if(index) *index= x;
  345. }
  346. }
  347. x++;
  348. if(x == packet_size) x= 0;
  349. }
  350. return best_score;
  351. }
  352. /* autodetect fec presence. Must have at least 1024 bytes */
  353. static int get_packet_size(const uint8_t *buf, int size)
  354. {
  355. int score, fec_score, dvhs_score;
  356. if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
  357. return -1;
  358. score = analyze(buf, size, TS_PACKET_SIZE, NULL);
  359. dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
  360. fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
  361. // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
  362. if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
  363. else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
  364. else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
  365. else return -1;
  366. }
  367. typedef struct SectionHeader {
  368. uint8_t tid;
  369. uint16_t id;
  370. uint8_t version;
  371. uint8_t sec_num;
  372. uint8_t last_sec_num;
  373. } SectionHeader;
  374. static inline int get8(const uint8_t **pp, const uint8_t *p_end)
  375. {
  376. const uint8_t *p;
  377. int c;
  378. p = *pp;
  379. if (p >= p_end)
  380. return -1;
  381. c = *p++;
  382. *pp = p;
  383. return c;
  384. }
  385. static inline int get16(const uint8_t **pp, const uint8_t *p_end)
  386. {
  387. const uint8_t *p;
  388. int c;
  389. p = *pp;
  390. if ((p + 1) >= p_end)
  391. return -1;
  392. c = AV_RB16(p);
  393. p += 2;
  394. *pp = p;
  395. return c;
  396. }
  397. /* read and allocate a DVB string preceeded by its length */
  398. static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
  399. {
  400. int len;
  401. const uint8_t *p;
  402. char *str;
  403. p = *pp;
  404. len = get8(&p, p_end);
  405. if (len < 0)
  406. return NULL;
  407. if ((p + len) > p_end)
  408. return NULL;
  409. str = av_malloc(len + 1);
  410. if (!str)
  411. return NULL;
  412. memcpy(str, p, len);
  413. str[len] = '\0';
  414. p += len;
  415. *pp = p;
  416. return str;
  417. }
  418. static int parse_section_header(SectionHeader *h,
  419. const uint8_t **pp, const uint8_t *p_end)
  420. {
  421. int val;
  422. val = get8(pp, p_end);
  423. if (val < 0)
  424. return -1;
  425. h->tid = val;
  426. *pp += 2;
  427. val = get16(pp, p_end);
  428. if (val < 0)
  429. return -1;
  430. h->id = val;
  431. val = get8(pp, p_end);
  432. if (val < 0)
  433. return -1;
  434. h->version = (val >> 1) & 0x1f;
  435. val = get8(pp, p_end);
  436. if (val < 0)
  437. return -1;
  438. h->sec_num = val;
  439. val = get8(pp, p_end);
  440. if (val < 0)
  441. return -1;
  442. h->last_sec_num = val;
  443. return 0;
  444. }
  445. typedef struct {
  446. uint32_t stream_type;
  447. enum AVMediaType codec_type;
  448. enum CodecID codec_id;
  449. } StreamType;
  450. static const StreamType ISO_types[] = {
  451. { 0x01, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
  452. { 0x02, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
  453. { 0x03, AVMEDIA_TYPE_AUDIO, CODEC_ID_MP3 },
  454. { 0x04, AVMEDIA_TYPE_AUDIO, CODEC_ID_MP3 },
  455. { 0x0f, AVMEDIA_TYPE_AUDIO, CODEC_ID_AAC },
  456. { 0x10, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG4 },
  457. { 0x11, AVMEDIA_TYPE_AUDIO, CODEC_ID_AAC_LATM }, /* LATM syntax */
  458. { 0x1b, AVMEDIA_TYPE_VIDEO, CODEC_ID_H264 },
  459. { 0xd1, AVMEDIA_TYPE_VIDEO, CODEC_ID_DIRAC },
  460. { 0xea, AVMEDIA_TYPE_VIDEO, CODEC_ID_VC1 },
  461. { 0 },
  462. };
  463. static const StreamType HDMV_types[] = {
  464. { 0x80, AVMEDIA_TYPE_AUDIO, CODEC_ID_PCM_BLURAY },
  465. { 0x81, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
  466. { 0x82, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
  467. { 0x83, AVMEDIA_TYPE_AUDIO, CODEC_ID_TRUEHD },
  468. { 0x84, AVMEDIA_TYPE_AUDIO, CODEC_ID_EAC3 },
  469. { 0x90, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_HDMV_PGS_SUBTITLE },
  470. { 0 },
  471. };
  472. /* ATSC ? */
  473. static const StreamType MISC_types[] = {
  474. { 0x81, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
  475. { 0x8a, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
  476. { 0 },
  477. };
  478. static const StreamType REGD_types[] = {
  479. { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, CODEC_ID_DIRAC },
  480. { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
  481. { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, CODEC_ID_S302M },
  482. { 0 },
  483. };
  484. /* descriptor present */
  485. static const StreamType DESC_types[] = {
  486. { 0x6a, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 }, /* AC-3 descriptor */
  487. { 0x7a, AVMEDIA_TYPE_AUDIO, CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
  488. { 0x7b, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
  489. { 0x56, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_TELETEXT },
  490. { 0x59, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
  491. { 0 },
  492. };
  493. static void mpegts_find_stream_type(AVStream *st,
  494. uint32_t stream_type, const StreamType *types)
  495. {
  496. for (; types->stream_type; types++) {
  497. if (stream_type == types->stream_type) {
  498. st->codec->codec_type = types->codec_type;
  499. st->codec->codec_id = types->codec_id;
  500. st->request_probe = 0;
  501. return;
  502. }
  503. }
  504. }
  505. static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
  506. uint32_t stream_type, uint32_t prog_reg_desc)
  507. {
  508. av_set_pts_info(st, 33, 1, 90000);
  509. st->priv_data = pes;
  510. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  511. st->codec->codec_id = CODEC_ID_NONE;
  512. st->need_parsing = AVSTREAM_PARSE_FULL;
  513. pes->st = st;
  514. pes->stream_type = stream_type;
  515. av_log(pes->stream, AV_LOG_DEBUG,
  516. "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
  517. st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
  518. st->codec->codec_tag = pes->stream_type;
  519. mpegts_find_stream_type(st, pes->stream_type, ISO_types);
  520. if (prog_reg_desc == AV_RL32("HDMV") &&
  521. st->codec->codec_id == CODEC_ID_NONE) {
  522. mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
  523. if (pes->stream_type == 0x83) {
  524. // HDMV TrueHD streams also contain an AC3 coded version of the
  525. // audio track - add a second stream for this
  526. AVStream *sub_st;
  527. // priv_data cannot be shared between streams
  528. PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
  529. if (!sub_pes)
  530. return AVERROR(ENOMEM);
  531. memcpy(sub_pes, pes, sizeof(*sub_pes));
  532. sub_st = av_new_stream(pes->stream, pes->pid);
  533. if (!sub_st) {
  534. av_free(sub_pes);
  535. return AVERROR(ENOMEM);
  536. }
  537. av_set_pts_info(sub_st, 33, 1, 90000);
  538. sub_st->priv_data = sub_pes;
  539. sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  540. sub_st->codec->codec_id = CODEC_ID_AC3;
  541. sub_st->need_parsing = AVSTREAM_PARSE_FULL;
  542. sub_pes->sub_st = pes->sub_st = sub_st;
  543. }
  544. }
  545. if (st->codec->codec_id == CODEC_ID_NONE)
  546. mpegts_find_stream_type(st, pes->stream_type, MISC_types);
  547. return 0;
  548. }
  549. static void new_pes_packet(PESContext *pes, AVPacket *pkt)
  550. {
  551. av_init_packet(pkt);
  552. pkt->destruct = av_destruct_packet;
  553. pkt->data = pes->buffer;
  554. pkt->size = pes->data_index;
  555. if(pes->total_size != MAX_PES_PAYLOAD &&
  556. pes->pes_header_size + pes->data_index != pes->total_size + 6) {
  557. av_log(pes->ts, AV_LOG_WARNING, "PES packet size mismatch\n");
  558. pes->flags |= AV_PKT_FLAG_CORRUPT;
  559. }
  560. memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  561. // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
  562. if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
  563. pkt->stream_index = pes->sub_st->index;
  564. else
  565. pkt->stream_index = pes->st->index;
  566. pkt->pts = pes->pts;
  567. pkt->dts = pes->dts;
  568. /* store position of first TS packet of this PES packet */
  569. pkt->pos = pes->ts_packet_pos;
  570. pkt->flags = pes->flags;
  571. /* reset pts values */
  572. pes->pts = AV_NOPTS_VALUE;
  573. pes->dts = AV_NOPTS_VALUE;
  574. pes->buffer = NULL;
  575. pes->data_index = 0;
  576. pes->flags = 0;
  577. }
  578. /* return non zero if a packet could be constructed */
  579. static int mpegts_push_data(MpegTSFilter *filter,
  580. const uint8_t *buf, int buf_size, int is_start,
  581. int64_t pos)
  582. {
  583. PESContext *pes = filter->u.pes_filter.opaque;
  584. MpegTSContext *ts = pes->ts;
  585. const uint8_t *p;
  586. int len, code;
  587. if(!ts->pkt)
  588. return 0;
  589. if (is_start) {
  590. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  591. new_pes_packet(pes, ts->pkt);
  592. ts->stop_parse = 1;
  593. }
  594. pes->state = MPEGTS_HEADER;
  595. pes->data_index = 0;
  596. pes->ts_packet_pos = pos;
  597. }
  598. p = buf;
  599. while (buf_size > 0) {
  600. switch(pes->state) {
  601. case MPEGTS_HEADER:
  602. len = PES_START_SIZE - pes->data_index;
  603. if (len > buf_size)
  604. len = buf_size;
  605. memcpy(pes->header + pes->data_index, p, len);
  606. pes->data_index += len;
  607. p += len;
  608. buf_size -= len;
  609. if (pes->data_index == PES_START_SIZE) {
  610. /* we got all the PES or section header. We can now
  611. decide */
  612. if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
  613. pes->header[2] == 0x01) {
  614. /* it must be an mpeg2 PES stream */
  615. code = pes->header[3] | 0x100;
  616. av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
  617. if ((pes->st && pes->st->discard == AVDISCARD_ALL) ||
  618. code == 0x1be) /* padding_stream */
  619. goto skip;
  620. #if FF_API_MAX_STREAMS
  621. if (!pes->st && pes->stream->nb_streams == MAX_STREAMS)
  622. goto skip;
  623. #endif
  624. /* stream not present in PMT */
  625. if (!pes->st) {
  626. pes->st = av_new_stream(ts->stream, pes->pid);
  627. if (!pes->st)
  628. return AVERROR(ENOMEM);
  629. mpegts_set_stream_info(pes->st, pes, 0, 0);
  630. }
  631. pes->total_size = AV_RB16(pes->header + 4);
  632. /* NOTE: a zero total size means the PES size is
  633. unbounded */
  634. if (!pes->total_size)
  635. pes->total_size = MAX_PES_PAYLOAD;
  636. /* allocate pes buffer */
  637. pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
  638. if (!pes->buffer)
  639. return AVERROR(ENOMEM);
  640. if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
  641. code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
  642. code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
  643. code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
  644. pes->state = MPEGTS_PESHEADER;
  645. if (pes->st->codec->codec_id == CODEC_ID_NONE && !pes->st->request_probe) {
  646. av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
  647. pes->pid, pes->stream_type);
  648. pes->st->request_probe= 1;
  649. }
  650. } else {
  651. pes->state = MPEGTS_PAYLOAD;
  652. pes->data_index = 0;
  653. }
  654. } else {
  655. /* otherwise, it should be a table */
  656. /* skip packet */
  657. skip:
  658. pes->state = MPEGTS_SKIP;
  659. continue;
  660. }
  661. }
  662. break;
  663. /**********************************************/
  664. /* PES packing parsing */
  665. case MPEGTS_PESHEADER:
  666. len = PES_HEADER_SIZE - pes->data_index;
  667. if (len < 0)
  668. return -1;
  669. if (len > buf_size)
  670. len = buf_size;
  671. memcpy(pes->header + pes->data_index, p, len);
  672. pes->data_index += len;
  673. p += len;
  674. buf_size -= len;
  675. if (pes->data_index == PES_HEADER_SIZE) {
  676. pes->pes_header_size = pes->header[8] + 9;
  677. pes->state = MPEGTS_PESHEADER_FILL;
  678. }
  679. break;
  680. case MPEGTS_PESHEADER_FILL:
  681. len = pes->pes_header_size - pes->data_index;
  682. if (len < 0)
  683. return -1;
  684. if (len > buf_size)
  685. len = buf_size;
  686. memcpy(pes->header + pes->data_index, p, len);
  687. pes->data_index += len;
  688. p += len;
  689. buf_size -= len;
  690. if (pes->data_index == pes->pes_header_size) {
  691. const uint8_t *r;
  692. unsigned int flags, pes_ext, skip;
  693. flags = pes->header[7];
  694. r = pes->header + 9;
  695. pes->pts = AV_NOPTS_VALUE;
  696. pes->dts = AV_NOPTS_VALUE;
  697. if ((flags & 0xc0) == 0x80) {
  698. pes->dts = pes->pts = ff_parse_pes_pts(r);
  699. r += 5;
  700. } else if ((flags & 0xc0) == 0xc0) {
  701. pes->pts = ff_parse_pes_pts(r);
  702. r += 5;
  703. pes->dts = ff_parse_pes_pts(r);
  704. r += 5;
  705. }
  706. pes->extended_stream_id = -1;
  707. if (flags & 0x01) { /* PES extension */
  708. pes_ext = *r++;
  709. /* Skip PES private data, program packet sequence counter and P-STD buffer */
  710. skip = (pes_ext >> 4) & 0xb;
  711. skip += skip & 0x9;
  712. r += skip;
  713. if ((pes_ext & 0x41) == 0x01 &&
  714. (r + 2) <= (pes->header + pes->pes_header_size)) {
  715. /* PES extension 2 */
  716. if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
  717. pes->extended_stream_id = r[1];
  718. }
  719. }
  720. /* we got the full header. We parse it and get the payload */
  721. pes->state = MPEGTS_PAYLOAD;
  722. pes->data_index = 0;
  723. }
  724. break;
  725. case MPEGTS_PAYLOAD:
  726. if (buf_size > 0 && pes->buffer) {
  727. if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
  728. new_pes_packet(pes, ts->pkt);
  729. pes->total_size = MAX_PES_PAYLOAD;
  730. pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
  731. if (!pes->buffer)
  732. return AVERROR(ENOMEM);
  733. ts->stop_parse = 1;
  734. } else if (pes->data_index == 0 && buf_size > pes->total_size) {
  735. // pes packet size is < ts size packet and pes data is padded with 0xff
  736. // not sure if this is legal in ts but see issue #2392
  737. buf_size = pes->total_size;
  738. }
  739. memcpy(pes->buffer+pes->data_index, p, buf_size);
  740. pes->data_index += buf_size;
  741. }
  742. buf_size = 0;
  743. /* emit complete packets with known packet size
  744. * decreases demuxer delay for infrequent packets like subtitles from
  745. * a couple of seconds to milliseconds for properly muxed files.
  746. * total_size is the number of bytes following pes_packet_length
  747. * in the pes header, i.e. not counting the first 6 bytes */
  748. if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
  749. pes->pes_header_size + pes->data_index == pes->total_size + 6) {
  750. ts->stop_parse = 1;
  751. new_pes_packet(pes, ts->pkt);
  752. }
  753. break;
  754. case MPEGTS_SKIP:
  755. buf_size = 0;
  756. break;
  757. }
  758. }
  759. return 0;
  760. }
  761. static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
  762. {
  763. MpegTSFilter *tss;
  764. PESContext *pes;
  765. /* if no pid found, then add a pid context */
  766. pes = av_mallocz(sizeof(PESContext));
  767. if (!pes)
  768. return 0;
  769. pes->ts = ts;
  770. pes->stream = ts->stream;
  771. pes->pid = pid;
  772. pes->pcr_pid = pcr_pid;
  773. pes->state = MPEGTS_SKIP;
  774. pes->pts = AV_NOPTS_VALUE;
  775. pes->dts = AV_NOPTS_VALUE;
  776. tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
  777. if (!tss) {
  778. av_free(pes);
  779. return 0;
  780. }
  781. return pes;
  782. }
  783. static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
  784. int *es_id, uint8_t **dec_config_descr,
  785. int *dec_config_descr_size)
  786. {
  787. AVIOContext pb;
  788. int tag;
  789. unsigned len;
  790. ffio_init_context(&pb, buf, size, 0, NULL, NULL, NULL, NULL);
  791. len = ff_mp4_read_descr(s, &pb, &tag);
  792. if (tag == MP4IODescrTag) {
  793. avio_rb16(&pb); // ID
  794. avio_r8(&pb);
  795. avio_r8(&pb);
  796. avio_r8(&pb);
  797. avio_r8(&pb);
  798. avio_r8(&pb);
  799. len = ff_mp4_read_descr(s, &pb, &tag);
  800. if (tag == MP4ESDescrTag) {
  801. *es_id = avio_rb16(&pb); /* ES_ID */
  802. av_dlog(s, "ES_ID %#x\n", *es_id);
  803. avio_r8(&pb); /* priority */
  804. len = ff_mp4_read_descr(s, &pb, &tag);
  805. if (tag == MP4DecConfigDescrTag) {
  806. *dec_config_descr = av_malloc(len);
  807. if (!*dec_config_descr)
  808. return AVERROR(ENOMEM);
  809. *dec_config_descr_size = len;
  810. avio_read(&pb, *dec_config_descr, len);
  811. }
  812. }
  813. }
  814. return 0;
  815. }
  816. int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
  817. const uint8_t **pp, const uint8_t *desc_list_end,
  818. int mp4_dec_config_descr_len, int mp4_es_id, int pid,
  819. uint8_t *mp4_dec_config_descr)
  820. {
  821. const uint8_t *desc_end;
  822. int desc_len, desc_tag;
  823. char language[252];
  824. int i;
  825. desc_tag = get8(pp, desc_list_end);
  826. if (desc_tag < 0)
  827. return -1;
  828. desc_len = get8(pp, desc_list_end);
  829. if (desc_len < 0)
  830. return -1;
  831. desc_end = *pp + desc_len;
  832. if (desc_end > desc_list_end)
  833. return -1;
  834. av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
  835. if (st->codec->codec_id == CODEC_ID_NONE &&
  836. stream_type == STREAM_TYPE_PRIVATE_DATA)
  837. mpegts_find_stream_type(st, desc_tag, DESC_types);
  838. switch(desc_tag) {
  839. case 0x1F: /* FMC descriptor */
  840. get16(pp, desc_end);
  841. if (st->codec->codec_id == CODEC_ID_AAC_LATM &&
  842. mp4_dec_config_descr_len && mp4_es_id == pid) {
  843. AVIOContext pb;
  844. ffio_init_context(&pb, mp4_dec_config_descr,
  845. mp4_dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
  846. ff_mp4_read_dec_config_descr(fc, st, &pb);
  847. if (st->codec->codec_id == CODEC_ID_AAC &&
  848. st->codec->extradata_size > 0)
  849. st->need_parsing = 0;
  850. }
  851. break;
  852. case 0x56: /* DVB teletext descriptor */
  853. language[0] = get8(pp, desc_end);
  854. language[1] = get8(pp, desc_end);
  855. language[2] = get8(pp, desc_end);
  856. language[3] = 0;
  857. av_dict_set(&st->metadata, "language", language, 0);
  858. break;
  859. case 0x59: /* subtitling descriptor */
  860. language[0] = get8(pp, desc_end);
  861. language[1] = get8(pp, desc_end);
  862. language[2] = get8(pp, desc_end);
  863. language[3] = 0;
  864. /* hearing impaired subtitles detection */
  865. switch(get8(pp, desc_end)) {
  866. case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
  867. case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
  868. case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
  869. case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
  870. case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
  871. case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
  872. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  873. break;
  874. }
  875. if (st->codec->extradata) {
  876. if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
  877. av_log_ask_for_sample(fc, "DVB sub with multiple IDs\n");
  878. } else {
  879. st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
  880. if (st->codec->extradata) {
  881. st->codec->extradata_size = 4;
  882. memcpy(st->codec->extradata, *pp, 4);
  883. }
  884. }
  885. *pp += 4;
  886. av_dict_set(&st->metadata, "language", language, 0);
  887. break;
  888. case 0x0a: /* ISO 639 language descriptor */
  889. for (i = 0; i + 4 <= desc_len; i += 4) {
  890. language[i + 0] = get8(pp, desc_end);
  891. language[i + 1] = get8(pp, desc_end);
  892. language[i + 2] = get8(pp, desc_end);
  893. language[i + 3] = ',';
  894. switch (get8(pp, desc_end)) {
  895. case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
  896. case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
  897. case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
  898. }
  899. }
  900. if (i) {
  901. language[i - 1] = 0;
  902. av_dict_set(&st->metadata, "language", language, 0);
  903. }
  904. break;
  905. case 0x05: /* registration descriptor */
  906. st->codec->codec_tag = bytestream_get_le32(pp);
  907. av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
  908. if (st->codec->codec_id == CODEC_ID_NONE &&
  909. stream_type == STREAM_TYPE_PRIVATE_DATA)
  910. mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
  911. break;
  912. case 0x52: /* stream identifier descriptor */
  913. st->stream_identifier = 1 + get8(pp, desc_end);
  914. break;
  915. default:
  916. break;
  917. }
  918. *pp = desc_end;
  919. return 0;
  920. }
  921. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  922. {
  923. MpegTSContext *ts = filter->u.section_filter.opaque;
  924. SectionHeader h1, *h = &h1;
  925. PESContext *pes;
  926. AVStream *st;
  927. const uint8_t *p, *p_end, *desc_list_end;
  928. int program_info_length, pcr_pid, pid, stream_type;
  929. int desc_list_len;
  930. uint32_t prog_reg_desc = 0; /* registration descriptor */
  931. uint8_t *mp4_dec_config_descr = NULL;
  932. int mp4_dec_config_descr_len = 0;
  933. int mp4_es_id = 0;
  934. av_dlog(ts->stream, "PMT: len %i\n", section_len);
  935. hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
  936. p_end = section + section_len - 4;
  937. p = section;
  938. if (parse_section_header(h, &p, p_end) < 0)
  939. return;
  940. av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
  941. h->id, h->sec_num, h->last_sec_num);
  942. if (h->tid != PMT_TID)
  943. return;
  944. clear_program(ts, h->id);
  945. pcr_pid = get16(&p, p_end) & 0x1fff;
  946. if (pcr_pid < 0)
  947. return;
  948. add_pid_to_pmt(ts, h->id, pcr_pid);
  949. set_pcr_pid(ts->stream, h->id, pcr_pid);
  950. av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
  951. program_info_length = get16(&p, p_end) & 0xfff;
  952. if (program_info_length < 0)
  953. return;
  954. while(program_info_length >= 2) {
  955. uint8_t tag, len;
  956. tag = get8(&p, p_end);
  957. len = get8(&p, p_end);
  958. av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
  959. if(len > program_info_length - 2)
  960. //something else is broken, exit the program_descriptors_loop
  961. break;
  962. program_info_length -= len + 2;
  963. if (tag == 0x1d) { // IOD descriptor
  964. get8(&p, p_end); // scope
  965. get8(&p, p_end); // label
  966. len -= 2;
  967. mp4_read_iods(ts->stream, p, len, &mp4_es_id,
  968. &mp4_dec_config_descr, &mp4_dec_config_descr_len);
  969. } else if (tag == 0x05 && len >= 4) { // registration descriptor
  970. prog_reg_desc = bytestream_get_le32(&p);
  971. len -= 4;
  972. }
  973. p += len;
  974. }
  975. p += program_info_length;
  976. if (p >= p_end)
  977. goto out;
  978. // stop parsing after pmt, we found header
  979. if (!ts->stream->nb_streams)
  980. ts->stop_parse = 2;
  981. for(;;) {
  982. st = 0;
  983. stream_type = get8(&p, p_end);
  984. if (stream_type < 0)
  985. break;
  986. pid = get16(&p, p_end) & 0x1fff;
  987. if (pid < 0)
  988. break;
  989. /* now create ffmpeg stream */
  990. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  991. pes = ts->pids[pid]->u.pes_filter.opaque;
  992. if (!pes->st)
  993. pes->st = av_new_stream(pes->stream, pes->pid);
  994. st = pes->st;
  995. } else {
  996. if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
  997. pes = add_pes_stream(ts, pid, pcr_pid);
  998. if (pes)
  999. st = av_new_stream(pes->stream, pes->pid);
  1000. }
  1001. if (!st)
  1002. goto out;
  1003. if (!pes->stream_type)
  1004. mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
  1005. add_pid_to_pmt(ts, h->id, pid);
  1006. ff_program_add_stream_index(ts->stream, h->id, st->index);
  1007. desc_list_len = get16(&p, p_end) & 0xfff;
  1008. if (desc_list_len < 0)
  1009. break;
  1010. desc_list_end = p + desc_list_len;
  1011. if (desc_list_end > p_end)
  1012. break;
  1013. for(;;) {
  1014. if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
  1015. mp4_dec_config_descr_len, mp4_es_id, pid, mp4_dec_config_descr) < 0)
  1016. break;
  1017. if (prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
  1018. ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
  1019. pes->sub_st->codec->codec_tag = st->codec->codec_tag;
  1020. }
  1021. }
  1022. p = desc_list_end;
  1023. }
  1024. out:
  1025. av_free(mp4_dec_config_descr);
  1026. }
  1027. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1028. {
  1029. MpegTSContext *ts = filter->u.section_filter.opaque;
  1030. SectionHeader h1, *h = &h1;
  1031. const uint8_t *p, *p_end;
  1032. int sid, pmt_pid;
  1033. AVProgram *program;
  1034. av_dlog(ts->stream, "PAT:\n");
  1035. hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
  1036. p_end = section + section_len - 4;
  1037. p = section;
  1038. if (parse_section_header(h, &p, p_end) < 0)
  1039. return;
  1040. if (h->tid != PAT_TID)
  1041. return;
  1042. ts->stream->ts_id = h->id;
  1043. clear_programs(ts);
  1044. for(;;) {
  1045. sid = get16(&p, p_end);
  1046. if (sid < 0)
  1047. break;
  1048. pmt_pid = get16(&p, p_end) & 0x1fff;
  1049. if (pmt_pid < 0)
  1050. break;
  1051. av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  1052. if (sid == 0x0000) {
  1053. /* NIT info */
  1054. } else {
  1055. program = av_new_program(ts->stream, sid);
  1056. program->program_num = sid;
  1057. program->pmt_pid = pmt_pid;
  1058. if (ts->pids[pmt_pid])
  1059. mpegts_close_filter(ts, ts->pids[pmt_pid]);
  1060. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  1061. add_pat_entry(ts, sid);
  1062. add_pid_to_pmt(ts, sid, 0); //add pat pid to program
  1063. add_pid_to_pmt(ts, sid, pmt_pid);
  1064. }
  1065. }
  1066. }
  1067. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1068. {
  1069. MpegTSContext *ts = filter->u.section_filter.opaque;
  1070. SectionHeader h1, *h = &h1;
  1071. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  1072. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  1073. char *name, *provider_name;
  1074. av_dlog(ts->stream, "SDT:\n");
  1075. hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
  1076. p_end = section + section_len - 4;
  1077. p = section;
  1078. if (parse_section_header(h, &p, p_end) < 0)
  1079. return;
  1080. if (h->tid != SDT_TID)
  1081. return;
  1082. onid = get16(&p, p_end);
  1083. if (onid < 0)
  1084. return;
  1085. val = get8(&p, p_end);
  1086. if (val < 0)
  1087. return;
  1088. for(;;) {
  1089. sid = get16(&p, p_end);
  1090. if (sid < 0)
  1091. break;
  1092. val = get8(&p, p_end);
  1093. if (val < 0)
  1094. break;
  1095. desc_list_len = get16(&p, p_end) & 0xfff;
  1096. if (desc_list_len < 0)
  1097. break;
  1098. desc_list_end = p + desc_list_len;
  1099. if (desc_list_end > p_end)
  1100. break;
  1101. for(;;) {
  1102. desc_tag = get8(&p, desc_list_end);
  1103. if (desc_tag < 0)
  1104. break;
  1105. desc_len = get8(&p, desc_list_end);
  1106. desc_end = p + desc_len;
  1107. if (desc_end > desc_list_end)
  1108. break;
  1109. av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
  1110. desc_tag, desc_len);
  1111. switch(desc_tag) {
  1112. case 0x48:
  1113. service_type = get8(&p, p_end);
  1114. if (service_type < 0)
  1115. break;
  1116. provider_name = getstr8(&p, p_end);
  1117. if (!provider_name)
  1118. break;
  1119. name = getstr8(&p, p_end);
  1120. if (name) {
  1121. AVProgram *program = av_new_program(ts->stream, sid);
  1122. if(program) {
  1123. av_dict_set(&program->metadata, "service_name", name, 0);
  1124. av_dict_set(&program->metadata, "service_provider", provider_name, 0);
  1125. }
  1126. }
  1127. av_free(name);
  1128. av_free(provider_name);
  1129. break;
  1130. default:
  1131. break;
  1132. }
  1133. p = desc_end;
  1134. }
  1135. p = desc_list_end;
  1136. }
  1137. }
  1138. /* handle one TS packet */
  1139. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  1140. {
  1141. AVFormatContext *s = ts->stream;
  1142. MpegTSFilter *tss;
  1143. int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
  1144. has_adaptation, has_payload;
  1145. const uint8_t *p, *p_end;
  1146. int64_t pos;
  1147. pid = AV_RB16(packet + 1) & 0x1fff;
  1148. if(pid && discard_pid(ts, pid))
  1149. return 0;
  1150. is_start = packet[1] & 0x40;
  1151. tss = ts->pids[pid];
  1152. if (ts->auto_guess && tss == NULL && is_start) {
  1153. add_pes_stream(ts, pid, -1);
  1154. tss = ts->pids[pid];
  1155. }
  1156. if (!tss)
  1157. return 0;
  1158. afc = (packet[3] >> 4) & 3;
  1159. if (afc == 0) /* reserved value */
  1160. return 0;
  1161. has_adaptation = afc & 2;
  1162. has_payload = afc & 1;
  1163. is_discontinuity = has_adaptation
  1164. && packet[4] != 0 /* with length > 0 */
  1165. && (packet[5] & 0x80); /* and discontinuity indicated */
  1166. /* continuity check (currently not used) */
  1167. cc = (packet[3] & 0xf);
  1168. expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
  1169. cc_ok = pid == 0x1FFF // null packet PID
  1170. || is_discontinuity
  1171. || tss->last_cc < 0
  1172. || expected_cc == cc;
  1173. tss->last_cc = cc;
  1174. if (!cc_ok) {
  1175. av_log(ts, AV_LOG_WARNING, "Continuity Check Failed\n");
  1176. if(tss->type == MPEGTS_PES) {
  1177. PESContext *pc = tss->u.pes_filter.opaque;
  1178. pc->flags |= AV_PKT_FLAG_CORRUPT;
  1179. }
  1180. }
  1181. if (!has_payload)
  1182. return 0;
  1183. p = packet + 4;
  1184. if (has_adaptation) {
  1185. /* skip adapation field */
  1186. p += p[0] + 1;
  1187. }
  1188. /* if past the end of packet, ignore */
  1189. p_end = packet + TS_PACKET_SIZE;
  1190. if (p >= p_end)
  1191. return 0;
  1192. pos = avio_tell(ts->stream->pb);
  1193. ts->pos47= pos % ts->raw_packet_size;
  1194. if (tss->type == MPEGTS_SECTION) {
  1195. if (is_start) {
  1196. /* pointer field present */
  1197. len = *p++;
  1198. if (p + len > p_end)
  1199. return 0;
  1200. if (len && cc_ok) {
  1201. /* write remaining section bytes */
  1202. write_section_data(s, tss,
  1203. p, len, 0);
  1204. /* check whether filter has been closed */
  1205. if (!ts->pids[pid])
  1206. return 0;
  1207. }
  1208. p += len;
  1209. if (p < p_end) {
  1210. write_section_data(s, tss,
  1211. p, p_end - p, 1);
  1212. }
  1213. } else {
  1214. if (cc_ok) {
  1215. write_section_data(s, tss,
  1216. p, p_end - p, 0);
  1217. }
  1218. }
  1219. } else {
  1220. int ret;
  1221. // Note: The position here points actually behind the current packet.
  1222. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  1223. pos - ts->raw_packet_size)) < 0)
  1224. return ret;
  1225. }
  1226. return 0;
  1227. }
  1228. /* XXX: try to find a better synchro over several packets (use
  1229. get_packet_size() ?) */
  1230. static int mpegts_resync(AVFormatContext *s)
  1231. {
  1232. AVIOContext *pb = s->pb;
  1233. int c, i;
  1234. for(i = 0;i < MAX_RESYNC_SIZE; i++) {
  1235. c = avio_r8(pb);
  1236. if (url_feof(pb))
  1237. return -1;
  1238. if (c == 0x47) {
  1239. avio_seek(pb, -1, SEEK_CUR);
  1240. return 0;
  1241. }
  1242. }
  1243. av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
  1244. /* no sync found */
  1245. return -1;
  1246. }
  1247. /* return -1 if error or EOF. Return 0 if OK. */
  1248. static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
  1249. {
  1250. AVIOContext *pb = s->pb;
  1251. int skip, len;
  1252. for(;;) {
  1253. len = avio_read(pb, buf, TS_PACKET_SIZE);
  1254. if (len != TS_PACKET_SIZE)
  1255. return len < 0 ? len : AVERROR_EOF;
  1256. /* check paquet sync byte */
  1257. if (buf[0] != 0x47) {
  1258. /* find a new packet start */
  1259. avio_seek(pb, -TS_PACKET_SIZE, SEEK_CUR);
  1260. if (mpegts_resync(s) < 0)
  1261. return AVERROR(EAGAIN);
  1262. else
  1263. continue;
  1264. } else {
  1265. skip = raw_packet_size - TS_PACKET_SIZE;
  1266. if (skip > 0)
  1267. avio_skip(pb, skip);
  1268. break;
  1269. }
  1270. }
  1271. return 0;
  1272. }
  1273. static int handle_packets(MpegTSContext *ts, int nb_packets)
  1274. {
  1275. AVFormatContext *s = ts->stream;
  1276. uint8_t packet[TS_PACKET_SIZE];
  1277. int packet_num, ret = 0;
  1278. if (avio_tell(s->pb) != ts->last_pos) {
  1279. int i;
  1280. // av_dlog("Skipping after seek\n");
  1281. /* seek detected, flush pes buffer */
  1282. for (i = 0; i < NB_PID_MAX; i++) {
  1283. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1284. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1285. av_freep(&pes->buffer);
  1286. ts->pids[i]->last_cc = -1;
  1287. pes->data_index = 0;
  1288. pes->state = MPEGTS_SKIP; /* skip until pes header */
  1289. }
  1290. }
  1291. }
  1292. ts->stop_parse = 0;
  1293. packet_num = 0;
  1294. for(;;) {
  1295. packet_num++;
  1296. if (nb_packets != 0 && packet_num >= nb_packets ||
  1297. ts->stop_parse > 1) {
  1298. ret = AVERROR(EAGAIN);
  1299. break;
  1300. }
  1301. if (ts->stop_parse > 0)
  1302. break;
  1303. ret = read_packet(s, packet, ts->raw_packet_size);
  1304. if (ret != 0)
  1305. break;
  1306. ret = handle_packet(ts, packet);
  1307. if (ret != 0)
  1308. break;
  1309. }
  1310. ts->last_pos = avio_tell(s->pb);
  1311. return ret;
  1312. }
  1313. static int mpegts_probe(AVProbeData *p)
  1314. {
  1315. #if 1
  1316. const int size= p->buf_size;
  1317. int score, fec_score, dvhs_score;
  1318. int check_count= size / TS_FEC_PACKET_SIZE;
  1319. #define CHECK_COUNT 10
  1320. if (check_count < CHECK_COUNT)
  1321. return -1;
  1322. score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1323. dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
  1324. fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1325. // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
  1326. // we need a clear definition for the returned score otherwise things will become messy sooner or later
  1327. if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
  1328. else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
  1329. else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
  1330. else return -1;
  1331. #else
  1332. /* only use the extension for safer guess */
  1333. if (av_match_ext(p->filename, "ts"))
  1334. return AVPROBE_SCORE_MAX;
  1335. else
  1336. return 0;
  1337. #endif
  1338. }
  1339. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  1340. (-1) if not available */
  1341. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1342. const uint8_t *packet)
  1343. {
  1344. int afc, len, flags;
  1345. const uint8_t *p;
  1346. unsigned int v;
  1347. afc = (packet[3] >> 4) & 3;
  1348. if (afc <= 1)
  1349. return -1;
  1350. p = packet + 4;
  1351. len = p[0];
  1352. p++;
  1353. if (len == 0)
  1354. return -1;
  1355. flags = *p++;
  1356. len--;
  1357. if (!(flags & 0x10))
  1358. return -1;
  1359. if (len < 6)
  1360. return -1;
  1361. v = AV_RB32(p);
  1362. *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
  1363. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  1364. return 0;
  1365. }
  1366. static int mpegts_read_header(AVFormatContext *s,
  1367. AVFormatParameters *ap)
  1368. {
  1369. MpegTSContext *ts = s->priv_data;
  1370. AVIOContext *pb = s->pb;
  1371. uint8_t buf[8*1024];
  1372. int len;
  1373. int64_t pos;
  1374. #if FF_API_FORMAT_PARAMETERS
  1375. if (ap) {
  1376. if (ap->mpeg2ts_compute_pcr)
  1377. ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
  1378. }
  1379. #endif
  1380. /* read the first 1024 bytes to get packet size */
  1381. pos = avio_tell(pb);
  1382. len = avio_read(pb, buf, sizeof(buf));
  1383. if (len != sizeof(buf))
  1384. goto fail;
  1385. ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
  1386. if (ts->raw_packet_size <= 0) {
  1387. av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
  1388. ts->raw_packet_size = TS_PACKET_SIZE;
  1389. }
  1390. ts->stream = s;
  1391. ts->auto_guess = 0;
  1392. if (s->iformat == &ff_mpegts_demuxer) {
  1393. /* normal demux */
  1394. /* first do a scaning to get all the services */
  1395. if (pb->seekable && avio_seek(pb, pos, SEEK_SET) < 0)
  1396. av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
  1397. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  1398. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  1399. handle_packets(ts, s->probesize / ts->raw_packet_size);
  1400. /* if could not find service, enable auto_guess */
  1401. ts->auto_guess = 1;
  1402. av_dlog(ts->stream, "tuning done\n");
  1403. s->ctx_flags |= AVFMTCTX_NOHEADER;
  1404. } else {
  1405. AVStream *st;
  1406. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  1407. int64_t pcrs[2], pcr_h;
  1408. int packet_count[2];
  1409. uint8_t packet[TS_PACKET_SIZE];
  1410. /* only read packets */
  1411. st = av_new_stream(s, 0);
  1412. if (!st)
  1413. goto fail;
  1414. av_set_pts_info(st, 60, 1, 27000000);
  1415. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1416. st->codec->codec_id = CODEC_ID_MPEG2TS;
  1417. /* we iterate until we find two PCRs to estimate the bitrate */
  1418. pcr_pid = -1;
  1419. nb_pcrs = 0;
  1420. nb_packets = 0;
  1421. for(;;) {
  1422. ret = read_packet(s, packet, ts->raw_packet_size);
  1423. if (ret < 0)
  1424. return -1;
  1425. pid = AV_RB16(packet + 1) & 0x1fff;
  1426. if ((pcr_pid == -1 || pcr_pid == pid) &&
  1427. parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
  1428. pcr_pid = pid;
  1429. packet_count[nb_pcrs] = nb_packets;
  1430. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  1431. nb_pcrs++;
  1432. if (nb_pcrs >= 2)
  1433. break;
  1434. }
  1435. nb_packets++;
  1436. }
  1437. /* NOTE1: the bitrate is computed without the FEC */
  1438. /* NOTE2: it is only the bitrate of the start of the stream */
  1439. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  1440. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  1441. s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
  1442. st->codec->bit_rate = s->bit_rate;
  1443. st->start_time = ts->cur_pcr;
  1444. av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
  1445. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  1446. }
  1447. avio_seek(pb, pos, SEEK_SET);
  1448. return 0;
  1449. fail:
  1450. return -1;
  1451. }
  1452. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  1453. static int mpegts_raw_read_packet(AVFormatContext *s,
  1454. AVPacket *pkt)
  1455. {
  1456. MpegTSContext *ts = s->priv_data;
  1457. int ret, i;
  1458. int64_t pcr_h, next_pcr_h, pos;
  1459. int pcr_l, next_pcr_l;
  1460. uint8_t pcr_buf[12];
  1461. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  1462. return AVERROR(ENOMEM);
  1463. pkt->pos= avio_tell(s->pb);
  1464. ret = read_packet(s, pkt->data, ts->raw_packet_size);
  1465. if (ret < 0) {
  1466. av_free_packet(pkt);
  1467. return ret;
  1468. }
  1469. if (ts->mpeg2ts_compute_pcr) {
  1470. /* compute exact PCR for each packet */
  1471. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  1472. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  1473. pos = avio_tell(s->pb);
  1474. for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
  1475. avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  1476. avio_read(s->pb, pcr_buf, 12);
  1477. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  1478. /* XXX: not precise enough */
  1479. ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  1480. (i + 1);
  1481. break;
  1482. }
  1483. }
  1484. avio_seek(s->pb, pos, SEEK_SET);
  1485. /* no next PCR found: we use previous increment */
  1486. ts->cur_pcr = pcr_h * 300 + pcr_l;
  1487. }
  1488. pkt->pts = ts->cur_pcr;
  1489. pkt->duration = ts->pcr_incr;
  1490. ts->cur_pcr += ts->pcr_incr;
  1491. }
  1492. pkt->stream_index = 0;
  1493. return 0;
  1494. }
  1495. static int mpegts_read_packet(AVFormatContext *s,
  1496. AVPacket *pkt)
  1497. {
  1498. MpegTSContext *ts = s->priv_data;
  1499. int ret, i;
  1500. ts->pkt = pkt;
  1501. ret = handle_packets(ts, 0);
  1502. if (ret < 0) {
  1503. /* flush pes data left */
  1504. for (i = 0; i < NB_PID_MAX; i++) {
  1505. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1506. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1507. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  1508. new_pes_packet(pes, pkt);
  1509. pes->state = MPEGTS_SKIP;
  1510. ret = 0;
  1511. break;
  1512. }
  1513. }
  1514. }
  1515. }
  1516. return ret;
  1517. }
  1518. static int mpegts_read_close(AVFormatContext *s)
  1519. {
  1520. MpegTSContext *ts = s->priv_data;
  1521. int i;
  1522. clear_programs(ts);
  1523. for(i=0;i<NB_PID_MAX;i++)
  1524. if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
  1525. return 0;
  1526. }
  1527. static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  1528. int64_t *ppos, int64_t pos_limit)
  1529. {
  1530. MpegTSContext *ts = s->priv_data;
  1531. int64_t pos, timestamp;
  1532. uint8_t buf[TS_PACKET_SIZE];
  1533. int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
  1534. const int find_next= 1;
  1535. pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
  1536. if (find_next) {
  1537. for(;;) {
  1538. avio_seek(s->pb, pos, SEEK_SET);
  1539. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1540. return AV_NOPTS_VALUE;
  1541. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1542. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1543. break;
  1544. }
  1545. pos += ts->raw_packet_size;
  1546. }
  1547. } else {
  1548. for(;;) {
  1549. pos -= ts->raw_packet_size;
  1550. if (pos < 0)
  1551. return AV_NOPTS_VALUE;
  1552. avio_seek(s->pb, pos, SEEK_SET);
  1553. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1554. return AV_NOPTS_VALUE;
  1555. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1556. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1557. break;
  1558. }
  1559. }
  1560. }
  1561. *ppos = pos;
  1562. return timestamp;
  1563. }
  1564. #ifdef USE_SYNCPOINT_SEARCH
  1565. static int read_seek2(AVFormatContext *s,
  1566. int stream_index,
  1567. int64_t min_ts,
  1568. int64_t target_ts,
  1569. int64_t max_ts,
  1570. int flags)
  1571. {
  1572. int64_t pos;
  1573. int64_t ts_ret, ts_adj;
  1574. int stream_index_gen_search;
  1575. AVStream *st;
  1576. AVParserState *backup;
  1577. backup = ff_store_parser_state(s);
  1578. // detect direction of seeking for search purposes
  1579. flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ?
  1580. AVSEEK_FLAG_BACKWARD : 0;
  1581. if (flags & AVSEEK_FLAG_BYTE) {
  1582. // use position directly, we will search starting from it
  1583. pos = target_ts;
  1584. } else {
  1585. // search for some position with good timestamp match
  1586. if (stream_index < 0) {
  1587. stream_index_gen_search = av_find_default_stream_index(s);
  1588. if (stream_index_gen_search < 0) {
  1589. ff_restore_parser_state(s, backup);
  1590. return -1;
  1591. }
  1592. st = s->streams[stream_index_gen_search];
  1593. // timestamp for default must be expressed in AV_TIME_BASE units
  1594. ts_adj = av_rescale(target_ts,
  1595. st->time_base.den,
  1596. AV_TIME_BASE * (int64_t)st->time_base.num);
  1597. } else {
  1598. ts_adj = target_ts;
  1599. stream_index_gen_search = stream_index;
  1600. }
  1601. pos = av_gen_search(s, stream_index_gen_search, ts_adj,
  1602. 0, INT64_MAX, -1,
  1603. AV_NOPTS_VALUE,
  1604. AV_NOPTS_VALUE,
  1605. flags, &ts_ret, mpegts_get_pcr);
  1606. if (pos < 0) {
  1607. ff_restore_parser_state(s, backup);
  1608. return -1;
  1609. }
  1610. }
  1611. // search for actual matching keyframe/starting position for all streams
  1612. if (ff_gen_syncpoint_search(s, stream_index, pos,
  1613. min_ts, target_ts, max_ts,
  1614. flags) < 0) {
  1615. ff_restore_parser_state(s, backup);
  1616. return -1;
  1617. }
  1618. ff_free_parser_state(s, backup);
  1619. return 0;
  1620. }
  1621. static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
  1622. {
  1623. int ret;
  1624. if (flags & AVSEEK_FLAG_BACKWARD) {
  1625. flags &= ~AVSEEK_FLAG_BACKWARD;
  1626. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags);
  1627. if (ret < 0)
  1628. // for compatibility reasons, seek to the best-fitting timestamp
  1629. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
  1630. } else {
  1631. ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
  1632. if (ret < 0)
  1633. // for compatibility reasons, seek to the best-fitting timestamp
  1634. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
  1635. }
  1636. return ret;
  1637. }
  1638. #else
  1639. static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
  1640. MpegTSContext *ts = s->priv_data;
  1641. uint8_t buf[TS_PACKET_SIZE];
  1642. int64_t pos;
  1643. if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
  1644. return -1;
  1645. pos= avio_tell(s->pb);
  1646. for(;;) {
  1647. avio_seek(s->pb, pos, SEEK_SET);
  1648. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1649. return -1;
  1650. // pid = AV_RB16(buf + 1) & 0x1fff;
  1651. if(buf[1] & 0x40) break;
  1652. pos += ts->raw_packet_size;
  1653. }
  1654. avio_seek(s->pb, pos, SEEK_SET);
  1655. return 0;
  1656. }
  1657. #endif
  1658. /**************************************************************/
  1659. /* parsing functions - called from other demuxers such as RTP */
  1660. MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
  1661. {
  1662. MpegTSContext *ts;
  1663. ts = av_mallocz(sizeof(MpegTSContext));
  1664. if (!ts)
  1665. return NULL;
  1666. /* no stream case, currently used by RTP */
  1667. ts->raw_packet_size = TS_PACKET_SIZE;
  1668. ts->stream = s;
  1669. ts->auto_guess = 1;
  1670. return ts;
  1671. }
  1672. /* return the consumed length if a packet was output, or -1 if no
  1673. packet is output */
  1674. int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  1675. const uint8_t *buf, int len)
  1676. {
  1677. int len1;
  1678. len1 = len;
  1679. ts->pkt = pkt;
  1680. for(;;) {
  1681. ts->stop_parse = 0;
  1682. if (len < TS_PACKET_SIZE)
  1683. return -1;
  1684. if (buf[0] != 0x47) {
  1685. buf++;
  1686. len--;
  1687. } else {
  1688. handle_packet(ts, buf);
  1689. buf += TS_PACKET_SIZE;
  1690. len -= TS_PACKET_SIZE;
  1691. if (ts->stop_parse == 1)
  1692. break;
  1693. }
  1694. }
  1695. return len1 - len;
  1696. }
  1697. void ff_mpegts_parse_close(MpegTSContext *ts)
  1698. {
  1699. int i;
  1700. for(i=0;i<NB_PID_MAX;i++)
  1701. av_free(ts->pids[i]);
  1702. av_free(ts);
  1703. }
  1704. AVInputFormat ff_mpegts_demuxer = {
  1705. .name = "mpegts",
  1706. .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
  1707. .priv_data_size = sizeof(MpegTSContext),
  1708. .read_probe = mpegts_probe,
  1709. .read_header = mpegts_read_header,
  1710. .read_packet = mpegts_read_packet,
  1711. .read_close = mpegts_read_close,
  1712. .read_seek = read_seek,
  1713. .read_timestamp = mpegts_get_pcr,
  1714. .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
  1715. #ifdef USE_SYNCPOINT_SEARCH
  1716. .read_seek2 = read_seek2,
  1717. #endif
  1718. };
  1719. AVInputFormat ff_mpegtsraw_demuxer = {
  1720. .name = "mpegtsraw",
  1721. .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
  1722. .priv_data_size = sizeof(MpegTSContext),
  1723. .read_header = mpegts_read_header,
  1724. .read_packet = mpegts_raw_read_packet,
  1725. .read_close = mpegts_read_close,
  1726. .read_seek = read_seek,
  1727. .read_timestamp = mpegts_get_pcr,
  1728. .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
  1729. #ifdef USE_SYNCPOINT_SEARCH
  1730. .read_seek2 = read_seek2,
  1731. #endif
  1732. .priv_class = &mpegtsraw_class,
  1733. };