Subversion Repositories Kolibri OS

Rev

Go to most recent revision | Blame | Last modification | View Log | RSS feed

  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.  
  22. #include "libavutil/buffer.h"
  23. #include "libavutil/crc.h"
  24. #include "libavutil/intreadwrite.h"
  25. #include "libavutil/log.h"
  26. #include "libavutil/dict.h"
  27. #include "libavutil/mathematics.h"
  28. #include "libavutil/opt.h"
  29. #include "libavutil/avassert.h"
  30. #include "libavcodec/bytestream.h"
  31. #include "libavcodec/get_bits.h"
  32. #include "libavcodec/mathops.h"
  33. #include "avformat.h"
  34. #include "mpegts.h"
  35. #include "internal.h"
  36. #include "avio_internal.h"
  37. #include "seek.h"
  38. #include "mpeg.h"
  39. #include "isom.h"
  40.  
  41. /* maximum size in which we look for synchronisation if
  42.    synchronisation is lost */
  43. #define MAX_RESYNC_SIZE 65536
  44.  
  45. #define MAX_PES_PAYLOAD 200*1024
  46.  
  47. #define MAX_MP4_DESCR_COUNT 16
  48.  
  49. enum MpegTSFilterType {
  50.     MPEGTS_PES,
  51.     MPEGTS_SECTION,
  52. };
  53.  
  54. typedef struct MpegTSFilter MpegTSFilter;
  55.  
  56. typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos, int64_t cur_pcr);
  57.  
  58. typedef struct MpegTSPESFilter {
  59.     PESCallback *pes_cb;
  60.     void *opaque;
  61. } MpegTSPESFilter;
  62.  
  63. typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
  64.  
  65. typedef void SetServiceCallback(void *opaque, int ret);
  66.  
  67. typedef struct MpegTSSectionFilter {
  68.     int section_index;
  69.     int section_h_size;
  70.     uint8_t *section_buf;
  71.     unsigned int check_crc:1;
  72.     unsigned int end_of_section_reached:1;
  73.     SectionCallback *section_cb;
  74.     void *opaque;
  75. } MpegTSSectionFilter;
  76.  
  77. struct MpegTSFilter {
  78.     int pid;
  79.     int es_id;
  80.     int last_cc; /* last cc code (-1 if first packet) */
  81.     enum MpegTSFilterType type;
  82.     union {
  83.         MpegTSPESFilter pes_filter;
  84.         MpegTSSectionFilter section_filter;
  85.     } u;
  86. };
  87.  
  88. #define MAX_PIDS_PER_PROGRAM 64
  89. struct Program {
  90.     unsigned int id; //program id/service id
  91.     unsigned int nb_pids;
  92.     unsigned int pids[MAX_PIDS_PER_PROGRAM];
  93. };
  94.  
  95. struct MpegTSContext {
  96.     const AVClass *class;
  97.     /* user data */
  98.     AVFormatContext *stream;
  99.     /** raw packet size, including FEC if present            */
  100.     int raw_packet_size;
  101.  
  102.     int size_stat[3];
  103.     int size_stat_count;
  104. #define SIZE_STAT_THRESHOLD 10
  105.  
  106.     int64_t pos47_full;
  107.  
  108.     /** if true, all pids are analyzed to find streams       */
  109.     int auto_guess;
  110.  
  111.     /** compute exact PCR for each transport stream packet   */
  112.     int mpeg2ts_compute_pcr;
  113.  
  114.     /** fix dvb teletext pts                                 */
  115.     int fix_teletext_pts;
  116.  
  117.     int64_t cur_pcr;    /**< used to estimate the exact PCR  */
  118.     int pcr_incr;       /**< used to estimate the exact PCR  */
  119.  
  120.     /* data needed to handle file based ts */
  121.     /** stop parsing loop                                    */
  122.     int stop_parse;
  123.     /** packet containing Audio/Video data                   */
  124.     AVPacket *pkt;
  125.     /** to detect seek                                       */
  126.     int64_t last_pos;
  127.  
  128.     /******************************************/
  129.     /* private mpegts data */
  130.     /* scan context */
  131.     /** structure to keep track of Program->pids mapping     */
  132.     unsigned int nb_prg;
  133.     struct Program *prg;
  134.  
  135.     int8_t crc_validity[NB_PID_MAX];
  136.  
  137.     /** filters for various streams specified by PMT + for the PAT and PMT */
  138.     MpegTSFilter *pids[NB_PID_MAX];
  139.     int current_pid;
  140. };
  141.  
  142. static const AVOption mpegtsraw_options[] = {
  143.     {"compute_pcr", "Compute exact PCR for each transport stream packet.", offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_INT,
  144.      {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
  145.     { NULL },
  146. };
  147.  
  148. static const AVClass mpegtsraw_class = {
  149.     .class_name = "mpegtsraw demuxer",
  150.     .item_name  = av_default_item_name,
  151.     .option     = mpegtsraw_options,
  152.     .version    = LIBAVUTIL_VERSION_INT,
  153. };
  154.  
  155. static const AVOption mpegts_options[] = {
  156.     {"fix_teletext_pts", "Try to fix pts values of dvb teletext streams.", offsetof(MpegTSContext, fix_teletext_pts), AV_OPT_TYPE_INT,
  157.      {.i64 = 1}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
  158.     { NULL },
  159. };
  160.  
  161. static const AVClass mpegts_class = {
  162.     .class_name = "mpegts demuxer",
  163.     .item_name  = av_default_item_name,
  164.     .option     = mpegts_options,
  165.     .version    = LIBAVUTIL_VERSION_INT,
  166. };
  167.  
  168. /* TS stream handling */
  169.  
  170. enum MpegTSState {
  171.     MPEGTS_HEADER = 0,
  172.     MPEGTS_PESHEADER,
  173.     MPEGTS_PESHEADER_FILL,
  174.     MPEGTS_PAYLOAD,
  175.     MPEGTS_SKIP,
  176. };
  177.  
  178. /* enough for PES header + length */
  179. #define PES_START_SIZE  6
  180. #define PES_HEADER_SIZE 9
  181. #define MAX_PES_HEADER_SIZE (9 + 255)
  182.  
  183. typedef struct PESContext {
  184.     int pid;
  185.     int pcr_pid; /**< if -1 then all packets containing PCR are considered */
  186.     int stream_type;
  187.     MpegTSContext *ts;
  188.     AVFormatContext *stream;
  189.     AVStream *st;
  190.     AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
  191.     enum MpegTSState state;
  192.     /* used to get the format */
  193.     int data_index;
  194.     int flags; /**< copied to the AVPacket flags */
  195.     int total_size;
  196.     int pes_header_size;
  197.     int extended_stream_id;
  198.     int64_t pts, dts;
  199.     int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
  200.     uint8_t header[MAX_PES_HEADER_SIZE];
  201.     AVBufferRef *buffer;
  202.     SLConfigDescr sl;
  203.     int64_t last_pcr;
  204. } PESContext;
  205.  
  206. extern AVInputFormat ff_mpegts_demuxer;
  207.  
  208. static void clear_avprogram(MpegTSContext *ts, unsigned int programid)
  209. {
  210.     AVProgram *prg = NULL;
  211.     int i;
  212.     for(i=0; i<ts->stream->nb_programs; i++)
  213.         if(ts->stream->programs[i]->id == programid){
  214.             prg = ts->stream->programs[i];
  215.             break;
  216.         }
  217.     if (!prg)
  218.         return;
  219.     prg->nb_stream_indexes = 0;
  220. }
  221.  
  222. static void clear_program(MpegTSContext *ts, unsigned int programid)
  223. {
  224.     int i;
  225.  
  226.     clear_avprogram(ts, programid);
  227.     for(i=0; i<ts->nb_prg; i++)
  228.         if(ts->prg[i].id == programid)
  229.             ts->prg[i].nb_pids = 0;
  230. }
  231.  
  232. static void clear_programs(MpegTSContext *ts)
  233. {
  234.     av_freep(&ts->prg);
  235.     ts->nb_prg=0;
  236. }
  237.  
  238. static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
  239. {
  240.     struct Program *p;
  241.     if (av_reallocp_array(&ts->prg, ts->nb_prg + 1, sizeof(*ts->prg)) < 0) {
  242.         ts->nb_prg = 0;
  243.         return;
  244.     }
  245.     p = &ts->prg[ts->nb_prg];
  246.     p->id = programid;
  247.     p->nb_pids = 0;
  248.     ts->nb_prg++;
  249. }
  250.  
  251. static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
  252. {
  253.     int i;
  254.     struct Program *p = NULL;
  255.     for(i=0; i<ts->nb_prg; i++) {
  256.         if(ts->prg[i].id == programid) {
  257.             p = &ts->prg[i];
  258.             break;
  259.         }
  260.     }
  261.     if(!p)
  262.         return;
  263.  
  264.     if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
  265.         return;
  266.     p->pids[p->nb_pids++] = pid;
  267. }
  268.  
  269. static void set_pcr_pid(AVFormatContext *s, unsigned int programid, unsigned int pid)
  270. {
  271.     int i;
  272.     for(i=0; i<s->nb_programs; i++) {
  273.         if(s->programs[i]->id == programid) {
  274.             s->programs[i]->pcr_pid = pid;
  275.             break;
  276.         }
  277.     }
  278. }
  279.  
  280. /**
  281.  * @brief discard_pid() decides if the pid is to be discarded according
  282.  *                      to caller's programs selection
  283.  * @param ts    : - TS context
  284.  * @param pid   : - pid
  285.  * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
  286.  *         0 otherwise
  287.  */
  288. static int discard_pid(MpegTSContext *ts, unsigned int pid)
  289. {
  290.     int i, j, k;
  291.     int used = 0, discarded = 0;
  292.     struct Program *p;
  293.  
  294.     /* If none of the programs have .discard=AVDISCARD_ALL then there's
  295.      * no way we have to discard this packet
  296.      */
  297.     for (k = 0; k < ts->stream->nb_programs; k++) {
  298.         if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
  299.             break;
  300.     }
  301.     if (k == ts->stream->nb_programs)
  302.         return 0;
  303.  
  304.     for(i=0; i<ts->nb_prg; i++) {
  305.         p = &ts->prg[i];
  306.         for(j=0; j<p->nb_pids; j++) {
  307.             if(p->pids[j] != pid)
  308.                 continue;
  309.             //is program with id p->id set to be discarded?
  310.             for(k=0; k<ts->stream->nb_programs; k++) {
  311.                 if(ts->stream->programs[k]->id == p->id) {
  312.                     if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
  313.                         discarded++;
  314.                     else
  315.                         used++;
  316.                 }
  317.             }
  318.         }
  319.     }
  320.  
  321.     return !used && discarded;
  322. }
  323.  
  324. /**
  325.  *  Assemble PES packets out of TS packets, and then call the "section_cb"
  326.  *  function when they are complete.
  327.  */
  328. static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
  329.                                const uint8_t *buf, int buf_size, int is_start)
  330. {
  331.     MpegTSContext *ts = s->priv_data;
  332.     MpegTSSectionFilter *tss = &tss1->u.section_filter;
  333.     int len;
  334.  
  335.     if (is_start) {
  336.         memcpy(tss->section_buf, buf, buf_size);
  337.         tss->section_index = buf_size;
  338.         tss->section_h_size = -1;
  339.         tss->end_of_section_reached = 0;
  340.     } else {
  341.         if (tss->end_of_section_reached)
  342.             return;
  343.         len = 4096 - tss->section_index;
  344.         if (buf_size < len)
  345.             len = buf_size;
  346.         memcpy(tss->section_buf + tss->section_index, buf, len);
  347.         tss->section_index += len;
  348.     }
  349.  
  350.     /* compute section length if possible */
  351.     if (tss->section_h_size == -1 && tss->section_index >= 3) {
  352.         len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
  353.         if (len > 4096)
  354.             return;
  355.         tss->section_h_size = len;
  356.     }
  357.  
  358.     if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
  359.         int crc_valid = 1;
  360.         tss->end_of_section_reached = 1;
  361.  
  362.         if (tss->check_crc){
  363.             crc_valid = !av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, tss->section_buf, tss->section_h_size);
  364.             if (crc_valid){
  365.                 ts->crc_validity[ tss1->pid ] = 100;
  366.             }else if(ts->crc_validity[ tss1->pid ] > -10){
  367.                 ts->crc_validity[ tss1->pid ]--;
  368.             }else
  369.                 crc_valid = 2;
  370.         }
  371.         if (crc_valid)
  372.             tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
  373.     }
  374. }
  375.  
  376. static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
  377.                                          SectionCallback *section_cb, void *opaque,
  378.                                          int check_crc)
  379.  
  380. {
  381.     MpegTSFilter *filter;
  382.     MpegTSSectionFilter *sec;
  383.  
  384.     av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
  385.  
  386.     if (pid >= NB_PID_MAX || ts->pids[pid])
  387.         return NULL;
  388.     filter = av_mallocz(sizeof(MpegTSFilter));
  389.     if (!filter)
  390.         return NULL;
  391.     ts->pids[pid] = filter;
  392.     filter->type = MPEGTS_SECTION;
  393.     filter->pid = pid;
  394.     filter->es_id = -1;
  395.     filter->last_cc = -1;
  396.     sec = &filter->u.section_filter;
  397.     sec->section_cb = section_cb;
  398.     sec->opaque = opaque;
  399.     sec->section_buf = av_malloc(MAX_SECTION_SIZE);
  400.     sec->check_crc = check_crc;
  401.     if (!sec->section_buf) {
  402.         av_free(filter);
  403.         return NULL;
  404.     }
  405.     return filter;
  406. }
  407.  
  408. static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
  409.                                      PESCallback *pes_cb,
  410.                                      void *opaque)
  411. {
  412.     MpegTSFilter *filter;
  413.     MpegTSPESFilter *pes;
  414.  
  415.     if (pid >= NB_PID_MAX || ts->pids[pid])
  416.         return NULL;
  417.     filter = av_mallocz(sizeof(MpegTSFilter));
  418.     if (!filter)
  419.         return NULL;
  420.     ts->pids[pid] = filter;
  421.     filter->type = MPEGTS_PES;
  422.     filter->pid = pid;
  423.     filter->es_id = -1;
  424.     filter->last_cc = -1;
  425.     pes = &filter->u.pes_filter;
  426.     pes->pes_cb = pes_cb;
  427.     pes->opaque = opaque;
  428.     return filter;
  429. }
  430.  
  431. static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
  432. {
  433.     int pid;
  434.  
  435.     pid = filter->pid;
  436.     if (filter->type == MPEGTS_SECTION)
  437.         av_freep(&filter->u.section_filter.section_buf);
  438.     else if (filter->type == MPEGTS_PES) {
  439.         PESContext *pes = filter->u.pes_filter.opaque;
  440.         av_buffer_unref(&pes->buffer);
  441.         /* referenced private data will be freed later in
  442.          * avformat_close_input */
  443.         if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
  444.             av_freep(&filter->u.pes_filter.opaque);
  445.         }
  446.     }
  447.  
  448.     av_free(filter);
  449.     ts->pids[pid] = NULL;
  450. }
  451.  
  452. static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
  453.     int stat[TS_MAX_PACKET_SIZE];
  454.     int i;
  455.     int x=0;
  456.     int best_score=0;
  457.  
  458.     memset(stat, 0, packet_size*sizeof(int));
  459.  
  460.     for(x=i=0; i<size-3; i++){
  461.         if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && buf[i+3] != 0x47){
  462.             stat[x]++;
  463.             if(stat[x] > best_score){
  464.                 best_score= stat[x];
  465.                 if(index) *index= x;
  466.             }
  467.         }
  468.  
  469.         x++;
  470.         if(x == packet_size) x= 0;
  471.     }
  472.  
  473.     return best_score;
  474. }
  475.  
  476. /* autodetect fec presence. Must have at least 1024 bytes  */
  477. static int get_packet_size(const uint8_t *buf, int size)
  478. {
  479.     int score, fec_score, dvhs_score;
  480.  
  481.     if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
  482.         return -1;
  483.  
  484.     score    = analyze(buf, size, TS_PACKET_SIZE, NULL);
  485.     dvhs_score    = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
  486.     fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
  487.     av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
  488.             score, dvhs_score, fec_score);
  489.  
  490.     if     (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
  491.     else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
  492.     else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
  493.     else                       return -1;
  494. }
  495.  
  496. typedef struct SectionHeader {
  497.     uint8_t tid;
  498.     uint16_t id;
  499.     uint8_t version;
  500.     uint8_t sec_num;
  501.     uint8_t last_sec_num;
  502. } SectionHeader;
  503.  
  504. static inline int get8(const uint8_t **pp, const uint8_t *p_end)
  505. {
  506.     const uint8_t *p;
  507.     int c;
  508.  
  509.     p = *pp;
  510.     if (p >= p_end)
  511.         return -1;
  512.     c = *p++;
  513.     *pp = p;
  514.     return c;
  515. }
  516.  
  517. static inline int get16(const uint8_t **pp, const uint8_t *p_end)
  518. {
  519.     const uint8_t *p;
  520.     int c;
  521.  
  522.     p = *pp;
  523.     if ((p + 1) >= p_end)
  524.         return -1;
  525.     c = AV_RB16(p);
  526.     p += 2;
  527.     *pp = p;
  528.     return c;
  529. }
  530.  
  531. /* read and allocate a DVB string preceded by its length */
  532. static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
  533. {
  534.     int len;
  535.     const uint8_t *p;
  536.     char *str;
  537.  
  538.     p = *pp;
  539.     len = get8(&p, p_end);
  540.     if (len < 0)
  541.         return NULL;
  542.     if ((p + len) > p_end)
  543.         return NULL;
  544.     str = av_malloc(len + 1);
  545.     if (!str)
  546.         return NULL;
  547.     memcpy(str, p, len);
  548.     str[len] = '\0';
  549.     p += len;
  550.     *pp = p;
  551.     return str;
  552. }
  553.  
  554. static int parse_section_header(SectionHeader *h,
  555.                                 const uint8_t **pp, const uint8_t *p_end)
  556. {
  557.     int val;
  558.  
  559.     val = get8(pp, p_end);
  560.     if (val < 0)
  561.         return -1;
  562.     h->tid = val;
  563.     *pp += 2;
  564.     val = get16(pp, p_end);
  565.     if (val < 0)
  566.         return -1;
  567.     h->id = val;
  568.     val = get8(pp, p_end);
  569.     if (val < 0)
  570.         return -1;
  571.     h->version = (val >> 1) & 0x1f;
  572.     val = get8(pp, p_end);
  573.     if (val < 0)
  574.         return -1;
  575.     h->sec_num = val;
  576.     val = get8(pp, p_end);
  577.     if (val < 0)
  578.         return -1;
  579.     h->last_sec_num = val;
  580.     return 0;
  581. }
  582.  
  583. typedef struct {
  584.     uint32_t stream_type;
  585.     enum AVMediaType codec_type;
  586.     enum AVCodecID codec_id;
  587. } StreamType;
  588.  
  589. static const StreamType ISO_types[] = {
  590.     { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
  591.     { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
  592.     { 0x03, AVMEDIA_TYPE_AUDIO,        AV_CODEC_ID_MP3 },
  593.     { 0x04, AVMEDIA_TYPE_AUDIO,        AV_CODEC_ID_MP3 },
  594.     { 0x0f, AVMEDIA_TYPE_AUDIO,        AV_CODEC_ID_AAC },
  595.     { 0x10, AVMEDIA_TYPE_VIDEO,      AV_CODEC_ID_MPEG4 },
  596.     /* Makito encoder sets stream type 0x11 for AAC,
  597.      * so auto-detect LOAS/LATM instead of hardcoding it. */
  598. #if !CONFIG_LOAS_DEMUXER
  599.     { 0x11, AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
  600. #endif
  601.     { 0x1b, AVMEDIA_TYPE_VIDEO,       AV_CODEC_ID_H264 },
  602.     { 0x24, AVMEDIA_TYPE_VIDEO,       AV_CODEC_ID_HEVC },
  603.     { 0x42, AVMEDIA_TYPE_VIDEO,       AV_CODEC_ID_CAVS },
  604.     { 0xd1, AVMEDIA_TYPE_VIDEO,      AV_CODEC_ID_DIRAC },
  605.     { 0xea, AVMEDIA_TYPE_VIDEO,        AV_CODEC_ID_VC1 },
  606.     { 0 },
  607. };
  608.  
  609. static const StreamType HDMV_types[] = {
  610.     { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
  611.     { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
  612.     { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  613.     { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
  614.     { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
  615.     { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
  616.     { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
  617.     { 0xa1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC3 Secondary Audio */
  618.     { 0xa2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },  /* DTS Express Secondary Audio */
  619.     { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
  620.     { 0 },
  621. };
  622.  
  623. /* ATSC ? */
  624. static const StreamType MISC_types[] = {
  625.     { 0x81, AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_AC3 },
  626.     { 0x8a, AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_DTS },
  627.     { 0 },
  628. };
  629.  
  630. static const StreamType REGD_types[] = {
  631.     { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
  632.     { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_AC3 },
  633.     { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
  634.     { MKTAG('D','T','S','1'), AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_DTS },
  635.     { MKTAG('D','T','S','2'), AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_DTS },
  636.     { MKTAG('D','T','S','3'), AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_DTS },
  637.     { MKTAG('H','E','V','C'), AVMEDIA_TYPE_VIDEO,  AV_CODEC_ID_HEVC },
  638.     { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA,    AV_CODEC_ID_SMPTE_KLV },
  639.     { MKTAG('V','C','-','1'), AVMEDIA_TYPE_VIDEO,   AV_CODEC_ID_VC1 },
  640.     { 0 },
  641. };
  642.  
  643. /* descriptor present */
  644. static const StreamType DESC_types[] = {
  645.     { 0x6a, AVMEDIA_TYPE_AUDIO,             AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
  646.     { 0x7a, AVMEDIA_TYPE_AUDIO,            AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
  647.     { 0x7b, AVMEDIA_TYPE_AUDIO,             AV_CODEC_ID_DTS },
  648.     { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
  649.     { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
  650.     { 0 },
  651. };
  652.  
  653. static void mpegts_find_stream_type(AVStream *st,
  654.                                     uint32_t stream_type, const StreamType *types)
  655. {
  656.     if (avcodec_is_open(st->codec)) {
  657.         av_log(NULL, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
  658.         return;
  659.     }
  660.  
  661.     for (; types->stream_type; types++) {
  662.         if (stream_type == types->stream_type) {
  663.             st->codec->codec_type = types->codec_type;
  664.             st->codec->codec_id   = types->codec_id;
  665.             st->request_probe     = 0;
  666.             return;
  667.         }
  668.     }
  669. }
  670.  
  671. static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
  672.                                   uint32_t stream_type, uint32_t prog_reg_desc)
  673. {
  674.     int old_codec_type= st->codec->codec_type;
  675.     int old_codec_id  = st->codec->codec_id;
  676.  
  677.     if (avcodec_is_open(st->codec)) {
  678.         av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
  679.         return 0;
  680.     }
  681.  
  682.     avpriv_set_pts_info(st, 33, 1, 90000);
  683.     st->priv_data = pes;
  684.     st->codec->codec_type = AVMEDIA_TYPE_DATA;
  685.     st->codec->codec_id   = AV_CODEC_ID_NONE;
  686.     st->need_parsing = AVSTREAM_PARSE_FULL;
  687.     pes->st = st;
  688.     pes->stream_type = stream_type;
  689.  
  690.     av_log(pes->stream, AV_LOG_DEBUG,
  691.            "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
  692.            st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
  693.  
  694.     st->codec->codec_tag = pes->stream_type;
  695.  
  696.     mpegts_find_stream_type(st, pes->stream_type, ISO_types);
  697.     if ((prog_reg_desc == AV_RL32("HDMV") ||
  698.          prog_reg_desc == AV_RL32("HDPR")) &&
  699.         st->codec->codec_id == AV_CODEC_ID_NONE) {
  700.         mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
  701.         if (pes->stream_type == 0x83) {
  702.             // HDMV TrueHD streams also contain an AC3 coded version of the
  703.             // audio track - add a second stream for this
  704.             AVStream *sub_st;
  705.             // priv_data cannot be shared between streams
  706.             PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
  707.             if (!sub_pes)
  708.                 return AVERROR(ENOMEM);
  709.             memcpy(sub_pes, pes, sizeof(*sub_pes));
  710.  
  711.             sub_st = avformat_new_stream(pes->stream, NULL);
  712.             if (!sub_st) {
  713.                 av_free(sub_pes);
  714.                 return AVERROR(ENOMEM);
  715.             }
  716.  
  717.             sub_st->id = pes->pid;
  718.             avpriv_set_pts_info(sub_st, 33, 1, 90000);
  719.             sub_st->priv_data = sub_pes;
  720.             sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  721.             sub_st->codec->codec_id   = AV_CODEC_ID_AC3;
  722.             sub_st->need_parsing = AVSTREAM_PARSE_FULL;
  723.             sub_pes->sub_st = pes->sub_st = sub_st;
  724.         }
  725.     }
  726.     if (st->codec->codec_id == AV_CODEC_ID_NONE)
  727.         mpegts_find_stream_type(st, pes->stream_type, MISC_types);
  728.     if (st->codec->codec_id == AV_CODEC_ID_NONE){
  729.         st->codec->codec_id  = old_codec_id;
  730.         st->codec->codec_type= old_codec_type;
  731.     }
  732.  
  733.     return 0;
  734. }
  735.  
  736. static void new_pes_packet(PESContext *pes, AVPacket *pkt)
  737. {
  738.     av_init_packet(pkt);
  739.  
  740.     pkt->buf  = pes->buffer;
  741.     pkt->data = pes->buffer->data;
  742.     pkt->size = pes->data_index;
  743.  
  744.     if(pes->total_size != MAX_PES_PAYLOAD &&
  745.        pes->pes_header_size + pes->data_index != pes->total_size + PES_START_SIZE) {
  746.         av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
  747.         pes->flags |= AV_PKT_FLAG_CORRUPT;
  748.     }
  749.     memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  750.  
  751.     // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
  752.     if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
  753.         pkt->stream_index = pes->sub_st->index;
  754.     else
  755.         pkt->stream_index = pes->st->index;
  756.     pkt->pts = pes->pts;
  757.     pkt->dts = pes->dts;
  758.     /* store position of first TS packet of this PES packet */
  759.     pkt->pos = pes->ts_packet_pos;
  760.     pkt->flags = pes->flags;
  761.  
  762.     /* reset pts values */
  763.     pes->pts = AV_NOPTS_VALUE;
  764.     pes->dts = AV_NOPTS_VALUE;
  765.     pes->buffer = NULL;
  766.     pes->data_index = 0;
  767.     pes->flags = 0;
  768. }
  769.  
  770. static uint64_t get_ts64(GetBitContext *gb, int bits)
  771. {
  772.     if (get_bits_left(gb) < bits)
  773.         return AV_NOPTS_VALUE;
  774.     return get_bits64(gb, bits);
  775. }
  776.  
  777. static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size)
  778. {
  779.     GetBitContext gb;
  780.     int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
  781.     int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
  782.     int dts_flag = -1, cts_flag = -1;
  783.     int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
  784.  
  785.     init_get_bits(&gb, buf, buf_size*8);
  786.  
  787.     if (sl->use_au_start)
  788.         au_start_flag = get_bits1(&gb);
  789.     if (sl->use_au_end)
  790.         au_end_flag = get_bits1(&gb);
  791.     if (!sl->use_au_start && !sl->use_au_end)
  792.         au_start_flag = au_end_flag = 1;
  793.     if (sl->ocr_len > 0)
  794.         ocr_flag = get_bits1(&gb);
  795.     if (sl->use_idle)
  796.         idle_flag = get_bits1(&gb);
  797.     if (sl->use_padding)
  798.         padding_flag = get_bits1(&gb);
  799.     if (padding_flag)
  800.         padding_bits = get_bits(&gb, 3);
  801.  
  802.     if (!idle_flag && (!padding_flag || padding_bits != 0)) {
  803.         if (sl->packet_seq_num_len)
  804.             skip_bits_long(&gb, sl->packet_seq_num_len);
  805.         if (sl->degr_prior_len)
  806.             if (get_bits1(&gb))
  807.                 skip_bits(&gb, sl->degr_prior_len);
  808.         if (ocr_flag)
  809.             skip_bits_long(&gb, sl->ocr_len);
  810.         if (au_start_flag) {
  811.             if (sl->use_rand_acc_pt)
  812.                 get_bits1(&gb);
  813.             if (sl->au_seq_num_len > 0)
  814.                 skip_bits_long(&gb, sl->au_seq_num_len);
  815.             if (sl->use_timestamps) {
  816.                 dts_flag = get_bits1(&gb);
  817.                 cts_flag = get_bits1(&gb);
  818.             }
  819.         }
  820.         if (sl->inst_bitrate_len)
  821.             inst_bitrate_flag = get_bits1(&gb);
  822.         if (dts_flag == 1)
  823.             dts = get_ts64(&gb, sl->timestamp_len);
  824.         if (cts_flag == 1)
  825.             cts = get_ts64(&gb, sl->timestamp_len);
  826.         if (sl->au_len > 0)
  827.             skip_bits_long(&gb, sl->au_len);
  828.         if (inst_bitrate_flag)
  829.             skip_bits_long(&gb, sl->inst_bitrate_len);
  830.     }
  831.  
  832.     if (dts != AV_NOPTS_VALUE)
  833.         pes->dts = dts;
  834.     if (cts != AV_NOPTS_VALUE)
  835.         pes->pts = cts;
  836.  
  837.     if (sl->timestamp_len && sl->timestamp_res)
  838.         avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
  839.  
  840.     return (get_bits_count(&gb) + 7) >> 3;
  841. }
  842.  
  843. /* return non zero if a packet could be constructed */
  844. static int mpegts_push_data(MpegTSFilter *filter,
  845.                             const uint8_t *buf, int buf_size, int is_start,
  846.                             int64_t pos, int64_t pcr)
  847. {
  848.     PESContext *pes = filter->u.pes_filter.opaque;
  849.     MpegTSContext *ts = pes->ts;
  850.     const uint8_t *p;
  851.     int len, code;
  852.  
  853.     if(!ts->pkt)
  854.         return 0;
  855.  
  856.     if (pcr != -1)
  857.         pes->last_pcr = pcr;
  858.  
  859.     if (is_start) {
  860.         if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  861.             new_pes_packet(pes, ts->pkt);
  862.             ts->stop_parse = 1;
  863.         }
  864.         pes->state = MPEGTS_HEADER;
  865.         pes->data_index = 0;
  866.         pes->ts_packet_pos = pos;
  867.     }
  868.     p = buf;
  869.     while (buf_size > 0) {
  870.         switch(pes->state) {
  871.         case MPEGTS_HEADER:
  872.             len = PES_START_SIZE - pes->data_index;
  873.             if (len > buf_size)
  874.                 len = buf_size;
  875.             memcpy(pes->header + pes->data_index, p, len);
  876.             pes->data_index += len;
  877.             p += len;
  878.             buf_size -= len;
  879.             if (pes->data_index == PES_START_SIZE) {
  880.                 /* we got all the PES or section header. We can now
  881.                    decide */
  882.                 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
  883.                     pes->header[2] == 0x01) {
  884.                     /* it must be an mpeg2 PES stream */
  885.                     code = pes->header[3] | 0x100;
  886.                     av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
  887.  
  888.                     if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
  889.                          (!pes->sub_st || pes->sub_st->discard == AVDISCARD_ALL)) ||
  890.                         code == 0x1be) /* padding_stream */
  891.                         goto skip;
  892.  
  893.                     /* stream not present in PMT */
  894.                     if (!pes->st) {
  895.                         pes->st = avformat_new_stream(ts->stream, NULL);
  896.                         if (!pes->st)
  897.                             return AVERROR(ENOMEM);
  898.                         pes->st->id = pes->pid;
  899.                         mpegts_set_stream_info(pes->st, pes, 0, 0);
  900.                     }
  901.  
  902.                     pes->total_size = AV_RB16(pes->header + 4);
  903.                     /* NOTE: a zero total size means the PES size is
  904.                        unbounded */
  905.                     if (!pes->total_size)
  906.                         pes->total_size = MAX_PES_PAYLOAD;
  907.  
  908.                     /* allocate pes buffer */
  909.                     pes->buffer = av_buffer_alloc(pes->total_size +
  910.                                                   FF_INPUT_BUFFER_PADDING_SIZE);
  911.                     if (!pes->buffer)
  912.                         return AVERROR(ENOMEM);
  913.  
  914.                     if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
  915.                         code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
  916.                         code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
  917.                         code != 0x1f8) {                  /* ITU-T Rec. H.222.1 type E stream */
  918.                         pes->state = MPEGTS_PESHEADER;
  919.                         if (pes->st->codec->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) {
  920.                             av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
  921.                                     pes->pid, pes->stream_type);
  922.                             pes->st->request_probe= 1;
  923.                         }
  924.                     } else {
  925.                         pes->state = MPEGTS_PAYLOAD;
  926.                         pes->data_index = 0;
  927.                     }
  928.                 } else {
  929.                     /* otherwise, it should be a table */
  930.                     /* skip packet */
  931.                 skip:
  932.                     pes->state = MPEGTS_SKIP;
  933.                     continue;
  934.                 }
  935.             }
  936.             break;
  937.             /**********************************************/
  938.             /* PES packing parsing */
  939.         case MPEGTS_PESHEADER:
  940.             len = PES_HEADER_SIZE - pes->data_index;
  941.             if (len < 0)
  942.                 return -1;
  943.             if (len > buf_size)
  944.                 len = buf_size;
  945.             memcpy(pes->header + pes->data_index, p, len);
  946.             pes->data_index += len;
  947.             p += len;
  948.             buf_size -= len;
  949.             if (pes->data_index == PES_HEADER_SIZE) {
  950.                 pes->pes_header_size = pes->header[8] + 9;
  951.                 pes->state = MPEGTS_PESHEADER_FILL;
  952.             }
  953.             break;
  954.         case MPEGTS_PESHEADER_FILL:
  955.             len = pes->pes_header_size - pes->data_index;
  956.             if (len < 0)
  957.                 return -1;
  958.             if (len > buf_size)
  959.                 len = buf_size;
  960.             memcpy(pes->header + pes->data_index, p, len);
  961.             pes->data_index += len;
  962.             p += len;
  963.             buf_size -= len;
  964.             if (pes->data_index == pes->pes_header_size) {
  965.                 const uint8_t *r;
  966.                 unsigned int flags, pes_ext, skip;
  967.  
  968.                 flags = pes->header[7];
  969.                 r = pes->header + 9;
  970.                 pes->pts = AV_NOPTS_VALUE;
  971.                 pes->dts = AV_NOPTS_VALUE;
  972.                 if ((flags & 0xc0) == 0x80) {
  973.                     pes->dts = pes->pts = ff_parse_pes_pts(r);
  974.                     r += 5;
  975.                 } else if ((flags & 0xc0) == 0xc0) {
  976.                     pes->pts = ff_parse_pes_pts(r);
  977.                     r += 5;
  978.                     pes->dts = ff_parse_pes_pts(r);
  979.                     r += 5;
  980.                 }
  981.                 pes->extended_stream_id = -1;
  982.                 if (flags & 0x01) { /* PES extension */
  983.                     pes_ext = *r++;
  984.                     /* Skip PES private data, program packet sequence counter and P-STD buffer */
  985.                     skip = (pes_ext >> 4) & 0xb;
  986.                     skip += skip & 0x9;
  987.                     r += skip;
  988.                     if ((pes_ext & 0x41) == 0x01 &&
  989.                         (r + 2) <= (pes->header + pes->pes_header_size)) {
  990.                         /* PES extension 2 */
  991.                         if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
  992.                             pes->extended_stream_id = r[1];
  993.                     }
  994.                 }
  995.  
  996.                 /* we got the full header. We parse it and get the payload */
  997.                 pes->state = MPEGTS_PAYLOAD;
  998.                 pes->data_index = 0;
  999.                 if (pes->stream_type == 0x12 && buf_size > 0) {
  1000.                     int sl_header_bytes = read_sl_header(pes, &pes->sl, p, buf_size);
  1001.                     pes->pes_header_size += sl_header_bytes;
  1002.                     p += sl_header_bytes;
  1003.                     buf_size -= sl_header_bytes;
  1004.                 }
  1005.                 if (pes->ts->fix_teletext_pts && pes->st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
  1006.                     AVProgram *p = NULL;
  1007.                     while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
  1008.                         if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
  1009.                             MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
  1010.                             if (f && f->type == MPEGTS_PES) {
  1011.                                 PESContext *pcrpes = f->u.pes_filter.opaque;
  1012.                                 if (pcrpes && pcrpes->last_pcr != -1 && pcrpes->st && pcrpes->st->discard != AVDISCARD_ALL) {
  1013.                                     // teletext packets do not always have correct timestamps,
  1014.                                     // the standard says they should be handled after 40.6 ms at most,
  1015.                                     // and the pcr error to this packet should be no more than 100 ms.
  1016.                                     // TODO: we should interpolate the PCR, not just use the last one
  1017.                                     int64_t pcr = pcrpes->last_pcr / 300;
  1018.                                     pes->st->pts_wrap_reference = pcrpes->st->pts_wrap_reference;
  1019.                                     pes->st->pts_wrap_behavior = pcrpes->st->pts_wrap_behavior;
  1020.                                     if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
  1021.                                         pes->pts = pes->dts = pcr;
  1022.                                     } else if (pes->dts > pcr + 3654 + 9000) {
  1023.                                         pes->pts = pes->dts = pcr + 3654 + 9000;
  1024.                                     }
  1025.                                     break;
  1026.                                 }
  1027.                             }
  1028.                         }
  1029.                     }
  1030.                 }
  1031.             }
  1032.             break;
  1033.         case MPEGTS_PAYLOAD:
  1034.             if (buf_size > 0 && pes->buffer) {
  1035.                 if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
  1036.                     new_pes_packet(pes, ts->pkt);
  1037.                     pes->total_size = MAX_PES_PAYLOAD;
  1038.                     pes->buffer = av_buffer_alloc(pes->total_size + FF_INPUT_BUFFER_PADDING_SIZE);
  1039.                     if (!pes->buffer)
  1040.                         return AVERROR(ENOMEM);
  1041.                     ts->stop_parse = 1;
  1042.                 } else if (pes->data_index == 0 && buf_size > pes->total_size) {
  1043.                     // pes packet size is < ts size packet and pes data is padded with 0xff
  1044.                     // not sure if this is legal in ts but see issue #2392
  1045.                     buf_size = pes->total_size;
  1046.                 }
  1047.                 memcpy(pes->buffer->data + pes->data_index, p, buf_size);
  1048.                 pes->data_index += buf_size;
  1049.             }
  1050.             buf_size = 0;
  1051.             /* emit complete packets with known packet size
  1052.              * decreases demuxer delay for infrequent packets like subtitles from
  1053.              * a couple of seconds to milliseconds for properly muxed files.
  1054.              * total_size is the number of bytes following pes_packet_length
  1055.              * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
  1056.             if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
  1057.                 pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
  1058.                 ts->stop_parse = 1;
  1059.                 new_pes_packet(pes, ts->pkt);
  1060.             }
  1061.             break;
  1062.         case MPEGTS_SKIP:
  1063.             buf_size = 0;
  1064.             break;
  1065.         }
  1066.     }
  1067.  
  1068.     return 0;
  1069. }
  1070.  
  1071. static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
  1072. {
  1073.     MpegTSFilter *tss;
  1074.     PESContext *pes;
  1075.  
  1076.     /* if no pid found, then add a pid context */
  1077.     pes = av_mallocz(sizeof(PESContext));
  1078.     if (!pes)
  1079.         return 0;
  1080.     pes->ts = ts;
  1081.     pes->stream = ts->stream;
  1082.     pes->pid = pid;
  1083.     pes->pcr_pid = pcr_pid;
  1084.     pes->state = MPEGTS_SKIP;
  1085.     pes->pts = AV_NOPTS_VALUE;
  1086.     pes->dts = AV_NOPTS_VALUE;
  1087.     pes->last_pcr = -1;
  1088.     tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
  1089.     if (!tss) {
  1090.         av_free(pes);
  1091.         return 0;
  1092.     }
  1093.     return pes;
  1094. }
  1095.  
  1096. #define MAX_LEVEL 4
  1097. typedef struct {
  1098.     AVFormatContext *s;
  1099.     AVIOContext pb;
  1100.     Mp4Descr *descr;
  1101.     Mp4Descr *active_descr;
  1102.     int descr_count;
  1103.     int max_descr_count;
  1104.     int level;
  1105. } MP4DescrParseContext;
  1106.  
  1107. static int init_MP4DescrParseContext(
  1108.     MP4DescrParseContext *d, AVFormatContext *s, const uint8_t *buf,
  1109.     unsigned size, Mp4Descr *descr, int max_descr_count)
  1110. {
  1111.     int ret;
  1112.     if (size > (1<<30))
  1113.         return AVERROR_INVALIDDATA;
  1114.  
  1115.     if ((ret = ffio_init_context(&d->pb, (unsigned char*)buf, size, 0,
  1116.                           NULL, NULL, NULL, NULL)) < 0)
  1117.         return ret;
  1118.  
  1119.     d->s = s;
  1120.     d->level = 0;
  1121.     d->descr_count = 0;
  1122.     d->descr = descr;
  1123.     d->active_descr = NULL;
  1124.     d->max_descr_count = max_descr_count;
  1125.  
  1126.     return 0;
  1127. }
  1128.  
  1129. static void update_offsets(AVIOContext *pb, int64_t *off, int *len) {
  1130.     int64_t new_off = avio_tell(pb);
  1131.     (*len) -= new_off - *off;
  1132.     *off = new_off;
  1133. }
  1134.  
  1135. static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
  1136.                            int target_tag);
  1137.  
  1138. static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
  1139. {
  1140.     while (len > 0) {
  1141.         if (parse_mp4_descr(d, off, len, 0) < 0)
  1142.             return -1;
  1143.         update_offsets(&d->pb, &off, &len);
  1144.     }
  1145.     return 0;
  1146. }
  1147.  
  1148. static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1149. {
  1150.     avio_rb16(&d->pb); // ID
  1151.     avio_r8(&d->pb);
  1152.     avio_r8(&d->pb);
  1153.     avio_r8(&d->pb);
  1154.     avio_r8(&d->pb);
  1155.     avio_r8(&d->pb);
  1156.     update_offsets(&d->pb, &off, &len);
  1157.     return parse_mp4_descr_arr(d, off, len);
  1158. }
  1159.  
  1160. static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1161. {
  1162.     int id_flags;
  1163.     if (len < 2)
  1164.         return 0;
  1165.     id_flags = avio_rb16(&d->pb);
  1166.     if (!(id_flags & 0x0020)) { //URL_Flag
  1167.         update_offsets(&d->pb, &off, &len);
  1168.         return parse_mp4_descr_arr(d, off, len); //ES_Descriptor[]
  1169.     } else {
  1170.         return 0;
  1171.     }
  1172. }
  1173.  
  1174. static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1175. {
  1176.     int es_id = 0;
  1177.     if (d->descr_count >= d->max_descr_count)
  1178.         return -1;
  1179.     ff_mp4_parse_es_descr(&d->pb, &es_id);
  1180.     d->active_descr = d->descr + (d->descr_count++);
  1181.  
  1182.     d->active_descr->es_id = es_id;
  1183.     update_offsets(&d->pb, &off, &len);
  1184.     parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
  1185.     update_offsets(&d->pb, &off, &len);
  1186.     if (len > 0)
  1187.         parse_mp4_descr(d, off, len, MP4SLDescrTag);
  1188.     d->active_descr = NULL;
  1189.     return 0;
  1190. }
  1191.  
  1192. static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1193. {
  1194.     Mp4Descr *descr = d->active_descr;
  1195.     if (!descr)
  1196.         return -1;
  1197.     d->active_descr->dec_config_descr = av_malloc(len);
  1198.     if (!descr->dec_config_descr)
  1199.         return AVERROR(ENOMEM);
  1200.     descr->dec_config_descr_len = len;
  1201.     avio_read(&d->pb, descr->dec_config_descr, len);
  1202.     return 0;
  1203. }
  1204.  
  1205. static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1206. {
  1207.     Mp4Descr *descr = d->active_descr;
  1208.     int predefined;
  1209.     if (!descr)
  1210.         return -1;
  1211.  
  1212.     predefined = avio_r8(&d->pb);
  1213.     if (!predefined) {
  1214.         int lengths;
  1215.         int flags = avio_r8(&d->pb);
  1216.         descr->sl.use_au_start       = !!(flags & 0x80);
  1217.         descr->sl.use_au_end         = !!(flags & 0x40);
  1218.         descr->sl.use_rand_acc_pt    = !!(flags & 0x20);
  1219.         descr->sl.use_padding        = !!(flags & 0x08);
  1220.         descr->sl.use_timestamps     = !!(flags & 0x04);
  1221.         descr->sl.use_idle           = !!(flags & 0x02);
  1222.         descr->sl.timestamp_res      = avio_rb32(&d->pb);
  1223.                                        avio_rb32(&d->pb);
  1224.         descr->sl.timestamp_len      = avio_r8(&d->pb);
  1225.         descr->sl.ocr_len            = avio_r8(&d->pb);
  1226.         descr->sl.au_len             = avio_r8(&d->pb);
  1227.         descr->sl.inst_bitrate_len   = avio_r8(&d->pb);
  1228.         lengths                      = avio_rb16(&d->pb);
  1229.         descr->sl.degr_prior_len     = lengths >> 12;
  1230.         descr->sl.au_seq_num_len     = (lengths >> 7) & 0x1f;
  1231.         descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
  1232.     } else {
  1233.         avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
  1234.     }
  1235.     return 0;
  1236. }
  1237.  
  1238. static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
  1239.                            int target_tag) {
  1240.     int tag;
  1241.     int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
  1242.     update_offsets(&d->pb, &off, &len);
  1243.     if (len < 0 || len1 > len || len1 <= 0) {
  1244.         av_log(d->s, AV_LOG_ERROR, "Tag %x length violation new length %d bytes remaining %d\n", tag, len1, len);
  1245.         return -1;
  1246.     }
  1247.  
  1248.     if (d->level++ >= MAX_LEVEL) {
  1249.         av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
  1250.         goto done;
  1251.     }
  1252.  
  1253.     if (target_tag && tag != target_tag) {
  1254.         av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag, target_tag);
  1255.         goto done;
  1256.     }
  1257.  
  1258.     switch (tag) {
  1259.     case MP4IODescrTag:
  1260.         parse_MP4IODescrTag(d, off, len1);
  1261.         break;
  1262.     case MP4ODescrTag:
  1263.         parse_MP4ODescrTag(d, off, len1);
  1264.         break;
  1265.     case MP4ESDescrTag:
  1266.         parse_MP4ESDescrTag(d, off, len1);
  1267.         break;
  1268.     case MP4DecConfigDescrTag:
  1269.         parse_MP4DecConfigDescrTag(d, off, len1);
  1270.         break;
  1271.     case MP4SLDescrTag:
  1272.         parse_MP4SLDescrTag(d, off, len1);
  1273.         break;
  1274.     }
  1275.  
  1276. done:
  1277.     d->level--;
  1278.     avio_seek(&d->pb, off + len1, SEEK_SET);
  1279.     return 0;
  1280. }
  1281.  
  1282. static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
  1283.                          Mp4Descr *descr, int *descr_count, int max_descr_count)
  1284. {
  1285.     MP4DescrParseContext d;
  1286.     if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
  1287.         return -1;
  1288.  
  1289.     parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
  1290.  
  1291.     *descr_count = d.descr_count;
  1292.     return 0;
  1293. }
  1294.  
  1295. static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
  1296.                        Mp4Descr *descr, int *descr_count, int max_descr_count)
  1297. {
  1298.     MP4DescrParseContext d;
  1299.     if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
  1300.         return -1;
  1301.  
  1302.     parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
  1303.  
  1304.     *descr_count = d.descr_count;
  1305.     return 0;
  1306. }
  1307.  
  1308. static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1309. {
  1310.     MpegTSContext *ts = filter->u.section_filter.opaque;
  1311.     SectionHeader h;
  1312.     const uint8_t *p, *p_end;
  1313.     AVIOContext pb;
  1314.     Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
  1315.     int mp4_descr_count = 0;
  1316.     int i, pid;
  1317.     AVFormatContext *s = ts->stream;
  1318.  
  1319.     p_end = section + section_len - 4;
  1320.     p = section;
  1321.     if (parse_section_header(&h, &p, p_end) < 0)
  1322.         return;
  1323.     if (h.tid != M4OD_TID)
  1324.         return;
  1325.  
  1326.     mp4_read_od(s, p, (unsigned)(p_end - p), mp4_descr, &mp4_descr_count, MAX_MP4_DESCR_COUNT);
  1327.  
  1328.     for (pid = 0; pid < NB_PID_MAX; pid++) {
  1329.         if (!ts->pids[pid])
  1330.              continue;
  1331.         for (i = 0; i < mp4_descr_count; i++) {
  1332.             PESContext *pes;
  1333.             AVStream *st;
  1334.             if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
  1335.                 continue;
  1336.             if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
  1337.                 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
  1338.                 continue;
  1339.             }
  1340.             pes = ts->pids[pid]->u.pes_filter.opaque;
  1341.             st = pes->st;
  1342.             if (!st) {
  1343.                 continue;
  1344.             }
  1345.  
  1346.             pes->sl = mp4_descr[i].sl;
  1347.  
  1348.             ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
  1349.                               mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
  1350.             ff_mp4_read_dec_config_descr(s, st, &pb);
  1351.             if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1352.                 st->codec->extradata_size > 0)
  1353.                 st->need_parsing = 0;
  1354.             if (st->codec->codec_id == AV_CODEC_ID_H264 &&
  1355.                 st->codec->extradata_size > 0)
  1356.                 st->need_parsing = 0;
  1357.  
  1358.             if (st->codec->codec_id <= AV_CODEC_ID_NONE) {
  1359.             } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO) {
  1360.                 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1361.             } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE) {
  1362.                 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1363.             } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN) {
  1364.                 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1365.             }
  1366.         }
  1367.     }
  1368.     for (i = 0; i < mp4_descr_count; i++)
  1369.         av_free(mp4_descr[i].dec_config_descr);
  1370. }
  1371.  
  1372. int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
  1373.                               const uint8_t **pp, const uint8_t *desc_list_end,
  1374.                               Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
  1375.                               MpegTSContext *ts)
  1376. {
  1377.     const uint8_t *desc_end;
  1378.     int desc_len, desc_tag, desc_es_id;
  1379.     char language[252];
  1380.     int i;
  1381.  
  1382.     desc_tag = get8(pp, desc_list_end);
  1383.     if (desc_tag < 0)
  1384.         return -1;
  1385.     desc_len = get8(pp, desc_list_end);
  1386.     if (desc_len < 0)
  1387.         return -1;
  1388.     desc_end = *pp + desc_len;
  1389.     if (desc_end > desc_list_end)
  1390.         return -1;
  1391.  
  1392.     av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
  1393.  
  1394.     if (st->codec->codec_id == AV_CODEC_ID_NONE &&
  1395.         stream_type == STREAM_TYPE_PRIVATE_DATA)
  1396.         mpegts_find_stream_type(st, desc_tag, DESC_types);
  1397.  
  1398.     switch(desc_tag) {
  1399.     case 0x1E: /* SL descriptor */
  1400.         desc_es_id = get16(pp, desc_end);
  1401.         if (ts && ts->pids[pid])
  1402.             ts->pids[pid]->es_id = desc_es_id;
  1403.         for (i = 0; i < mp4_descr_count; i++)
  1404.         if (mp4_descr[i].dec_config_descr_len &&
  1405.             mp4_descr[i].es_id == desc_es_id) {
  1406.             AVIOContext pb;
  1407.             ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
  1408.                           mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
  1409.             ff_mp4_read_dec_config_descr(fc, st, &pb);
  1410.             if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1411.                 st->codec->extradata_size > 0)
  1412.                 st->need_parsing = 0;
  1413.             if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
  1414.                 mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
  1415.         }
  1416.         break;
  1417.     case 0x1F: /* FMC descriptor */
  1418.         get16(pp, desc_end);
  1419.         if (mp4_descr_count > 0 && (st->codec->codec_id == AV_CODEC_ID_AAC_LATM || st->request_probe>0) &&
  1420.             mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
  1421.             AVIOContext pb;
  1422.             ffio_init_context(&pb, mp4_descr->dec_config_descr,
  1423.                           mp4_descr->dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
  1424.             ff_mp4_read_dec_config_descr(fc, st, &pb);
  1425.             if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1426.                 st->codec->extradata_size > 0){
  1427.                 st->request_probe= st->need_parsing = 0;
  1428.                 st->codec->codec_type= AVMEDIA_TYPE_AUDIO;
  1429.             }
  1430.         }
  1431.         break;
  1432.     case 0x56: /* DVB teletext descriptor */
  1433.         language[0] = get8(pp, desc_end);
  1434.         language[1] = get8(pp, desc_end);
  1435.         language[2] = get8(pp, desc_end);
  1436.         language[3] = 0;
  1437.         av_dict_set(&st->metadata, "language", language, 0);
  1438.         break;
  1439.     case 0x59: /* subtitling descriptor */
  1440.         language[0] = get8(pp, desc_end);
  1441.         language[1] = get8(pp, desc_end);
  1442.         language[2] = get8(pp, desc_end);
  1443.         language[3] = 0;
  1444.         /* hearing impaired subtitles detection */
  1445.         switch(get8(pp, desc_end)) {
  1446.         case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
  1447.         case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
  1448.         case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
  1449.         case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
  1450.         case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
  1451.         case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
  1452.             st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1453.             break;
  1454.         }
  1455.         if (st->codec->extradata) {
  1456.             if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
  1457.                 avpriv_request_sample(fc, "DVB sub with multiple IDs");
  1458.         } else {
  1459.             if (!ff_alloc_extradata(st->codec, 4)) {
  1460.                 memcpy(st->codec->extradata, *pp, 4);
  1461.             }
  1462.         }
  1463.         *pp += 4;
  1464.         av_dict_set(&st->metadata, "language", language, 0);
  1465.         break;
  1466.     case 0x0a: /* ISO 639 language descriptor */
  1467.         for (i = 0; i + 4 <= desc_len; i += 4) {
  1468.             language[i + 0] = get8(pp, desc_end);
  1469.             language[i + 1] = get8(pp, desc_end);
  1470.             language[i + 2] = get8(pp, desc_end);
  1471.             language[i + 3] = ',';
  1472.         switch (get8(pp, desc_end)) {
  1473.             case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
  1474.             case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
  1475.             case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
  1476.         }
  1477.         }
  1478.         if (i) {
  1479.             language[i - 1] = 0;
  1480.             av_dict_set(&st->metadata, "language", language, 0);
  1481.         }
  1482.         break;
  1483.     case 0x05: /* registration descriptor */
  1484.         st->codec->codec_tag = bytestream_get_le32(pp);
  1485.         av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
  1486.         if (st->codec->codec_id == AV_CODEC_ID_NONE)
  1487.             mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
  1488.         break;
  1489.     case 0x52: /* stream identifier descriptor */
  1490.         st->stream_identifier = 1 + get8(pp, desc_end);
  1491.         break;
  1492.     default:
  1493.         break;
  1494.     }
  1495.     *pp = desc_end;
  1496.     return 0;
  1497. }
  1498.  
  1499. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1500. {
  1501.     MpegTSContext *ts = filter->u.section_filter.opaque;
  1502.     SectionHeader h1, *h = &h1;
  1503.     PESContext *pes;
  1504.     AVStream *st;
  1505.     const uint8_t *p, *p_end, *desc_list_end;
  1506.     int program_info_length, pcr_pid, pid, stream_type;
  1507.     int desc_list_len;
  1508.     uint32_t prog_reg_desc = 0; /* registration descriptor */
  1509.  
  1510.     Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
  1511.     int mp4_descr_count = 0;
  1512.     int i;
  1513.  
  1514.     av_dlog(ts->stream, "PMT: len %i\n", section_len);
  1515.     hex_dump_debug(ts->stream, section, section_len);
  1516.  
  1517.     p_end = section + section_len - 4;
  1518.     p = section;
  1519.     if (parse_section_header(h, &p, p_end) < 0)
  1520.         return;
  1521.  
  1522.     av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
  1523.            h->id, h->sec_num, h->last_sec_num);
  1524.  
  1525.     if (h->tid != PMT_TID)
  1526.         return;
  1527.  
  1528.     clear_program(ts, h->id);
  1529.     pcr_pid = get16(&p, p_end);
  1530.     if (pcr_pid < 0)
  1531.         return;
  1532.     pcr_pid &= 0x1fff;
  1533.     add_pid_to_pmt(ts, h->id, pcr_pid);
  1534.     set_pcr_pid(ts->stream, h->id, pcr_pid);
  1535.  
  1536.     av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
  1537.  
  1538.     program_info_length = get16(&p, p_end);
  1539.     if (program_info_length < 0)
  1540.         return;
  1541.     program_info_length &= 0xfff;
  1542.     while(program_info_length >= 2) {
  1543.         uint8_t tag, len;
  1544.         tag = get8(&p, p_end);
  1545.         len = get8(&p, p_end);
  1546.  
  1547.         av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
  1548.  
  1549.         if(len > program_info_length - 2)
  1550.             //something else is broken, exit the program_descriptors_loop
  1551.             break;
  1552.         program_info_length -= len + 2;
  1553.         if (tag == 0x1d) { // IOD descriptor
  1554.             get8(&p, p_end); // scope
  1555.             get8(&p, p_end); // label
  1556.             len -= 2;
  1557.             mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
  1558.                           &mp4_descr_count, MAX_MP4_DESCR_COUNT);
  1559.         } else if (tag == 0x05 && len >= 4) { // registration descriptor
  1560.             prog_reg_desc = bytestream_get_le32(&p);
  1561.             len -= 4;
  1562.         }
  1563.         p += len;
  1564.     }
  1565.     p += program_info_length;
  1566.     if (p >= p_end)
  1567.         goto out;
  1568.  
  1569.     // stop parsing after pmt, we found header
  1570.     if (!ts->stream->nb_streams)
  1571.         ts->stop_parse = 2;
  1572.  
  1573.     for(;;) {
  1574.         st = 0;
  1575.         pes = NULL;
  1576.         stream_type = get8(&p, p_end);
  1577.         if (stream_type < 0)
  1578.             break;
  1579.         pid = get16(&p, p_end);
  1580.         if (pid < 0)
  1581.             break;
  1582.         pid &= 0x1fff;
  1583.         if (pid == ts->current_pid)
  1584.             break;
  1585.  
  1586.         /* now create stream */
  1587.         if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  1588.             pes = ts->pids[pid]->u.pes_filter.opaque;
  1589.             if (!pes->st) {
  1590.                 pes->st = avformat_new_stream(pes->stream, NULL);
  1591.                 if (!pes->st)
  1592.                     goto out;
  1593.                 pes->st->id = pes->pid;
  1594.             }
  1595.             st = pes->st;
  1596.         } else if (stream_type != 0x13) {
  1597.             if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
  1598.             pes = add_pes_stream(ts, pid, pcr_pid);
  1599.             if (pes) {
  1600.                 st = avformat_new_stream(pes->stream, NULL);
  1601.                 if (!st)
  1602.                     goto out;
  1603.                 st->id = pes->pid;
  1604.             }
  1605.         } else {
  1606.             int idx = ff_find_stream_index(ts->stream, pid);
  1607.             if (idx >= 0) {
  1608.                 st = ts->stream->streams[idx];
  1609.             } else {
  1610.                 st = avformat_new_stream(ts->stream, NULL);
  1611.                 if (!st)
  1612.                     goto out;
  1613.                 st->id = pid;
  1614.                 st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1615.             }
  1616.         }
  1617.  
  1618.         if (!st)
  1619.             goto out;
  1620.  
  1621.         if (pes && !pes->stream_type)
  1622.             mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
  1623.  
  1624.         add_pid_to_pmt(ts, h->id, pid);
  1625.  
  1626.         ff_program_add_stream_index(ts->stream, h->id, st->index);
  1627.  
  1628.         desc_list_len = get16(&p, p_end);
  1629.         if (desc_list_len < 0)
  1630.             break;
  1631.         desc_list_len &= 0xfff;
  1632.         desc_list_end = p + desc_list_len;
  1633.         if (desc_list_end > p_end)
  1634.             break;
  1635.         for(;;) {
  1636.             if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
  1637.                 mp4_descr, mp4_descr_count, pid, ts) < 0)
  1638.                 break;
  1639.  
  1640.             if (pes && prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
  1641.                 ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
  1642.                 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
  1643.             }
  1644.         }
  1645.         p = desc_list_end;
  1646.     }
  1647.  
  1648.  out:
  1649.     for (i = 0; i < mp4_descr_count; i++)
  1650.         av_free(mp4_descr[i].dec_config_descr);
  1651. }
  1652.  
  1653. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1654. {
  1655.     MpegTSContext *ts = filter->u.section_filter.opaque;
  1656.     SectionHeader h1, *h = &h1;
  1657.     const uint8_t *p, *p_end;
  1658.     int sid, pmt_pid;
  1659.     AVProgram *program;
  1660.  
  1661.     av_dlog(ts->stream, "PAT:\n");
  1662.     hex_dump_debug(ts->stream, section, section_len);
  1663.  
  1664.     p_end = section + section_len - 4;
  1665.     p = section;
  1666.     if (parse_section_header(h, &p, p_end) < 0)
  1667.         return;
  1668.     if (h->tid != PAT_TID)
  1669.         return;
  1670.  
  1671.     ts->stream->ts_id = h->id;
  1672.  
  1673.     clear_programs(ts);
  1674.     for(;;) {
  1675.         sid = get16(&p, p_end);
  1676.         if (sid < 0)
  1677.             break;
  1678.         pmt_pid = get16(&p, p_end);
  1679.         if (pmt_pid < 0)
  1680.             break;
  1681.         pmt_pid &= 0x1fff;
  1682.  
  1683.         if (pmt_pid == ts->current_pid)
  1684.             break;
  1685.  
  1686.         av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  1687.  
  1688.         if (sid == 0x0000) {
  1689.             /* NIT info */
  1690.         } else {
  1691.             MpegTSFilter *fil = ts->pids[pmt_pid];
  1692.             program = av_new_program(ts->stream, sid);
  1693.             program->program_num = sid;
  1694.             program->pmt_pid = pmt_pid;
  1695.             if (fil)
  1696.                 if (   fil->type != MPEGTS_SECTION
  1697.                     || fil->pid != pmt_pid
  1698.                     || fil->u.section_filter.section_cb != pmt_cb)
  1699.                     mpegts_close_filter(ts, ts->pids[pmt_pid]);
  1700.  
  1701.             if (!ts->pids[pmt_pid])
  1702.                 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  1703.             add_pat_entry(ts, sid);
  1704.             add_pid_to_pmt(ts, sid, 0); //add pat pid to program
  1705.             add_pid_to_pmt(ts, sid, pmt_pid);
  1706.         }
  1707.     }
  1708.  
  1709.     if (sid < 0) {
  1710.         int i,j;
  1711.         for (j=0; j<ts->stream->nb_programs; j++) {
  1712.             for (i=0; i<ts->nb_prg; i++)
  1713.                 if (ts->prg[i].id == ts->stream->programs[j]->id)
  1714.                     break;
  1715.             if (i==ts->nb_prg)
  1716.                 clear_avprogram(ts, ts->stream->programs[j]->id);
  1717.         }
  1718.     }
  1719. }
  1720.  
  1721. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1722. {
  1723.     MpegTSContext *ts = filter->u.section_filter.opaque;
  1724.     SectionHeader h1, *h = &h1;
  1725.     const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  1726.     int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  1727.     char *name, *provider_name;
  1728.  
  1729.     av_dlog(ts->stream, "SDT:\n");
  1730.     hex_dump_debug(ts->stream, section, section_len);
  1731.  
  1732.     p_end = section + section_len - 4;
  1733.     p = section;
  1734.     if (parse_section_header(h, &p, p_end) < 0)
  1735.         return;
  1736.     if (h->tid != SDT_TID)
  1737.         return;
  1738.     onid = get16(&p, p_end);
  1739.     if (onid < 0)
  1740.         return;
  1741.     val = get8(&p, p_end);
  1742.     if (val < 0)
  1743.         return;
  1744.     for(;;) {
  1745.         sid = get16(&p, p_end);
  1746.         if (sid < 0)
  1747.             break;
  1748.         val = get8(&p, p_end);
  1749.         if (val < 0)
  1750.             break;
  1751.         desc_list_len = get16(&p, p_end);
  1752.         if (desc_list_len < 0)
  1753.             break;
  1754.         desc_list_len &= 0xfff;
  1755.         desc_list_end = p + desc_list_len;
  1756.         if (desc_list_end > p_end)
  1757.             break;
  1758.         for(;;) {
  1759.             desc_tag = get8(&p, desc_list_end);
  1760.             if (desc_tag < 0)
  1761.                 break;
  1762.             desc_len = get8(&p, desc_list_end);
  1763.             desc_end = p + desc_len;
  1764.             if (desc_end > desc_list_end)
  1765.                 break;
  1766.  
  1767.             av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
  1768.                    desc_tag, desc_len);
  1769.  
  1770.             switch(desc_tag) {
  1771.             case 0x48:
  1772.                 service_type = get8(&p, p_end);
  1773.                 if (service_type < 0)
  1774.                     break;
  1775.                 provider_name = getstr8(&p, p_end);
  1776.                 if (!provider_name)
  1777.                     break;
  1778.                 name = getstr8(&p, p_end);
  1779.                 if (name) {
  1780.                     AVProgram *program = av_new_program(ts->stream, sid);
  1781.                     if(program) {
  1782.                         av_dict_set(&program->metadata, "service_name", name, 0);
  1783.                         av_dict_set(&program->metadata, "service_provider", provider_name, 0);
  1784.                     }
  1785.                 }
  1786.                 av_free(name);
  1787.                 av_free(provider_name);
  1788.                 break;
  1789.             default:
  1790.                 break;
  1791.             }
  1792.             p = desc_end;
  1793.         }
  1794.         p = desc_list_end;
  1795.     }
  1796. }
  1797.  
  1798. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1799.                      const uint8_t *packet);
  1800.  
  1801. /* handle one TS packet */
  1802. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  1803. {
  1804.     AVFormatContext *s = ts->stream;
  1805.     MpegTSFilter *tss;
  1806.     int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
  1807.         has_adaptation, has_payload;
  1808.     const uint8_t *p, *p_end;
  1809.     int64_t pos;
  1810.  
  1811.     pid = AV_RB16(packet + 1) & 0x1fff;
  1812.     if(pid && discard_pid(ts, pid))
  1813.         return 0;
  1814.     is_start = packet[1] & 0x40;
  1815.     tss = ts->pids[pid];
  1816.     if (ts->auto_guess && tss == NULL && is_start) {
  1817.         add_pes_stream(ts, pid, -1);
  1818.         tss = ts->pids[pid];
  1819.     }
  1820.     if (!tss)
  1821.         return 0;
  1822.     ts->current_pid = pid;
  1823.  
  1824.     afc = (packet[3] >> 4) & 3;
  1825.     if (afc == 0) /* reserved value */
  1826.         return 0;
  1827.     has_adaptation = afc & 2;
  1828.     has_payload = afc & 1;
  1829.     is_discontinuity = has_adaptation
  1830.                 && packet[4] != 0 /* with length > 0 */
  1831.                 && (packet[5] & 0x80); /* and discontinuity indicated */
  1832.  
  1833.     /* continuity check (currently not used) */
  1834.     cc = (packet[3] & 0xf);
  1835.     expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
  1836.     cc_ok = pid == 0x1FFF // null packet PID
  1837.             || is_discontinuity
  1838.             || tss->last_cc < 0
  1839.             || expected_cc == cc;
  1840.  
  1841.     tss->last_cc = cc;
  1842.     if (!cc_ok) {
  1843.         av_log(ts->stream, AV_LOG_DEBUG,
  1844.                "Continuity check failed for pid %d expected %d got %d\n",
  1845.                pid, expected_cc, cc);
  1846.         if(tss->type == MPEGTS_PES) {
  1847.             PESContext *pc = tss->u.pes_filter.opaque;
  1848.             pc->flags |= AV_PKT_FLAG_CORRUPT;
  1849.         }
  1850.     }
  1851.  
  1852.     if (!has_payload)
  1853.         return 0;
  1854.     p = packet + 4;
  1855.     if (has_adaptation) {
  1856.         /* skip adaptation field */
  1857.         p += p[0] + 1;
  1858.     }
  1859.     /* if past the end of packet, ignore */
  1860.     p_end = packet + TS_PACKET_SIZE;
  1861.     if (p >= p_end)
  1862.         return 0;
  1863.  
  1864.     pos = avio_tell(ts->stream->pb);
  1865.     if (pos >= 0) {
  1866.         av_assert0(pos >= TS_PACKET_SIZE);
  1867.         ts->pos47_full = pos - TS_PACKET_SIZE;
  1868.     }
  1869.  
  1870.     if (tss->type == MPEGTS_SECTION) {
  1871.         if (is_start) {
  1872.             /* pointer field present */
  1873.             len = *p++;
  1874.             if (p + len > p_end)
  1875.                 return 0;
  1876.             if (len && cc_ok) {
  1877.                 /* write remaining section bytes */
  1878.                 write_section_data(s, tss,
  1879.                                    p, len, 0);
  1880.                 /* check whether filter has been closed */
  1881.                 if (!ts->pids[pid])
  1882.                     return 0;
  1883.             }
  1884.             p += len;
  1885.             if (p < p_end) {
  1886.                 write_section_data(s, tss,
  1887.                                    p, p_end - p, 1);
  1888.             }
  1889.         } else {
  1890.             if (cc_ok) {
  1891.                 write_section_data(s, tss,
  1892.                                    p, p_end - p, 0);
  1893.             }
  1894.         }
  1895.     } else {
  1896.         int ret;
  1897.         int64_t pcr = -1;
  1898.         int64_t pcr_h;
  1899.         int pcr_l;
  1900.         if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
  1901.             pcr = pcr_h * 300 + pcr_l;
  1902.         // Note: The position here points actually behind the current packet.
  1903.         if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  1904.                                             pos - ts->raw_packet_size, pcr)) < 0)
  1905.             return ret;
  1906.     }
  1907.  
  1908.     return 0;
  1909. }
  1910.  
  1911. static void reanalyze(MpegTSContext *ts) {
  1912.     AVIOContext *pb = ts->stream->pb;
  1913.     int64_t pos = avio_tell(pb);
  1914.     if(pos < 0)
  1915.         return;
  1916.     pos -= ts->pos47_full;
  1917.     if (pos == TS_PACKET_SIZE) {
  1918.         ts->size_stat[0] ++;
  1919.     } else if (pos == TS_DVHS_PACKET_SIZE) {
  1920.         ts->size_stat[1] ++;
  1921.     } else if (pos == TS_FEC_PACKET_SIZE) {
  1922.         ts->size_stat[2] ++;
  1923.     }
  1924.  
  1925.     ts->size_stat_count ++;
  1926.     if(ts->size_stat_count > SIZE_STAT_THRESHOLD) {
  1927.         int newsize = 0;
  1928.         if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
  1929.             newsize = TS_PACKET_SIZE;
  1930.         } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
  1931.             newsize = TS_DVHS_PACKET_SIZE;
  1932.         } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
  1933.             newsize = TS_FEC_PACKET_SIZE;
  1934.         }
  1935.         if (newsize && newsize != ts->raw_packet_size) {
  1936.             av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
  1937.             ts->raw_packet_size = newsize;
  1938.         }
  1939.         ts->size_stat_count = 0;
  1940.         memset(ts->size_stat, 0, sizeof(ts->size_stat));
  1941.     }
  1942. }
  1943.  
  1944. /* XXX: try to find a better synchro over several packets (use
  1945.    get_packet_size() ?) */
  1946. static int mpegts_resync(AVFormatContext *s)
  1947. {
  1948.     AVIOContext *pb = s->pb;
  1949.     int c, i;
  1950.  
  1951.     for(i = 0;i < MAX_RESYNC_SIZE; i++) {
  1952.         c = avio_r8(pb);
  1953.         if (url_feof(pb))
  1954.             return -1;
  1955.         if (c == 0x47) {
  1956.             avio_seek(pb, -1, SEEK_CUR);
  1957.             reanalyze(s->priv_data);
  1958.             return 0;
  1959.         }
  1960.     }
  1961.     av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
  1962.     /* no sync found */
  1963.     return -1;
  1964. }
  1965.  
  1966. /* return -1 if error or EOF. Return 0 if OK. */
  1967. static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size, const uint8_t **data)
  1968. {
  1969.     AVIOContext *pb = s->pb;
  1970.     int len;
  1971.  
  1972.     for(;;) {
  1973.         len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
  1974.         if (len != TS_PACKET_SIZE)
  1975.             return len < 0 ? len : AVERROR_EOF;
  1976.         /* check packet sync byte */
  1977.         if ((*data)[0] != 0x47) {
  1978.             /* find a new packet start */
  1979.             uint64_t pos = avio_tell(pb);
  1980.             avio_seek(pb, -FFMIN(raw_packet_size, pos), SEEK_CUR);
  1981.  
  1982.             if (mpegts_resync(s) < 0)
  1983.                 return AVERROR(EAGAIN);
  1984.             else
  1985.                 continue;
  1986.         } else {
  1987.             break;
  1988.         }
  1989.     }
  1990.     return 0;
  1991. }
  1992.  
  1993. static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
  1994. {
  1995.     AVIOContext *pb = s->pb;
  1996.     int skip = raw_packet_size - TS_PACKET_SIZE;
  1997.     if (skip > 0)
  1998.         avio_skip(pb, skip);
  1999. }
  2000.  
  2001. static int handle_packets(MpegTSContext *ts, int nb_packets)
  2002. {
  2003.     AVFormatContext *s = ts->stream;
  2004.     uint8_t packet[TS_PACKET_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
  2005.     const uint8_t *data;
  2006.     int packet_num, ret = 0;
  2007.  
  2008.     if (avio_tell(s->pb) != ts->last_pos) {
  2009.         int i;
  2010.         av_dlog(ts->stream, "Skipping after seek\n");
  2011.         /* seek detected, flush pes buffer */
  2012.         for (i = 0; i < NB_PID_MAX; i++) {
  2013.             if (ts->pids[i]) {
  2014.                 if (ts->pids[i]->type == MPEGTS_PES) {
  2015.                    PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  2016.                    av_buffer_unref(&pes->buffer);
  2017.                    pes->data_index = 0;
  2018.                    pes->state = MPEGTS_SKIP; /* skip until pes header */
  2019.                    pes->last_pcr = -1;
  2020.                 }
  2021.                 ts->pids[i]->last_cc = -1;
  2022.             }
  2023.         }
  2024.     }
  2025.  
  2026.     ts->stop_parse = 0;
  2027.     packet_num = 0;
  2028.     memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  2029.     for(;;) {
  2030.         packet_num++;
  2031.         if (nb_packets != 0 && packet_num >= nb_packets ||
  2032.             ts->stop_parse > 1) {
  2033.             ret = AVERROR(EAGAIN);
  2034.             break;
  2035.         }
  2036.         if (ts->stop_parse > 0)
  2037.             break;
  2038.  
  2039.         ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2040.         if (ret != 0)
  2041.             break;
  2042.         ret = handle_packet(ts, data);
  2043.         finished_reading_packet(s, ts->raw_packet_size);
  2044.         if (ret != 0)
  2045.             break;
  2046.     }
  2047.     ts->last_pos = avio_tell(s->pb);
  2048.     return ret;
  2049. }
  2050.  
  2051. static int mpegts_probe(AVProbeData *p)
  2052. {
  2053.     const int size= p->buf_size;
  2054.     int maxscore=0;
  2055.     int sumscore=0;
  2056.     int i;
  2057.     int check_count= size / TS_FEC_PACKET_SIZE;
  2058. #define CHECK_COUNT 10
  2059. #define CHECK_BLOCK 100
  2060.  
  2061.     if (check_count < CHECK_COUNT)
  2062.         return -1;
  2063.  
  2064.     for (i=0; i<check_count; i+=CHECK_BLOCK){
  2065.         int left = FFMIN(check_count - i, CHECK_BLOCK);
  2066.         int score     = analyze(p->buf + TS_PACKET_SIZE     *i, TS_PACKET_SIZE     *left, TS_PACKET_SIZE     , NULL);
  2067.         int dvhs_score= analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL);
  2068.         int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
  2069.         score = FFMAX3(score, dvhs_score, fec_score);
  2070.         sumscore += score;
  2071.         maxscore = FFMAX(maxscore, score);
  2072.     }
  2073.  
  2074.     sumscore = sumscore*CHECK_COUNT/check_count;
  2075.     maxscore = maxscore*CHECK_COUNT/CHECK_BLOCK;
  2076.  
  2077.     av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
  2078.  
  2079.     if (sumscore > 6)           return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
  2080.     else if (maxscore > 6)      return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
  2081.     else                        return -1;
  2082. }
  2083.  
  2084. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  2085.    (-1) if not available */
  2086. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  2087.                      const uint8_t *packet)
  2088. {
  2089.     int afc, len, flags;
  2090.     const uint8_t *p;
  2091.     unsigned int v;
  2092.  
  2093.     afc = (packet[3] >> 4) & 3;
  2094.     if (afc <= 1)
  2095.         return -1;
  2096.     p = packet + 4;
  2097.     len = p[0];
  2098.     p++;
  2099.     if (len == 0)
  2100.         return -1;
  2101.     flags = *p++;
  2102.     len--;
  2103.     if (!(flags & 0x10))
  2104.         return -1;
  2105.     if (len < 6)
  2106.         return -1;
  2107.     v = AV_RB32(p);
  2108.     *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
  2109.     *ppcr_low = ((p[4] & 1) << 8) | p[5];
  2110.     return 0;
  2111. }
  2112.  
  2113. static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
  2114.  
  2115.     /* NOTE: We attempt to seek on non-seekable files as well, as the
  2116.      * probe buffer usually is big enough. Only warn if the seek failed
  2117.      * on files where the seek should work. */
  2118.     if (avio_seek(pb, pos, SEEK_SET) < 0)
  2119.         av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
  2120. }
  2121.  
  2122. static int mpegts_read_header(AVFormatContext *s)
  2123. {
  2124.     MpegTSContext *ts = s->priv_data;
  2125.     AVIOContext *pb = s->pb;
  2126.     uint8_t buf[8*1024]={0};
  2127.     int len;
  2128.     int64_t pos;
  2129.  
  2130.     ffio_ensure_seekback(pb, s->probesize);
  2131.  
  2132.     /* read the first 8192 bytes to get packet size */
  2133.     pos = avio_tell(pb);
  2134.     len = avio_read(pb, buf, sizeof(buf));
  2135.     ts->raw_packet_size = get_packet_size(buf, len);
  2136.     if (ts->raw_packet_size <= 0) {
  2137.         av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
  2138.         ts->raw_packet_size = TS_PACKET_SIZE;
  2139.     }
  2140.     ts->stream = s;
  2141.     ts->auto_guess = 0;
  2142.  
  2143.     if (s->iformat == &ff_mpegts_demuxer) {
  2144.         /* normal demux */
  2145.  
  2146.         /* first do a scan to get all the services */
  2147.         seek_back(s, pb, pos);
  2148.  
  2149.         mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  2150.  
  2151.         mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2152.  
  2153.         handle_packets(ts, s->probesize / ts->raw_packet_size);
  2154.         /* if could not find service, enable auto_guess */
  2155.  
  2156.         ts->auto_guess = 1;
  2157.  
  2158.         av_dlog(ts->stream, "tuning done\n");
  2159.  
  2160.         s->ctx_flags |= AVFMTCTX_NOHEADER;
  2161.     } else {
  2162.         AVStream *st;
  2163.         int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  2164.         int64_t pcrs[2], pcr_h;
  2165.         int packet_count[2];
  2166.         uint8_t packet[TS_PACKET_SIZE];
  2167.         const uint8_t *data;
  2168.  
  2169.         /* only read packets */
  2170.  
  2171.         st = avformat_new_stream(s, NULL);
  2172.         if (!st)
  2173.             goto fail;
  2174.         avpriv_set_pts_info(st, 60, 1, 27000000);
  2175.         st->codec->codec_type = AVMEDIA_TYPE_DATA;
  2176.         st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
  2177.  
  2178.         /* we iterate until we find two PCRs to estimate the bitrate */
  2179.         pcr_pid = -1;
  2180.         nb_pcrs = 0;
  2181.         nb_packets = 0;
  2182.         for(;;) {
  2183.             ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2184.             if (ret < 0)
  2185.                 goto fail;
  2186.             pid = AV_RB16(data + 1) & 0x1fff;
  2187.             if ((pcr_pid == -1 || pcr_pid == pid) &&
  2188.                 parse_pcr(&pcr_h, &pcr_l, data) == 0) {
  2189.                 finished_reading_packet(s, ts->raw_packet_size);
  2190.                 pcr_pid = pid;
  2191.                 packet_count[nb_pcrs] = nb_packets;
  2192.                 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  2193.                 nb_pcrs++;
  2194.                 if (nb_pcrs >= 2)
  2195.                     break;
  2196.             } else {
  2197.                 finished_reading_packet(s, ts->raw_packet_size);
  2198.             }
  2199.             nb_packets++;
  2200.         }
  2201.  
  2202.         /* NOTE1: the bitrate is computed without the FEC */
  2203.         /* NOTE2: it is only the bitrate of the start of the stream */
  2204.         ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  2205.         ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  2206.         s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
  2207.         st->codec->bit_rate = s->bit_rate;
  2208.         st->start_time = ts->cur_pcr;
  2209.         av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
  2210.                 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  2211.     }
  2212.  
  2213.     seek_back(s, pb, pos);
  2214.     return 0;
  2215.  fail:
  2216.     return -1;
  2217. }
  2218.  
  2219. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  2220.  
  2221. static int mpegts_raw_read_packet(AVFormatContext *s,
  2222.                                   AVPacket *pkt)
  2223. {
  2224.     MpegTSContext *ts = s->priv_data;
  2225.     int ret, i;
  2226.     int64_t pcr_h, next_pcr_h, pos;
  2227.     int pcr_l, next_pcr_l;
  2228.     uint8_t pcr_buf[12];
  2229.     const uint8_t *data;
  2230.  
  2231.     if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  2232.         return AVERROR(ENOMEM);
  2233.     pkt->pos= avio_tell(s->pb);
  2234.     ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
  2235.     if (ret < 0) {
  2236.         av_free_packet(pkt);
  2237.         return ret;
  2238.     }
  2239.     if (data != pkt->data)
  2240.         memcpy(pkt->data, data, ts->raw_packet_size);
  2241.     finished_reading_packet(s, ts->raw_packet_size);
  2242.     if (ts->mpeg2ts_compute_pcr) {
  2243.         /* compute exact PCR for each packet */
  2244.         if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  2245.             /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  2246.             pos = avio_tell(s->pb);
  2247.             for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
  2248.                 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  2249.                 avio_read(s->pb, pcr_buf, 12);
  2250.                 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  2251.                     /* XXX: not precise enough */
  2252.                     ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  2253.                         (i + 1);
  2254.                     break;
  2255.                 }
  2256.             }
  2257.             avio_seek(s->pb, pos, SEEK_SET);
  2258.             /* no next PCR found: we use previous increment */
  2259.             ts->cur_pcr = pcr_h * 300 + pcr_l;
  2260.         }
  2261.         pkt->pts = ts->cur_pcr;
  2262.         pkt->duration = ts->pcr_incr;
  2263.         ts->cur_pcr += ts->pcr_incr;
  2264.     }
  2265.     pkt->stream_index = 0;
  2266.     return 0;
  2267. }
  2268.  
  2269. static int mpegts_read_packet(AVFormatContext *s,
  2270.                               AVPacket *pkt)
  2271. {
  2272.     MpegTSContext *ts = s->priv_data;
  2273.     int ret, i;
  2274.  
  2275.     pkt->size = -1;
  2276.     ts->pkt = pkt;
  2277.     ret = handle_packets(ts, 0);
  2278.     if (ret < 0) {
  2279.         av_free_packet(ts->pkt);
  2280.         /* flush pes data left */
  2281.         for (i = 0; i < NB_PID_MAX; i++) {
  2282.             if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  2283.                 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  2284.                 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  2285.                     new_pes_packet(pes, pkt);
  2286.                     pes->state = MPEGTS_SKIP;
  2287.                     ret = 0;
  2288.                     break;
  2289.                 }
  2290.             }
  2291.         }
  2292.     }
  2293.  
  2294.     if (!ret && pkt->size < 0)
  2295.         ret = AVERROR(EINTR);
  2296.     return ret;
  2297. }
  2298.  
  2299. static void mpegts_free(MpegTSContext *ts)
  2300. {
  2301.     int i;
  2302.  
  2303.     clear_programs(ts);
  2304.  
  2305.     for(i=0;i<NB_PID_MAX;i++)
  2306.         if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
  2307. }
  2308.  
  2309. static int mpegts_read_close(AVFormatContext *s)
  2310. {
  2311.     MpegTSContext *ts = s->priv_data;
  2312.     mpegts_free(ts);
  2313.     return 0;
  2314. }
  2315.  
  2316. static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  2317.                               int64_t *ppos, int64_t pos_limit)
  2318. {
  2319.     MpegTSContext *ts = s->priv_data;
  2320.     int64_t pos, timestamp;
  2321.     uint8_t buf[TS_PACKET_SIZE];
  2322.     int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
  2323.     int pos47 = ts->pos47_full % ts->raw_packet_size;
  2324.     pos = ((*ppos  + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
  2325.     while(pos < pos_limit) {
  2326.         if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2327.             return AV_NOPTS_VALUE;
  2328.         if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  2329.             return AV_NOPTS_VALUE;
  2330.         if (buf[0] != 0x47) {
  2331.             avio_seek(s->pb, -TS_PACKET_SIZE, SEEK_CUR);
  2332.             if (mpegts_resync(s) < 0)
  2333.                 return AV_NOPTS_VALUE;
  2334.             pos = avio_tell(s->pb);
  2335.             continue;
  2336.         }
  2337.         if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  2338.             parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  2339.             *ppos = pos;
  2340.             return timestamp;
  2341.         }
  2342.         pos += ts->raw_packet_size;
  2343.     }
  2344.  
  2345.     return AV_NOPTS_VALUE;
  2346. }
  2347.  
  2348. static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
  2349.                               int64_t *ppos, int64_t pos_limit)
  2350. {
  2351.     MpegTSContext *ts = s->priv_data;
  2352.     int64_t pos;
  2353.     int pos47 = ts->pos47_full % ts->raw_packet_size;
  2354.     pos = ((*ppos  + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
  2355.     ff_read_frame_flush(s);
  2356.     if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2357.         return AV_NOPTS_VALUE;
  2358.     while(pos < pos_limit) {
  2359.         int ret;
  2360.         AVPacket pkt;
  2361.         av_init_packet(&pkt);
  2362.         ret= av_read_frame(s, &pkt);
  2363.         if(ret < 0)
  2364.             return AV_NOPTS_VALUE;
  2365.         av_free_packet(&pkt);
  2366.         if(pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0){
  2367.             ff_reduce_index(s, pkt.stream_index);
  2368.             av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
  2369.             if(pkt.stream_index == stream_index && pkt.pos >= *ppos){
  2370.                 *ppos= pkt.pos;
  2371.                 return pkt.dts;
  2372.             }
  2373.         }
  2374.         pos = pkt.pos;
  2375.     }
  2376.  
  2377.     return AV_NOPTS_VALUE;
  2378. }
  2379.  
  2380. /**************************************************************/
  2381. /* parsing functions - called from other demuxers such as RTP */
  2382.  
  2383. MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
  2384. {
  2385.     MpegTSContext *ts;
  2386.  
  2387.     ts = av_mallocz(sizeof(MpegTSContext));
  2388.     if (!ts)
  2389.         return NULL;
  2390.     /* no stream case, currently used by RTP */
  2391.     ts->raw_packet_size = TS_PACKET_SIZE;
  2392.     ts->stream = s;
  2393.     ts->auto_guess = 1;
  2394.     mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  2395.     mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2396.  
  2397.     return ts;
  2398. }
  2399.  
  2400. /* return the consumed length if a packet was output, or -1 if no
  2401.    packet is output */
  2402. int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  2403.                         const uint8_t *buf, int len)
  2404. {
  2405.     int len1;
  2406.  
  2407.     len1 = len;
  2408.     ts->pkt = pkt;
  2409.     for(;;) {
  2410.         ts->stop_parse = 0;
  2411.         if (len < TS_PACKET_SIZE)
  2412.             return -1;
  2413.         if (buf[0] != 0x47) {
  2414.             buf++;
  2415.             len--;
  2416.         } else {
  2417.             handle_packet(ts, buf);
  2418.             buf += TS_PACKET_SIZE;
  2419.             len -= TS_PACKET_SIZE;
  2420.             if (ts->stop_parse == 1)
  2421.                 break;
  2422.         }
  2423.     }
  2424.     return len1 - len;
  2425. }
  2426.  
  2427. void ff_mpegts_parse_close(MpegTSContext *ts)
  2428. {
  2429.     mpegts_free(ts);
  2430.     av_free(ts);
  2431. }
  2432.  
  2433. AVInputFormat ff_mpegts_demuxer = {
  2434.     .name           = "mpegts",
  2435.     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
  2436.     .priv_data_size = sizeof(MpegTSContext),
  2437.     .read_probe     = mpegts_probe,
  2438.     .read_header    = mpegts_read_header,
  2439.     .read_packet    = mpegts_read_packet,
  2440.     .read_close     = mpegts_read_close,
  2441.     .read_timestamp = mpegts_get_dts,
  2442.     .flags          = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2443.     .priv_class     = &mpegts_class,
  2444. };
  2445.  
  2446. AVInputFormat ff_mpegtsraw_demuxer = {
  2447.     .name           = "mpegtsraw",
  2448.     .long_name      = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
  2449.     .priv_data_size = sizeof(MpegTSContext),
  2450.     .read_header    = mpegts_read_header,
  2451.     .read_packet    = mpegts_raw_read_packet,
  2452.     .read_close     = mpegts_read_close,
  2453.     .read_timestamp = mpegts_get_dts,
  2454.     .flags          = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2455.     .priv_class     = &mpegtsraw_class,
  2456. };
  2457.