xref: /third_party/ffmpeg/libavformat/mpegts.c (revision cabdff1a)
1/*
2 * MPEG-2 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 "config_components.h"
23
24#include "libavutil/buffer.h"
25#include "libavutil/common.h"
26#include "libavutil/crc.h"
27#include "libavutil/internal.h"
28#include "libavutil/intreadwrite.h"
29#include "libavutil/log.h"
30#include "libavutil/dict.h"
31#include "libavutil/mathematics.h"
32#include "libavutil/opt.h"
33#include "libavutil/avassert.h"
34#include "libavutil/dovi_meta.h"
35#ifdef OHOS_DRM
36#include "libavutil/thread.h"
37#endif
38#include "libavcodec/bytestream.h"
39#include "libavcodec/get_bits.h"
40#include "libavcodec/opus.h"
41#include "avformat.h"
42#include "mpegts.h"
43#include "internal.h"
44#include "avio_internal.h"
45#include "demux.h"
46#include "mpeg.h"
47#include "isom.h"
48#if CONFIG_ICONV
49#include <iconv.h>
50#endif
51
52/* maximum size in which we look for synchronization if
53 * synchronization is lost */
54#define MAX_RESYNC_SIZE 65536
55
56#define MAX_MP4_DESCR_COUNT 16
57
58#ifdef OHOS_DRM
59#define DRM_USER_DATA_REGISTERED_UUID_SIZE 16
60#define DRM_VIDEO_FRAME_ARR_LEN            3
61#define DRM_H265_PAYLOAD_TYPE_OFFSET       5
62#define DRM_LEGACY_LEN                     3
63#define DRM_AMBIGUITY_ARR_LEN              3
64#define DRM_AMBIGUITY_START_NUM            (0x00)
65#define DRM_AMBIGUITY_END_NUM              (0x03)
66#define DRM_MIN_DRM_INFO_LEN               (2)
67#define DRM_TS_CRYPT_BYTE_BLOCK            (1)
68#define DRM_TS_SKIP_BYTE_BLOCK             (9)
69#define DRM_SHIFT_LEFT_NUM                 (1)
70#define DRM_H264_VIDEO_NAL_TYPE_UMASK_NUM  (0x1f)
71#define DRM_H265_VIDEO_NAL_TYPE_UMASK_NUM  (0x3f)
72#define DRM_H264_VIDEO_START_NAL_TYPE      (1)
73#define DRM_H264_VIDEO_END_NAL_TYPE        (5)
74#define DRM_H265_VIDEO_END_NAL_TYPE        (31)
75#define DRM_AVS_FLAG                       (0xb5)
76#define DRM_USER_DATA_UNREGISTERED_TAG     (0x05)
77#define DRM_INVALID_START_POS              (0xffffffff)
78
79static AVMutex g_mpegts_mutex = AV_MUTEX_INITIALIZER;
80static AVMutex g_mpegts_drm_info_mutex = AV_MUTEX_INITIALIZER;
81
82static const uint8_t g_video_frame_arr[DRM_VIDEO_FRAME_ARR_LEN] = { 0x00, 0x00, 0x01 };
83static const uint8_t g_ambiguity_arr[DRM_AMBIGUITY_ARR_LEN] = { 0x00, 0x00, 0x03 };
84static const uint8_t g_user_registered_uuid[DRM_USER_DATA_REGISTERED_UUID_SIZE] = {
85    0x70, 0xc1, 0xdb, 0x9f, 0x66, 0xae, 0x41, 0x27, 0xbf, 0xc0, 0xbb, 0x19, 0x81, 0x69, 0x4b, 0x66
86};
87
88typedef enum {
89    DRM_ARR_SUBSCRIPT_ZERO = 0,
90    DRM_ARR_SUBSCRIPT_ONE,
91    DRM_ARR_SUBSCRIPT_TWO,
92    DRM_ARR_SUBSCRIPT_THREE,
93} DRM_ArrSubscriptCollection;
94#endif
95
96#define MOD_UNLIKELY(modulus, dividend, divisor, prev_dividend)                \
97    do {                                                                       \
98        if ((prev_dividend) == 0 || (dividend) - (prev_dividend) != (divisor)) \
99            (modulus) = (dividend) % (divisor);                                \
100        (prev_dividend) = (dividend);                                          \
101    } while (0)
102
103#define PROBE_PACKET_MAX_BUF 8192
104#define PROBE_PACKET_MARGIN 5
105
106enum MpegTSFilterType {
107    MPEGTS_PES,
108    MPEGTS_SECTION,
109    MPEGTS_PCR,
110};
111
112typedef struct MpegTSFilter MpegTSFilter;
113
114typedef int PESCallback (MpegTSFilter *f, const uint8_t *buf, int len,
115                         int is_start, int64_t pos);
116
117typedef struct MpegTSPESFilter {
118    PESCallback *pes_cb;
119    void *opaque;
120} MpegTSPESFilter;
121
122typedef void SectionCallback (MpegTSFilter *f, const uint8_t *buf, int len);
123
124typedef void SetServiceCallback (void *opaque, int ret);
125
126typedef struct MpegTSSectionFilter {
127    int section_index;
128    int section_h_size;
129    int last_ver;
130    unsigned crc;
131    unsigned last_crc;
132    uint8_t *section_buf;
133    unsigned int check_crc : 1;
134    unsigned int end_of_section_reached : 1;
135    SectionCallback *section_cb;
136    void *opaque;
137} MpegTSSectionFilter;
138
139struct MpegTSFilter {
140    int pid;
141    int es_id;
142    int last_cc; /* last cc code (-1 if first packet) */
143    int64_t last_pcr;
144    int discard;
145    enum MpegTSFilterType type;
146    union {
147        MpegTSPESFilter pes_filter;
148        MpegTSSectionFilter section_filter;
149    } u;
150};
151
152struct Stream {
153    int idx;
154    int stream_identifier;
155};
156
157#define MAX_STREAMS_PER_PROGRAM 128
158#define MAX_PIDS_PER_PROGRAM (MAX_STREAMS_PER_PROGRAM + 2)
159struct Program {
160    unsigned int id; // program id/service id
161    unsigned int nb_pids;
162    unsigned int pids[MAX_PIDS_PER_PROGRAM];
163    unsigned int nb_streams;
164    struct Stream streams[MAX_STREAMS_PER_PROGRAM];
165
166    /** have we found pmt for this program */
167    int pmt_found;
168};
169
170struct MpegTSContext {
171    const AVClass *class;
172    /* user data */
173    AVFormatContext *stream;
174    /** raw packet size, including FEC if present */
175    int raw_packet_size;
176
177    int64_t pos47_full;
178
179    /** if true, all pids are analyzed to find streams */
180    int auto_guess;
181
182    /** compute exact PCR for each transport stream packet */
183    int mpeg2ts_compute_pcr;
184
185    /** fix dvb teletext pts                                 */
186    int fix_teletext_pts;
187
188    int64_t cur_pcr;    /**< used to estimate the exact PCR */
189    int64_t pcr_incr;   /**< used to estimate the exact PCR */
190
191    /* data needed to handle file based ts */
192    /** stop parsing loop */
193    int stop_parse;
194    /** packet containing Audio/Video data */
195    AVPacket *pkt;
196    /** to detect seek */
197    int64_t last_pos;
198
199    int skip_changes;
200    int skip_clear;
201    int skip_unknown_pmt;
202
203    int scan_all_pmts;
204
205    int resync_size;
206    int merge_pmt_versions;
207    int max_packet_size;
208
209    /******************************************/
210    /* private mpegts data */
211    /* scan context */
212    /** structure to keep track of Program->pids mapping */
213    unsigned int nb_prg;
214    struct Program *prg;
215
216    int8_t crc_validity[NB_PID_MAX];
217    /** filters for various streams specified by PMT + for the PAT and PMT */
218    MpegTSFilter *pids[NB_PID_MAX];
219    int current_pid;
220
221    AVStream *epg_stream;
222    AVBufferPool* pools[32];
223};
224
225#define MPEGTS_OPTIONS \
226    { "resync_size",   "set size limit for looking up a new synchronization", offsetof(MpegTSContext, resync_size), AV_OPT_TYPE_INT,  { .i64 =  MAX_RESYNC_SIZE}, 0, INT_MAX,  AV_OPT_FLAG_DECODING_PARAM }
227
228static const AVOption options[] = {
229    MPEGTS_OPTIONS,
230    {"fix_teletext_pts", "try to fix pts values of dvb teletext streams", offsetof(MpegTSContext, fix_teletext_pts), AV_OPT_TYPE_BOOL,
231     {.i64 = 1}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
232    {"ts_packetsize", "output option carrying the raw packet size", offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT,
233     {.i64 = 0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
234    {"scan_all_pmts", "scan and combine all PMTs", offsetof(MpegTSContext, scan_all_pmts), AV_OPT_TYPE_BOOL,
235     {.i64 = -1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM },
236    {"skip_unknown_pmt", "skip PMTs for programs not advertised in the PAT", offsetof(MpegTSContext, skip_unknown_pmt), AV_OPT_TYPE_BOOL,
237     {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
238    {"merge_pmt_versions", "re-use streams when PMT's version/pids change", offsetof(MpegTSContext, merge_pmt_versions), AV_OPT_TYPE_BOOL,
239     {.i64 = 0}, 0, 1,  AV_OPT_FLAG_DECODING_PARAM },
240    {"skip_changes", "skip changing / adding streams / programs", offsetof(MpegTSContext, skip_changes), AV_OPT_TYPE_BOOL,
241     {.i64 = 0}, 0, 1, 0 },
242    {"skip_clear", "skip clearing programs", offsetof(MpegTSContext, skip_clear), AV_OPT_TYPE_BOOL,
243     {.i64 = 0}, 0, 1, 0 },
244    {"max_packet_size", "maximum size of emitted packet", offsetof(MpegTSContext, max_packet_size), AV_OPT_TYPE_INT,
245     {.i64 = 204800}, 1, INT_MAX/2, AV_OPT_FLAG_DECODING_PARAM },
246    { NULL },
247};
248
249static const AVClass mpegts_class = {
250    .class_name = "mpegts demuxer",
251    .item_name  = av_default_item_name,
252    .option     = options,
253    .version    = LIBAVUTIL_VERSION_INT,
254};
255
256static const AVOption raw_options[] = {
257    MPEGTS_OPTIONS,
258    { "compute_pcr",   "compute exact PCR for each transport stream packet",
259          offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_BOOL,
260          { .i64 = 0 }, 0, 1,  AV_OPT_FLAG_DECODING_PARAM },
261    { "ts_packetsize", "output option carrying the raw packet size",
262      offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT,
263      { .i64 = 0 }, 0, 0,
264      AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
265    { NULL },
266};
267
268static const AVClass mpegtsraw_class = {
269    .class_name = "mpegtsraw demuxer",
270    .item_name  = av_default_item_name,
271    .option     = raw_options,
272    .version    = LIBAVUTIL_VERSION_INT,
273};
274
275/* TS stream handling */
276
277enum MpegTSState {
278    MPEGTS_HEADER = 0,
279    MPEGTS_PESHEADER,
280    MPEGTS_PESHEADER_FILL,
281    MPEGTS_PAYLOAD,
282    MPEGTS_SKIP,
283};
284
285/* enough for PES header + length */
286#define PES_START_SIZE  6
287#define PES_HEADER_SIZE 9
288#define MAX_PES_HEADER_SIZE (9 + 255)
289
290typedef struct PESContext {
291    int pid;
292    int pcr_pid; /**< if -1 then all packets containing PCR are considered */
293    int stream_type;
294    MpegTSContext *ts;
295    AVFormatContext *stream;
296    AVStream *st;
297    AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
298    enum MpegTSState state;
299    /* used to get the format */
300    int data_index;
301    int flags; /**< copied to the AVPacket flags */
302    int PES_packet_length;
303    int pes_header_size;
304    int extended_stream_id;
305    uint8_t stream_id;
306    int64_t pts, dts;
307    int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
308    uint8_t header[MAX_PES_HEADER_SIZE];
309    AVBufferRef *buffer;
310    SLConfigDescr sl;
311    int merged_st;
312} PESContext;
313
314extern const AVInputFormat ff_mpegts_demuxer;
315
316#ifdef OHOS_DRM
317static void mpegts_set_drm_algo_and_blocks(uint8_t algo, AV_DrmCencInfo *cenc_info)
318{
319    if (algo == 0x1) { // 0x1:SM4-SAMPL SM4S
320        cenc_info->algo = AV_DRM_ALG_CENC_SM4_CBC;
321        cenc_info->encrypt_blocks = DRM_TS_CRYPT_BYTE_BLOCK;
322        cenc_info->skip_blocks = DRM_TS_SKIP_BYTE_BLOCK;
323    } else if (algo == 0x2) { // 0x2:AES CBCS
324        cenc_info->algo = AV_DRM_ALG_CENC_AES_CBC;
325        cenc_info->encrypt_blocks = DRM_TS_CRYPT_BYTE_BLOCK;
326        cenc_info->skip_blocks = DRM_TS_SKIP_BYTE_BLOCK;
327    } else if (algo == 0x5) { // 0x5:AES CBC1
328        cenc_info->algo = AV_DRM_ALG_CENC_AES_CBC;
329        cenc_info->encrypt_blocks = 0;
330        cenc_info->skip_blocks = 0;
331    } else if (algo == 0x3) { // 0x3:SM4-CBC SM4C
332        cenc_info->algo = AV_DRM_ALG_CENC_SM4_CBC;
333        cenc_info->encrypt_blocks = 0;
334        cenc_info->skip_blocks = 0;
335    } else if (algo == 0x0) { // 0x0:NONE
336        cenc_info->algo = AV_DRM_ALG_CENC_UNENCRYPTED;
337        cenc_info->encrypt_blocks = 0;
338        cenc_info->skip_blocks = 0;
339    }
340    return;
341}
342
343static int mpegts_get_drm_info(const uint8_t *src, uint32_t src_len, AV_DrmInfo *drm_info)
344{
345    uint32_t offset = 0;
346    if (src_len <= DRM_MIN_DRM_INFO_LEN) {
347        av_log(NULL, AV_LOG_ERROR, "algo not found");
348        return -1;
349    }
350    uint8_t video_algo = src[offset] & 0x0f; // video algo offset
351    av_log(NULL, AV_LOG_DEBUG, "video_algo:%d\n", video_algo);
352    offset++;
353    uint8_t audio_algo = src[offset] & 0x0f; // audio algo offset
354    av_log(NULL, AV_LOG_DEBUG, "audio_algo:%d\n", audio_algo);
355    offset++;
356
357    if (src_len - offset <= AV_DRM_MAX_DRM_PSSH_LEN) {
358        memcpy(drm_info->pssh, src + offset, src_len - offset);
359        drm_info->pssh_len = src_len - offset;
360    } else {
361        av_log(NULL, AV_LOG_ERROR, "pssh not found");
362        return -1;
363    }
364    if (src_len >= offset + AV_DRM_UUID_OFFSET + AV_DRM_MAX_DRM_UUID_LEN) {
365        memcpy(drm_info->uuid, src + offset + AV_DRM_UUID_OFFSET, AV_DRM_MAX_DRM_UUID_LEN);
366        drm_info->uuid_len = (uint32_t)AV_DRM_MAX_DRM_UUID_LEN;
367    } else {
368        av_log(NULL, AV_LOG_ERROR, "uuid not found");
369        return -1;
370    }
371    return 0;
372}
373
374static int mpegts_avstream_is_exist_pssh(const AV_DrmInfo *old_side_data, uint32_t count, AV_DrmInfo *info)
375{
376    uint32_t i = 0;
377    if (count == 0) {
378        return 0;
379    }
380    for (; i < count; i++) {
381        if ((old_side_data[i].pssh_len == info->pssh_len) &&
382            (old_side_data[i].uuid_len == info->uuid_len)) {
383            if ((memcmp(old_side_data[i].pssh, info->pssh, old_side_data[i].pssh_len) == 0) &&
384                (memcmp(old_side_data[i].uuid, info->uuid, old_side_data[i].uuid_len) == 0)) {
385                return 1;
386            }
387        }
388    }
389    return 0;
390}
391
392static void mpegts_avstream_copy_drm_info(AV_DrmInfo *new_side_data, const AV_DrmInfo *old_side_data,
393    uint32_t old_side_data_count, AV_DrmInfo *info)
394{
395    uint32_t i = 0;
396    for (; i < old_side_data_count; i++) {
397        new_side_data[i].uuid_len = old_side_data[i].uuid_len;
398        memcpy(new_side_data[i].uuid, old_side_data[i].uuid, old_side_data[i].uuid_len);
399        new_side_data[i].pssh_len = old_side_data[i].pssh_len;
400        memcpy(new_side_data[i].pssh, old_side_data[i].pssh, old_side_data[i].pssh_len);
401    }
402    new_side_data[i].uuid_len = info->uuid_len;
403    memcpy(new_side_data[i].uuid, info->uuid, info->uuid_len);
404    new_side_data[i].pssh_len = info->pssh_len;
405    memcpy(new_side_data[i].pssh, info->pssh, info->pssh_len);
406    return;
407}
408
409static void mpegts_avstream_set_drm_info(AVStream *avstream, AV_DrmInfo *info)
410{
411    AV_DrmInfo *old_side_data = NULL;
412    AV_DrmInfo *new_side_data = NULL;
413    size_t old_side_data_size = 0;
414    uint32_t old_side_data_count = 0;
415    uint32_t pssh_exist_flag = 0;
416    ff_mutex_lock(&g_mpegts_drm_info_mutex);
417    old_side_data = (AV_DrmInfo *)av_stream_get_side_data(avstream, AV_PKT_DATA_ENCRYPTION_INIT_INFO,
418        &old_side_data_size);
419    if ((old_side_data != NULL) && (old_side_data_size != 0)) {
420        old_side_data_count = old_side_data_size / sizeof(AV_DrmInfo);
421        pssh_exist_flag = mpegts_avstream_is_exist_pssh(old_side_data, old_side_data_count, info);
422    }
423    if (pssh_exist_flag == 0) {
424        new_side_data = (AV_DrmInfo *)av_mallocz(sizeof(AV_DrmInfo) * (old_side_data_count + 1));
425        if (new_side_data != NULL) {
426            mpegts_avstream_copy_drm_info(new_side_data, old_side_data, old_side_data_count, info);
427            int ret = av_stream_add_side_data(avstream, AV_PKT_DATA_ENCRYPTION_INIT_INFO, (uint8_t *)new_side_data,
428                (size_t)(sizeof(AV_DrmInfo) * (old_side_data_count + 1)));
429            if (ret < 0)
430                av_free(new_side_data);
431        }
432    }
433    ff_mutex_unlock(&g_mpegts_drm_info_mutex);
434    return;
435}
436
437static void mpegts_get_cenc_info(const uint8_t *src, uint32_t src_len, AV_DrmCencInfo *cenc_info)
438{
439    uint32_t offset = 0;
440    if (src_len <= DRM_MIN_DRM_INFO_LEN) {
441        av_log(NULL, AV_LOG_ERROR, "algo not found");
442        return;
443    }
444    memset(cenc_info, 0, sizeof(AV_DrmCencInfo));
445
446    uint8_t video_algo = src[offset] & 0x0f; // video algo offset
447    mpegts_set_drm_algo_and_blocks(video_algo, cenc_info);
448    offset++;
449    uint8_t audio_algo = src[offset] & 0x0f; // audio algo offset
450    av_log(NULL, AV_LOG_DEBUG, "audio_algo:%d\n", audio_algo);
451    offset++;
452    cenc_info->mode = AV_DRM_CENC_INFO_KEY_IV_SUBSAMPLES_NOT_SET;
453    return;
454}
455
456static void mpegts_drm_get_sync_header_index(uint8_t *data, uint32_t data_size, uint32_t *pos_index)
457{
458    uint32_t i;
459    for (i = *pos_index; (i + (uint32_t)DRM_LEGACY_LEN) < data_size; i++) {
460        if ((data[i] != g_video_frame_arr[DRM_ARR_SUBSCRIPT_ZERO]) ||
461            (data[i + DRM_ARR_SUBSCRIPT_ONE] != g_video_frame_arr[DRM_ARR_SUBSCRIPT_ONE]) ||
462            (data[i + DRM_ARR_SUBSCRIPT_TWO] != g_video_frame_arr[DRM_ARR_SUBSCRIPT_TWO])) {
463            continue;
464        }
465        *pos_index = i;
466        return;
467    }
468    *pos_index = data_size;
469    return;
470}
471
472static int mpegts_drm_find_avs_cei_nal_unit(uint8_t *data, uint32_t data_size, uint32_t *cei_start_pos,
473    uint32_t index)
474{
475    uint32_t i = index;
476    /*
477     * only squence_header allowed, cei is in first extension_and_user_data after squence_header.
478     * data[i + DRM_LEGACY_LEN] is the nal unit header(00~b8),
479     * 0xb0 means Squence header, 0xb5 means video extension, 0xb1 undefined, others are frames
480     */
481    if (((data[i + DRM_LEGACY_LEN] > 0) && (data[i + DRM_LEGACY_LEN] < 0xb8)) &&
482        (data[i + DRM_LEGACY_LEN] != 0xb0) && (data[i + DRM_LEGACY_LEN] != 0xb5) &&
483        (data[i + DRM_LEGACY_LEN] != 0xb1)) {
484        av_log(NULL, AV_LOG_DEBUG, "avs frame found\n");
485        return 0;
486    }
487    if ((data[i + DRM_LEGACY_LEN] == 0xb5) && (i + DRM_LEGACY_LEN + 1 < data_size)) {
488        /* extension_and_user_data found, 0xd0: extension user data tag, 0xf0: the higher 4 bits */
489        if ((data[i + DRM_LEGACY_LEN + 1] & 0xf0) == 0xd0) {
490            *cei_start_pos = i;
491            av_log(NULL, AV_LOG_DEBUG, "cei found, packet start pos:%d\n", *cei_start_pos);
492        } else {
493            av_log(NULL, AV_LOG_ERROR, "cei not found, type=0x%x\n", (data[i + DRM_LEGACY_LEN + 1] & 0xf0));
494        }
495    }
496    return -1;
497}
498
499static int mpegts_drm_find_hevc_cei_nal_unit(uint8_t *data, uint32_t data_size, uint32_t *cei_start_pos,
500    uint32_t index)
501{
502    uint32_t i = index;
503    uint8_t nal_type = (data[i + DRM_LEGACY_LEN] >> DRM_SHIFT_LEFT_NUM) & DRM_H265_VIDEO_NAL_TYPE_UMASK_NUM;
504    av_log(NULL, AV_LOG_DEBUG, "nal type=%x\n", nal_type);
505    if (nal_type <= DRM_H265_VIDEO_END_NAL_TYPE) { // nal type: 0 ~ 31 are slice nal units and reserved units
506        /* sei is not after frame data. */
507        av_log(NULL, AV_LOG_DEBUG, "h265 frame found\n");
508        return 0;
509    } else if ((nal_type == 39) && (i + DRM_H265_PAYLOAD_TYPE_OFFSET < data_size)) { // 39: SEI nal unit
510        if (data[i + DRM_H265_PAYLOAD_TYPE_OFFSET] == DRM_USER_DATA_UNREGISTERED_TAG) {
511            *cei_start_pos = i;
512        }
513    }
514    if (*cei_start_pos != DRM_INVALID_START_POS) {
515        uint32_t start_pos = i + DRM_H265_PAYLOAD_TYPE_OFFSET;
516        uint32_t end_pos = i + DRM_H265_PAYLOAD_TYPE_OFFSET;
517        *cei_start_pos = DRM_INVALID_START_POS;
518        mpegts_drm_get_sync_header_index(data, data_size, &end_pos);
519        for (; (start_pos + (uint32_t)DRM_USER_DATA_REGISTERED_UUID_SIZE < end_pos); start_pos++) {
520            if (memcmp(data + start_pos, g_user_registered_uuid,
521                (uint32_t)DRM_USER_DATA_REGISTERED_UUID_SIZE) == 0) {
522                *cei_start_pos = i;
523                av_log(NULL, AV_LOG_DEBUG, "cei found, packet start pos:%d\n", *cei_start_pos);
524                break;
525            }
526        }
527    }
528    return -1;
529}
530
531static int mpegts_drm_find_h264_cei_nal_unit(uint8_t *data, uint32_t data_size, uint32_t *cei_start_pos,
532    uint32_t index)
533{
534    uint32_t i = index;
535    uint8_t nal_type = data[i + DRM_LEGACY_LEN] & DRM_H264_VIDEO_NAL_TYPE_UMASK_NUM;
536    av_log(NULL, AV_LOG_DEBUG, "nal type=%x\n", nal_type);
537    if ((nal_type >= DRM_H264_VIDEO_START_NAL_TYPE) && (nal_type <= DRM_H264_VIDEO_END_NAL_TYPE)) {
538        /* sei is not after frame data. */
539        av_log(NULL, AV_LOG_DEBUG, "h264 frame found\n");
540        return 0;
541    } else if ((nal_type == 39) || (nal_type == 6)) { // 39 or 6 is SEI nal unit tag
542        if ((i + DRM_LEGACY_LEN + 1 < data_size) &&
543            (data[i + DRM_LEGACY_LEN + 1] == DRM_USER_DATA_UNREGISTERED_TAG)) {
544            *cei_start_pos = i;
545        }
546    }
547    if (*cei_start_pos != DRM_INVALID_START_POS) {
548        uint32_t start_pos = i + DRM_LEGACY_LEN + 1;
549        uint32_t end_pos = i + DRM_LEGACY_LEN + 1;
550        *cei_start_pos = DRM_INVALID_START_POS;
551        mpegts_drm_get_sync_header_index(data, data_size, &end_pos);
552        for (; (start_pos + (uint32_t)DRM_USER_DATA_REGISTERED_UUID_SIZE < end_pos); start_pos++) {
553            if (memcmp(data + start_pos, g_user_registered_uuid,
554                (uint32_t)DRM_USER_DATA_REGISTERED_UUID_SIZE) == 0) {
555                *cei_start_pos = i;
556                av_log(NULL, AV_LOG_DEBUG, "cei found, packet start pos:%d\n", *cei_start_pos);
557                break;
558            }
559        }
560    }
561    return -1;
562}
563
564static int mpegts_drm_find_cei_nal_unit(enum AVCodecID codec_id, uint8_t *data, uint32_t data_size,
565    uint32_t *cei_start_pos, uint32_t index)
566{
567    int ret = 0;
568    if (codec_id == AV_CODEC_ID_AVS2 || codec_id == AV_CODEC_ID_AVS3) {
569        ret = mpegts_drm_find_avs_cei_nal_unit(data, data_size, cei_start_pos, index);
570    } else if (codec_id == AV_CODEC_ID_HEVC) {
571        ret = mpegts_drm_find_hevc_cei_nal_unit(data, data_size, cei_start_pos, index);
572    } else if (codec_id == AV_CODEC_ID_H264) {
573        ret = mpegts_drm_find_h264_cei_nal_unit(data, data_size, cei_start_pos, index);
574    }
575    return ret;
576}
577
578static int mpegts_drm_find_cei_pos(enum AVCodecID codec_id, uint8_t *data, uint32_t data_size,
579    uint32_t *cei_start_pos, uint32_t *cei_end_pos)
580{
581    uint32_t i;
582    for (i = 0; (i + (uint32_t)DRM_LEGACY_LEN) < data_size; i++) {
583        /*the start code prefix is 0x000001*/
584        if ((data[i] == g_video_frame_arr[DRM_ARR_SUBSCRIPT_ZERO]) &&
585            (data[i + DRM_ARR_SUBSCRIPT_ONE] == g_video_frame_arr[DRM_ARR_SUBSCRIPT_ONE]) &&
586            (data[i + DRM_ARR_SUBSCRIPT_TWO] == g_video_frame_arr[DRM_ARR_SUBSCRIPT_TWO])) {
587            uint32_t start_pos = (uint32_t)DRM_INVALID_START_POS;
588            if (*cei_start_pos != (uint32_t)DRM_INVALID_START_POS) {
589                *cei_end_pos = i;
590                av_log(NULL, AV_LOG_DEBUG, "cei found, start pos:%x end pos:%x\n", *cei_start_pos, *cei_end_pos);
591            }
592            /* found a nal unit, process nal to find the cei.*/
593            if (!mpegts_drm_find_cei_nal_unit(codec_id, data, data_size, &start_pos, i)) {
594                break;
595            }
596            if (start_pos != DRM_INVALID_START_POS) {
597                *cei_start_pos = start_pos;
598                *cei_end_pos = (uint32_t)DRM_INVALID_START_POS;
599            }
600            i += (uint32_t)DRM_LEGACY_LEN;
601        }
602    }
603    if ((*cei_start_pos != (uint32_t)DRM_INVALID_START_POS) && (*cei_end_pos != (uint32_t)DRM_INVALID_START_POS) &&
604        (*cei_start_pos < *cei_end_pos) && (*cei_end_pos <= data_size)) {
605        return 1; // 1 true
606    }
607    return 0;
608}
609
610static void mpegts_drm_remove_ambiguity_bytes(uint8_t *data, uint32_t *data_size, uint32_t offset)
611{
612    uint32_t len = *data_size;
613    uint32_t i;
614    for (i = offset; (i + (uint32_t)DRM_LEGACY_LEN) < len; i++) {
615        if ((data[i] == g_ambiguity_arr[DRM_ARR_SUBSCRIPT_ZERO]) &&
616            (data[i + DRM_ARR_SUBSCRIPT_ONE] == g_ambiguity_arr[DRM_ARR_SUBSCRIPT_ONE]) &&
617            (data[i + DRM_ARR_SUBSCRIPT_TWO] == g_ambiguity_arr[DRM_ARR_SUBSCRIPT_TWO])) {
618            if (data[i + DRM_ARR_SUBSCRIPT_THREE] >= DRM_AMBIGUITY_START_NUM &&
619                data[i + DRM_ARR_SUBSCRIPT_THREE] <= DRM_AMBIGUITY_END_NUM) {
620                memmove(data + i + DRM_ARR_SUBSCRIPT_TWO, data + i + DRM_ARR_SUBSCRIPT_THREE,
621                    len - (i + DRM_ARR_SUBSCRIPT_THREE));
622                len -= 1;
623                i++;
624            }
625        }
626    }
627    *data_size = len;
628    return;
629}
630
631static int mpegts_drm_get_key_id(uint8_t *data, uint32_t *data_size, uint32_t *pos, uint8_t *drm_descriptor_flag,
632    AV_DrmCencInfo *cenc_info)
633{
634    uint32_t offset = *pos;
635    if (offset >= *data_size) {
636        av_log(NULL, AV_LOG_ERROR, "cei data too short\n");
637        return -1;
638    }
639    uint8_t encryption_flag = (data[offset] & 0x80) >> 7; // 0x80 get encryption_flag & 7 get bits
640    uint8_t next_key_id_flag = (data[offset] & 0x40) >> 6; // 0x40 get next_key_id_flag & 6 get bits
641    *drm_descriptor_flag = (data[offset] & 0x20) >> 5; // 0x20 get drm_descriptor_flag & 5 get bits
642    offset += 1; // 1 skip flag
643    mpegts_drm_remove_ambiguity_bytes(data, data_size, offset);
644
645    if (encryption_flag != 0) {
646        if ((offset + (uint32_t)AV_DRM_KEY_ID_SIZE) > *data_size) {
647            av_log(NULL, AV_LOG_ERROR, "cei data too short\n");
648            return -1;
649        }
650        memcpy(cenc_info->key_id, data + offset, AV_DRM_KEY_ID_SIZE);
651        cenc_info->key_id_len = (uint32_t)AV_DRM_KEY_ID_SIZE;
652        offset += (uint32_t)AV_DRM_KEY_ID_SIZE;
653    } else {
654        cenc_info->algo = AV_DRM_ALG_CENC_UNENCRYPTED;
655    }
656    if (next_key_id_flag == 1) {
657        offset += (uint32_t)AV_DRM_KEY_ID_SIZE;
658    }
659    *pos = offset;
660    return 0;
661}
662
663static int mpegts_drm_get_iv(uint8_t *data, uint32_t data_size, uint32_t *pos, AV_DrmCencInfo *cenc_info)
664{
665    uint32_t offset = *pos;
666    if (offset >= data_size) {
667        av_log(NULL, AV_LOG_ERROR, "cei data too short\n");
668        return -1;
669    }
670    uint32_t iv_len = (uint32_t)(data[offset]);
671    offset += 1; // 1 skip iv len
672    if (offset + iv_len > data_size) {
673        av_log(NULL, AV_LOG_ERROR, "cei data too short\n");
674        return -1;
675    } else {
676        memcpy(cenc_info->iv, data + offset, iv_len);
677        cenc_info->iv_len = iv_len;
678        offset += iv_len;
679    }
680    *pos = offset;
681    return 0;
682}
683
684static int mpegts_drm_parse_drm_descriptor(AVStream *avstream, uint8_t *data, uint32_t data_size, uint32_t *pos,
685    uint8_t drm_descriptor_flag)
686{
687    int ret = 0;
688    uint32_t offset = *pos;
689    uint32_t drm_descriptor_len = 0;
690    AV_DrmInfo drm_info;
691    if (drm_descriptor_flag == 0) {
692        return 0;
693    }
694    if (offset + DRM_MIN_DRM_INFO_LEN >= data_size) {
695        av_log(NULL, AV_LOG_ERROR, "cei data too short\n");
696        return -1;
697    }
698    drm_descriptor_len = (uint32_t)(data[offset + 1]); // 1 drm descriptor len offset
699    if (offset + DRM_MIN_DRM_INFO_LEN + drm_descriptor_len > data_size) {
700        av_log(NULL, AV_LOG_ERROR, "drm descriptor data too short\n");
701        return -1;
702    }
703
704    ret = mpegts_get_drm_info(data + offset + DRM_MIN_DRM_INFO_LEN, drm_descriptor_len, &drm_info);
705    if (ret != 0) {
706        return ret;
707    }
708    mpegts_avstream_set_drm_info(avstream, &drm_info);
709    offset = offset + DRM_MIN_DRM_INFO_LEN + drm_descriptor_len;
710    *pos = offset;
711    return 0;
712}
713
714static int mpegts_drm_set_key_info(AVStream *avstream, uint8_t *data, uint32_t data_size, uint32_t cei_start_pos,
715    AV_DrmCencInfo *cenc_info)
716{
717    uint32_t total_size = data_size;
718    uint32_t pos = cei_start_pos;
719    uint8_t *cei_buf = NULL;
720    uint8_t drm_descriptor_flag = 0;
721
722    cei_buf = (uint8_t *)malloc(data_size);
723    if (cei_buf == NULL) {
724        av_log(NULL, AV_LOG_ERROR, "malloc cei data failed\n");
725        return 0;
726    }
727    memcpy(cei_buf, data, data_size);
728
729    if (pos + DRM_LEGACY_LEN >= total_size) {
730        av_log(NULL, AV_LOG_ERROR, "cei data too short\n");
731        free(cei_buf);
732        return 0;
733    }
734    if (cei_buf[pos + DRM_LEGACY_LEN] == (uint8_t)DRM_AVS_FLAG) {
735        pos += DRM_LEGACY_LEN; //skip 0x00 0x00 0x01
736        pos += 2; // 2 skip this flag
737    } else {
738        for (; (pos + (uint32_t)DRM_USER_DATA_REGISTERED_UUID_SIZE < total_size); pos++) {
739            if (memcmp(cei_buf + pos, g_user_registered_uuid, (uint32_t)DRM_USER_DATA_REGISTERED_UUID_SIZE) == 0) {
740                pos += (uint32_t)DRM_USER_DATA_REGISTERED_UUID_SIZE;
741                break;
742            }
743        }
744    }
745    int ret = mpegts_drm_get_key_id(cei_buf, &total_size, &pos, &drm_descriptor_flag, cenc_info);
746    if (ret != 0) {
747        free(cei_buf);
748        return 0; // 0 key_id not found
749    }
750    ret = mpegts_drm_get_iv(cei_buf, total_size, &pos, cenc_info);
751    if (ret != 0) {
752        free(cei_buf);
753        return 0; // 0 iv not found
754    }
755    ret = mpegts_drm_parse_drm_descriptor(avstream, cei_buf, total_size, &pos, drm_descriptor_flag);
756    if (ret != 0) {
757        free(cei_buf);
758        return 0; // 0 drm descriptor not found
759    }
760    free(cei_buf);
761    return 1; // 1 true
762}
763
764static void mpegts_drm_copy_cenc_info(AV_DrmCencInfo *dest, AV_DrmCencInfo *src, uint32_t flag)
765{
766    dest->algo = src->algo;
767    dest->key_id_len = src->key_id_len;
768    memcpy(dest->key_id, src->key_id, src->key_id_len);
769    dest->iv_len = src->iv_len;
770    memcpy(dest->iv, src->iv, src->iv_len);
771    dest->mode = src->mode;
772    dest->encrypt_blocks = src->encrypt_blocks;
773    dest->skip_blocks = src->skip_blocks;
774    dest->first_encrypt_offset = src->first_encrypt_offset;
775    if (flag == 1) { // 1:true
776        dest->sub_sample_num = src->sub_sample_num;
777        for (uint32_t i = 0; i < dest->sub_sample_num; i++) {
778            dest->sub_samples[i].clear_header_len = src->sub_samples[i].clear_header_len;
779            dest->sub_samples[i].pay_load_len = src->sub_samples[i].pay_load_len;
780        }
781    }
782}
783
784static void mpegts_avstream_set_cenc_info(AVStream *avstream, AV_DrmCencInfo *info)
785{
786    ff_mutex_lock(&g_mpegts_mutex);
787    AV_DrmCencInfo *cenc_info = (AV_DrmCencInfo *)av_stream_new_side_data(avstream, AV_PKT_DATA_ENCRYPTION_INFO,
788        (size_t)(sizeof(AV_DrmCencInfo)));
789    if (cenc_info != NULL) {
790        mpegts_drm_copy_cenc_info(cenc_info, info, 1); // 1:true
791    }
792    ff_mutex_unlock(&g_mpegts_mutex);
793    return;
794}
795
796static void mpegts_packet_set_cenc_info(AVPacket *pkt, AV_DrmCencInfo *info)
797{
798    AV_DrmCencInfo *cenc_info = (AV_DrmCencInfo *)av_packet_new_side_data(pkt, AV_PKT_DATA_ENCRYPTION_INFO,
799        (size_t)(sizeof(AV_DrmCencInfo)));
800    if (cenc_info != NULL) {
801        mpegts_drm_copy_cenc_info(cenc_info, info, 1); // 1:true
802    }
803    return;
804}
805
806static int mpegts_drm_get_cenc_info(AVStream *avstream, enum AVCodecID codec_id, uint8_t *data, uint32_t data_size,
807    AV_DrmCencInfo *cenc_info)
808{
809    int ret;
810    uint32_t cei_start_pos = (uint32_t)DRM_INVALID_START_POS;
811    uint32_t cei_end_pos = (uint32_t)DRM_INVALID_START_POS;
812    size_t cenc_info_size = 0;
813    AV_DrmCencInfo *cenc_info_store = NULL;
814
815    ff_mutex_lock(&g_mpegts_mutex);
816    cenc_info_store = (AV_DrmCencInfo *)av_stream_get_side_data(avstream, AV_PKT_DATA_ENCRYPTION_INFO,
817        &cenc_info_size);
818    if ((cenc_info_store != NULL) && (cenc_info_size != 0)) {
819        mpegts_drm_copy_cenc_info(cenc_info, cenc_info_store, 0);
820    } else {
821        ff_mutex_unlock(&g_mpegts_mutex);
822        return 0;
823    }
824    ff_mutex_unlock(&g_mpegts_mutex);
825
826    ret = mpegts_drm_find_cei_pos(codec_id, data, data_size, &cei_start_pos, &cei_end_pos);
827    if (ret) {
828        (void)mpegts_drm_set_key_info(avstream, data, cei_end_pos, cei_start_pos, cenc_info);
829    }
830    return 1;
831}
832
833static void mpegts_packet_add_cenc_info(AVFormatContext *s, AVPacket *pkt)
834{
835    AV_DrmCencInfo cenc_info;
836    if (pkt == NULL || pkt->data == NULL || pkt->size == 0) {
837        av_log(NULL, AV_LOG_ERROR, "pkt parameter err\n");
838        return;
839    }
840    if ((s == NULL) || (s->streams == NULL) || (pkt->stream_index >= s->nb_streams) ||
841        (s->streams[pkt->stream_index] == NULL) || (s->streams[pkt->stream_index]->codecpar == NULL)) {
842        av_log(NULL, AV_LOG_ERROR, "s parameter err\n");
843        return;
844    }
845    enum AVCodecID codec_id = s->streams[pkt->stream_index]->codecpar->codec_id;
846
847    memset(&cenc_info, 0, sizeof(AV_DrmCencInfo));
848
849    if ((codec_id != AV_CODEC_ID_AVS2) && (codec_id != AV_CODEC_ID_HEVC) && (codec_id != AV_CODEC_ID_H264) &&
850        (codec_id != AV_CODEC_ID_AVS3)) {
851        return;
852    }
853
854    cenc_info.sub_samples[0].clear_header_len = pkt->size;
855    cenc_info.sub_samples[0].pay_load_len = 0;
856    cenc_info.sub_sample_num = 1;
857    cenc_info.algo = AV_DRM_ALG_CENC_UNENCRYPTED;
858    cenc_info.mode = AV_DRM_CENC_INFO_KEY_IV_SUBSAMPLES_NOT_SET;
859
860    int ret = mpegts_drm_get_cenc_info(s->streams[pkt->stream_index], codec_id, pkt->data, pkt->size, &cenc_info);
861    if (ret) {
862        mpegts_packet_set_cenc_info(pkt, &cenc_info);
863        mpegts_avstream_set_cenc_info(s->streams[pkt->stream_index], &cenc_info);
864    }
865    return;
866}
867#endif
868
869static struct Program * get_program(MpegTSContext *ts, unsigned int programid)
870{
871    int i;
872    for (i = 0; i < ts->nb_prg; i++) {
873        if (ts->prg[i].id == programid) {
874            return &ts->prg[i];
875        }
876    }
877    return NULL;
878}
879
880static void clear_avprogram(MpegTSContext *ts, unsigned int programid)
881{
882    AVProgram *prg = NULL;
883    int i;
884
885    for (i = 0; i < ts->stream->nb_programs; i++)
886        if (ts->stream->programs[i]->id == programid) {
887            prg = ts->stream->programs[i];
888            break;
889        }
890    if (!prg)
891        return;
892    prg->nb_stream_indexes = 0;
893}
894
895static void clear_program(struct Program *p)
896{
897    if (!p)
898        return;
899    p->nb_pids = 0;
900    p->nb_streams = 0;
901    p->pmt_found = 0;
902}
903
904static void clear_programs(MpegTSContext *ts)
905{
906    av_freep(&ts->prg);
907    ts->nb_prg = 0;
908}
909
910static struct Program * add_program(MpegTSContext *ts, unsigned int programid)
911{
912    struct Program *p = get_program(ts, programid);
913    if (p)
914        return p;
915    if (av_reallocp_array(&ts->prg, ts->nb_prg + 1, sizeof(*ts->prg)) < 0) {
916        ts->nb_prg = 0;
917        return NULL;
918    }
919    p = &ts->prg[ts->nb_prg];
920    p->id = programid;
921    clear_program(p);
922    ts->nb_prg++;
923    return p;
924}
925
926static void add_pid_to_program(struct Program *p, unsigned int pid)
927{
928    int i;
929    if (!p)
930        return;
931
932    if (p->nb_pids >= MAX_PIDS_PER_PROGRAM)
933        return;
934
935    for (i = 0; i < p->nb_pids; i++)
936        if (p->pids[i] == pid)
937            return;
938
939    p->pids[p->nb_pids++] = pid;
940}
941
942static void update_av_program_info(AVFormatContext *s, unsigned int programid,
943                                   unsigned int pid, int version)
944{
945    int i;
946    for (i = 0; i < s->nb_programs; i++) {
947        AVProgram *program = s->programs[i];
948        if (program->id == programid) {
949            int old_pcr_pid = program->pcr_pid,
950                old_version = program->pmt_version;
951            program->pcr_pid = pid;
952            program->pmt_version = version;
953
954            if (old_version != -1 && old_version != version) {
955                av_log(s, AV_LOG_VERBOSE,
956                       "detected PMT change (program=%d, version=%d/%d, pcr_pid=0x%x/0x%x)\n",
957                       programid, old_version, version, old_pcr_pid, pid);
958            }
959            break;
960        }
961    }
962}
963
964/**
965 * @brief discard_pid() decides if the pid is to be discarded according
966 *                      to caller's programs selection
967 * @param ts    : - TS context
968 * @param pid   : - pid
969 * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
970 *         0 otherwise
971 */
972static int discard_pid(MpegTSContext *ts, unsigned int pid)
973{
974    int i, j, k;
975    int used = 0, discarded = 0;
976    struct Program *p;
977
978    if (pid == PAT_PID)
979        return 0;
980
981    /* If none of the programs have .discard=AVDISCARD_ALL then there's
982     * no way we have to discard this packet */
983    for (k = 0; k < ts->stream->nb_programs; k++)
984        if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
985            break;
986    if (k == ts->stream->nb_programs)
987        return 0;
988
989    for (i = 0; i < ts->nb_prg; i++) {
990        p = &ts->prg[i];
991        for (j = 0; j < p->nb_pids; j++) {
992            if (p->pids[j] != pid)
993                continue;
994            // is program with id p->id set to be discarded?
995            for (k = 0; k < ts->stream->nb_programs; k++) {
996                if (ts->stream->programs[k]->id == p->id) {
997                    if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
998                        discarded++;
999                    else
1000                        used++;
1001                }
1002            }
1003        }
1004    }
1005
1006    return !used && discarded;
1007}
1008
1009/**
1010 *  Assemble PES packets out of TS packets, and then call the "section_cb"
1011 *  function when they are complete.
1012 */
1013static void write_section_data(MpegTSContext *ts, MpegTSFilter *tss1,
1014                               const uint8_t *buf, int buf_size, int is_start)
1015{
1016    MpegTSSectionFilter *tss = &tss1->u.section_filter;
1017    uint8_t *cur_section_buf = NULL;
1018    int len, offset;
1019
1020    if (is_start) {
1021        memcpy(tss->section_buf, buf, buf_size);
1022        tss->section_index = buf_size;
1023        tss->section_h_size = -1;
1024        tss->end_of_section_reached = 0;
1025    } else {
1026        if (tss->end_of_section_reached)
1027            return;
1028        len = MAX_SECTION_SIZE - tss->section_index;
1029        if (buf_size < len)
1030            len = buf_size;
1031        memcpy(tss->section_buf + tss->section_index, buf, len);
1032        tss->section_index += len;
1033    }
1034
1035    offset = 0;
1036    cur_section_buf = tss->section_buf;
1037    while (cur_section_buf - tss->section_buf < MAX_SECTION_SIZE && cur_section_buf[0] != 0xff) {
1038        /* compute section length if possible */
1039        if (tss->section_h_size == -1 && tss->section_index - offset >= 3) {
1040            len = (AV_RB16(cur_section_buf + 1) & 0xfff) + 3;
1041            if (len > MAX_SECTION_SIZE)
1042                return;
1043            tss->section_h_size = len;
1044        }
1045
1046        if (tss->section_h_size != -1 &&
1047            tss->section_index >= offset + tss->section_h_size) {
1048            int crc_valid = 1;
1049            tss->end_of_section_reached = 1;
1050
1051            if (tss->check_crc) {
1052                crc_valid = !av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, cur_section_buf, tss->section_h_size);
1053                if (tss->section_h_size >= 4)
1054                    tss->crc = AV_RB32(cur_section_buf + tss->section_h_size - 4);
1055
1056                if (crc_valid) {
1057                    ts->crc_validity[ tss1->pid ] = 100;
1058                }else if (ts->crc_validity[ tss1->pid ] > -10) {
1059                    ts->crc_validity[ tss1->pid ]--;
1060                }else
1061                    crc_valid = 2;
1062            }
1063            if (crc_valid) {
1064                tss->section_cb(tss1, cur_section_buf, tss->section_h_size);
1065                if (crc_valid != 1)
1066                    tss->last_ver = -1;
1067            }
1068
1069            cur_section_buf += tss->section_h_size;
1070            offset += tss->section_h_size;
1071            tss->section_h_size = -1;
1072        } else {
1073            tss->section_h_size = -1;
1074            tss->end_of_section_reached = 0;
1075            break;
1076        }
1077    }
1078}
1079
1080static MpegTSFilter *mpegts_open_filter(MpegTSContext *ts, unsigned int pid,
1081                                        enum MpegTSFilterType type)
1082{
1083    MpegTSFilter *filter;
1084
1085    av_log(ts->stream, AV_LOG_TRACE, "Filter: pid=0x%x type=%d\n", pid, type);
1086
1087    if (pid >= NB_PID_MAX || ts->pids[pid])
1088        return NULL;
1089    filter = av_mallocz(sizeof(MpegTSFilter));
1090    if (!filter)
1091        return NULL;
1092    ts->pids[pid] = filter;
1093
1094    filter->type    = type;
1095    filter->pid     = pid;
1096    filter->es_id   = -1;
1097    filter->last_cc = -1;
1098    filter->last_pcr= -1;
1099
1100    return filter;
1101}
1102
1103static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts,
1104                                                unsigned int pid,
1105                                                SectionCallback *section_cb,
1106                                                void *opaque,
1107                                                int check_crc)
1108{
1109    MpegTSFilter *filter;
1110    MpegTSSectionFilter *sec;
1111    uint8_t *section_buf = av_mallocz(MAX_SECTION_SIZE);
1112
1113    if (!section_buf)
1114        return NULL;
1115
1116    if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_SECTION))) {
1117        av_free(section_buf);
1118        return NULL;
1119    }
1120    sec = &filter->u.section_filter;
1121    sec->section_cb  = section_cb;
1122    sec->opaque      = opaque;
1123    sec->section_buf = section_buf;
1124    sec->check_crc   = check_crc;
1125    sec->last_ver    = -1;
1126
1127    return filter;
1128}
1129
1130static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
1131                                            PESCallback *pes_cb,
1132                                            void *opaque)
1133{
1134    MpegTSFilter *filter;
1135    MpegTSPESFilter *pes;
1136
1137    if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_PES)))
1138        return NULL;
1139
1140    pes = &filter->u.pes_filter;
1141    pes->pes_cb = pes_cb;
1142    pes->opaque = opaque;
1143    return filter;
1144}
1145
1146static MpegTSFilter *mpegts_open_pcr_filter(MpegTSContext *ts, unsigned int pid)
1147{
1148    return mpegts_open_filter(ts, pid, MPEGTS_PCR);
1149}
1150
1151static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
1152{
1153    int pid;
1154
1155    pid = filter->pid;
1156    if (filter->type == MPEGTS_SECTION)
1157        av_freep(&filter->u.section_filter.section_buf);
1158    else if (filter->type == MPEGTS_PES) {
1159        PESContext *pes = filter->u.pes_filter.opaque;
1160        av_buffer_unref(&pes->buffer);
1161        /* referenced private data will be freed later in
1162         * avformat_close_input (pes->st->priv_data == pes) */
1163        if (!pes->st || pes->merged_st) {
1164            av_freep(&filter->u.pes_filter.opaque);
1165        }
1166    }
1167
1168    av_free(filter);
1169    ts->pids[pid] = NULL;
1170}
1171
1172static int analyze(const uint8_t *buf, int size, int packet_size,
1173                   int probe)
1174{
1175    int stat[TS_MAX_PACKET_SIZE];
1176    int stat_all = 0;
1177    int i;
1178    int best_score = 0;
1179
1180    memset(stat, 0, packet_size * sizeof(*stat));
1181
1182    for (i = 0; i < size - 3; i++) {
1183        if (buf[i] == 0x47) {
1184            int pid = AV_RB16(buf+1) & 0x1FFF;
1185            int asc = buf[i + 3] & 0x30;
1186            if (!probe || pid == 0x1FFF || asc) {
1187                int x = i % packet_size;
1188                stat[x]++;
1189                stat_all++;
1190                if (stat[x] > best_score) {
1191                    best_score = stat[x];
1192                }
1193            }
1194        }
1195    }
1196
1197    return best_score - FFMAX(stat_all - 10*best_score, 0)/10;
1198}
1199
1200/* autodetect fec presence */
1201static int get_packet_size(AVFormatContext* s)
1202{
1203    int score, fec_score, dvhs_score;
1204    int margin;
1205    int ret;
1206
1207    /*init buffer to store stream for probing */
1208    uint8_t buf[PROBE_PACKET_MAX_BUF] = {0};
1209    int buf_size = 0;
1210    int max_iterations = 16;
1211
1212    while (buf_size < PROBE_PACKET_MAX_BUF && max_iterations--) {
1213        ret = avio_read_partial(s->pb, buf + buf_size, PROBE_PACKET_MAX_BUF - buf_size);
1214        if (ret < 0)
1215            return AVERROR_INVALIDDATA;
1216        buf_size += ret;
1217
1218        score      = analyze(buf, buf_size, TS_PACKET_SIZE,      0);
1219        dvhs_score = analyze(buf, buf_size, TS_DVHS_PACKET_SIZE, 0);
1220        fec_score  = analyze(buf, buf_size, TS_FEC_PACKET_SIZE,  0);
1221        av_log(s, AV_LOG_TRACE, "Probe: %d, score: %d, dvhs_score: %d, fec_score: %d \n",
1222            buf_size, score, dvhs_score, fec_score);
1223
1224        margin = mid_pred(score, fec_score, dvhs_score);
1225
1226        if (buf_size < PROBE_PACKET_MAX_BUF)
1227            margin += PROBE_PACKET_MARGIN; /*if buffer not filled */
1228
1229        if (score > margin)
1230            return TS_PACKET_SIZE;
1231        else if (dvhs_score > margin)
1232            return TS_DVHS_PACKET_SIZE;
1233        else if (fec_score > margin)
1234            return TS_FEC_PACKET_SIZE;
1235    }
1236    return AVERROR_INVALIDDATA;
1237}
1238
1239typedef struct SectionHeader {
1240    uint8_t tid;
1241    uint16_t id;
1242    uint8_t version;
1243    uint8_t current_next;
1244    uint8_t sec_num;
1245    uint8_t last_sec_num;
1246} SectionHeader;
1247
1248static int skip_identical(const SectionHeader *h, MpegTSSectionFilter *tssf)
1249{
1250    if (h->version == tssf->last_ver && tssf->last_crc == tssf->crc)
1251        return 1;
1252
1253    tssf->last_ver = h->version;
1254    tssf->last_crc = tssf->crc;
1255
1256    return 0;
1257}
1258
1259static inline int get8(const uint8_t **pp, const uint8_t *p_end)
1260{
1261    const uint8_t *p;
1262    int c;
1263
1264    p = *pp;
1265    if (p >= p_end)
1266        return AVERROR_INVALIDDATA;
1267    c   = *p++;
1268    *pp = p;
1269    return c;
1270}
1271
1272static inline int get16(const uint8_t **pp, const uint8_t *p_end)
1273{
1274    const uint8_t *p;
1275    int c;
1276
1277    p = *pp;
1278    if (1 >= p_end - p)
1279        return AVERROR_INVALIDDATA;
1280    c   = AV_RB16(p);
1281    p  += 2;
1282    *pp = p;
1283    return c;
1284}
1285
1286/* read and allocate a DVB string preceded by its length */
1287static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
1288{
1289    int len;
1290    const uint8_t *p;
1291    char *str;
1292
1293    p   = *pp;
1294    len = get8(&p, p_end);
1295    if (len < 0)
1296        return NULL;
1297    if (len > p_end - p)
1298        return NULL;
1299#if CONFIG_ICONV
1300    if (len) {
1301        const char *encodings[] = {
1302            "ISO6937", "ISO-8859-5", "ISO-8859-6", "ISO-8859-7",
1303            "ISO-8859-8", "ISO-8859-9", "ISO-8859-10", "ISO-8859-11",
1304            "", "ISO-8859-13", "ISO-8859-14", "ISO-8859-15", "", "", "", "",
1305            "", "UCS-2BE", "KSC_5601", "GB2312", "UCS-2BE", "UTF-8", "", "",
1306            "", "", "", "", "", "", "", ""
1307        };
1308        iconv_t cd;
1309        char *in, *out;
1310        size_t inlen = len, outlen = inlen * 6 + 1;
1311        if (len >= 3 && p[0] == 0x10 && !p[1] && p[2] && p[2] <= 0xf && p[2] != 0xc) {
1312            char iso8859[12];
1313            snprintf(iso8859, sizeof(iso8859), "ISO-8859-%d", p[2]);
1314            inlen -= 3;
1315            in = (char *)p + 3;
1316            cd = iconv_open("UTF-8", iso8859);
1317        } else if (p[0] < 0x20) {
1318            inlen -= 1;
1319            in = (char *)p + 1;
1320            cd = iconv_open("UTF-8", encodings[*p]);
1321        } else {
1322            in = (char *)p;
1323            cd = iconv_open("UTF-8", encodings[0]);
1324        }
1325        if (cd == (iconv_t)-1)
1326            goto no_iconv;
1327        str = out = av_malloc(outlen);
1328        if (!str) {
1329            iconv_close(cd);
1330            return NULL;
1331        }
1332        if (iconv(cd, &in, &inlen, &out, &outlen) == -1) {
1333            iconv_close(cd);
1334            av_freep(&str);
1335            goto no_iconv;
1336        }
1337        iconv_close(cd);
1338        *out = 0;
1339        *pp = p + len;
1340        return str;
1341    }
1342no_iconv:
1343#endif
1344    str = av_malloc(len + 1);
1345    if (!str)
1346        return NULL;
1347    memcpy(str, p, len);
1348    str[len] = '\0';
1349    p  += len;
1350    *pp = p;
1351    return str;
1352}
1353
1354static int parse_section_header(SectionHeader *h,
1355                                const uint8_t **pp, const uint8_t *p_end)
1356{
1357    int val;
1358
1359    val = get8(pp, p_end);
1360    if (val < 0)
1361        return val;
1362    h->tid = val;
1363    *pp += 2;
1364    val  = get16(pp, p_end);
1365    if (val < 0)
1366        return val;
1367    h->id = val;
1368    val = get8(pp, p_end);
1369    if (val < 0)
1370        return val;
1371    h->version = (val >> 1) & 0x1f;
1372    h->current_next = val & 0x01;
1373    val = get8(pp, p_end);
1374    if (val < 0)
1375        return val;
1376    h->sec_num = val;
1377    val = get8(pp, p_end);
1378    if (val < 0)
1379        return val;
1380    h->last_sec_num = val;
1381    return 0;
1382}
1383
1384typedef struct StreamType {
1385    uint32_t stream_type;
1386    enum AVMediaType codec_type;
1387    enum AVCodecID codec_id;
1388} StreamType;
1389
1390static const StreamType ISO_types[] = {
1391    { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
1392    { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
1393    { 0x03, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3        },
1394    { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3        },
1395    { 0x0f, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC        },
1396    { 0x10, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4      },
1397    /* Makito encoder sets stream type 0x11 for AAC,
1398     * so auto-detect LOAS/LATM instead of hardcoding it. */
1399#if !CONFIG_LOAS_DEMUXER
1400    { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM   }, /* LATM syntax */
1401#endif
1402    { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264       },
1403    { 0x1c, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC        },
1404    { 0x20, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264       },
1405    { 0x21, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_JPEG2000   },
1406    { 0x24, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC       },
1407    { 0x42, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_CAVS       },
1408    { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC      },
1409    { 0xd2, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_AVS2       },
1410    { 0xd4, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_AVS3       },
1411    { 0xd5, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AVS3DA     }, /* avs3 audio */
1412    { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1        },
1413    { 0 },
1414};
1415
1416static const StreamType HDMV_types[] = {
1417    { 0x80, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_PCM_BLURAY        },
1418    { 0x81, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_AC3               },
1419    { 0x82, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS               },
1420    { 0x83, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_TRUEHD            },
1421    { 0x84, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_EAC3              },
1422    { 0x85, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS               }, /* DTS HD */
1423    { 0x86, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS               }, /* DTS HD MASTER*/
1424    { 0xa1, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_EAC3              }, /* E-AC3 Secondary Audio */
1425    { 0xa2, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS               }, /* DTS Express Secondary Audio */
1426    { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
1427    { 0x92, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_TEXT_SUBTITLE },
1428    { 0 },
1429};
1430
1431/* SCTE types */
1432static const StreamType SCTE_types[] = {
1433    { 0x86, AVMEDIA_TYPE_DATA,  AV_CODEC_ID_SCTE_35    },
1434    { 0 },
1435};
1436
1437/* ATSC ? */
1438static const StreamType MISC_types[] = {
1439    { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
1440    { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
1441    { 0 },
1442};
1443
1444/* HLS Sample Encryption Types  */
1445static const StreamType HLS_SAMPLE_ENC_types[] = {
1446    { 0xdb, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264},
1447    { 0xcf, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
1448    { 0xc1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
1449    { 0xc2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3},
1450    { 0 },
1451};
1452
1453static const StreamType REGD_types[] = {
1454    { MKTAG('d', 'r', 'a', 'c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
1455    { MKTAG('A', 'C', '-', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3   },
1456    { MKTAG('B', 'S', 'S', 'D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
1457    { MKTAG('D', 'T', 'S', '1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS   },
1458    { MKTAG('D', 'T', 'S', '2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS   },
1459    { MKTAG('D', 'T', 'S', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS   },
1460    { MKTAG('E', 'A', 'C', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3  },
1461    { MKTAG('H', 'E', 'V', 'C'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC  },
1462    { MKTAG('K', 'L', 'V', 'A'), AVMEDIA_TYPE_DATA,  AV_CODEC_ID_SMPTE_KLV },
1463    { MKTAG('I', 'D', '3', ' '), AVMEDIA_TYPE_DATA,  AV_CODEC_ID_TIMED_ID3 },
1464    { MKTAG('V', 'C', '-', '1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1   },
1465    { MKTAG('O', 'p', 'u', 's'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_OPUS  },
1466    { MKTAG('a', 'v', '3', 'a'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AVS3DA}, /* AVS3 Audio descriptor Tag */
1467    { 0 },
1468};
1469
1470static const StreamType METADATA_types[] = {
1471    { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
1472    { MKTAG('I','D','3',' '), AVMEDIA_TYPE_DATA, AV_CODEC_ID_TIMED_ID3 },
1473    { 0 },
1474};
1475
1476/* descriptor present */
1477static const StreamType DESC_types[] = {
1478    { 0x6a, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_AC3          }, /* AC-3 descriptor */
1479    { 0x7a, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_EAC3         }, /* E-AC-3 descriptor */
1480    { 0x7b, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS          },
1481    { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
1482    { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
1483    { 0 },
1484};
1485
1486static void mpegts_find_stream_type(AVStream *st,
1487                                    uint32_t stream_type,
1488                                    const StreamType *types)
1489{
1490    FFStream *const sti = ffstream(st);
1491    for (; types->stream_type; types++)
1492        if (stream_type == types->stream_type) {
1493            if (st->codecpar->codec_type != types->codec_type ||
1494                st->codecpar->codec_id   != types->codec_id) {
1495                st->codecpar->codec_type = types->codec_type;
1496                st->codecpar->codec_id   = types->codec_id;
1497                sti->need_context_update = 1;
1498            }
1499            sti->request_probe = 0;
1500            return;
1501        }
1502}
1503
1504static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
1505                                  uint32_t stream_type, uint32_t prog_reg_desc)
1506{
1507    FFStream *const sti = ffstream(st);
1508    int old_codec_type = st->codecpar->codec_type;
1509    int old_codec_id   = st->codecpar->codec_id;
1510    int old_codec_tag  = st->codecpar->codec_tag;
1511
1512    if (avcodec_is_open(sti->avctx)) {
1513        av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, internal codec is open\n");
1514        return 0;
1515    }
1516
1517    avpriv_set_pts_info(st, 33, 1, 90000);
1518    st->priv_data         = pes;
1519    st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
1520    st->codecpar->codec_id   = AV_CODEC_ID_NONE;
1521    sti->need_parsing = AVSTREAM_PARSE_FULL;
1522    pes->st          = st;
1523    pes->stream_type = stream_type;
1524
1525    av_log(pes->stream, AV_LOG_DEBUG,
1526           "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
1527           st->index, pes->stream_type, pes->pid, (char *)&prog_reg_desc);
1528
1529    st->codecpar->codec_tag = pes->stream_type;
1530
1531    mpegts_find_stream_type(st, pes->stream_type, ISO_types);
1532    if (pes->stream_type == 4 || pes->stream_type == 0x0f)
1533        sti->request_probe = 50;
1534    if ((prog_reg_desc == AV_RL32("HDMV") ||
1535         prog_reg_desc == AV_RL32("HDPR")) &&
1536        st->codecpar->codec_id == AV_CODEC_ID_NONE) {
1537        mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
1538        if (pes->stream_type == 0x83) {
1539            // HDMV TrueHD streams also contain an AC3 coded version of the
1540            // audio track - add a second stream for this
1541            AVStream *sub_st;
1542            // priv_data cannot be shared between streams
1543            PESContext *sub_pes = av_memdup(pes, sizeof(*sub_pes));
1544            if (!sub_pes)
1545                return AVERROR(ENOMEM);
1546
1547            sub_st = avformat_new_stream(pes->stream, NULL);
1548            if (!sub_st) {
1549                av_free(sub_pes);
1550                return AVERROR(ENOMEM);
1551            }
1552
1553            sub_st->id = pes->pid;
1554            avpriv_set_pts_info(sub_st, 33, 1, 90000);
1555            sub_st->priv_data         = sub_pes;
1556            sub_st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
1557            sub_st->codecpar->codec_id   = AV_CODEC_ID_AC3;
1558            ffstream(sub_st)->need_parsing = AVSTREAM_PARSE_FULL;
1559            sub_pes->sub_st           = pes->sub_st = sub_st;
1560        }
1561    }
1562    if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
1563        mpegts_find_stream_type(st, pes->stream_type, MISC_types);
1564    if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
1565        mpegts_find_stream_type(st, pes->stream_type, HLS_SAMPLE_ENC_types);
1566    if (st->codecpar->codec_id == AV_CODEC_ID_NONE) {
1567        st->codecpar->codec_id  = old_codec_id;
1568        st->codecpar->codec_type = old_codec_type;
1569    }
1570    if ((st->codecpar->codec_id == AV_CODEC_ID_NONE ||
1571            (sti->request_probe > 0 && sti->request_probe < AVPROBE_SCORE_STREAM_RETRY / 5)) &&
1572        sti->probe_packets > 0 &&
1573        stream_type == STREAM_TYPE_PRIVATE_DATA) {
1574        st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
1575        st->codecpar->codec_id   = AV_CODEC_ID_BIN_DATA;
1576        sti->request_probe = AVPROBE_SCORE_STREAM_RETRY / 5;
1577    }
1578
1579    /* queue a context update if properties changed */
1580    if (old_codec_type != st->codecpar->codec_type ||
1581        old_codec_id   != st->codecpar->codec_id   ||
1582        old_codec_tag  != st->codecpar->codec_tag)
1583        sti->need_context_update = 1;
1584
1585    return 0;
1586}
1587
1588static void reset_pes_packet_state(PESContext *pes)
1589{
1590    pes->pts        = AV_NOPTS_VALUE;
1591    pes->dts        = AV_NOPTS_VALUE;
1592    pes->data_index = 0;
1593    pes->flags      = 0;
1594    av_buffer_unref(&pes->buffer);
1595}
1596
1597static void new_data_packet(const uint8_t *buffer, int len, AVPacket *pkt)
1598{
1599    av_packet_unref(pkt);
1600    pkt->data = (uint8_t *)buffer;
1601    pkt->size = len;
1602}
1603
1604static int new_pes_packet(PESContext *pes, AVPacket *pkt)
1605{
1606    uint8_t *sd;
1607
1608    av_packet_unref(pkt);
1609
1610    pkt->buf  = pes->buffer;
1611    pkt->data = pes->buffer->data;
1612    pkt->size = pes->data_index;
1613
1614    if (pes->PES_packet_length &&
1615        pes->pes_header_size + pes->data_index != pes->PES_packet_length +
1616        PES_START_SIZE) {
1617        av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
1618        pes->flags |= AV_PKT_FLAG_CORRUPT;
1619    }
1620    memset(pkt->data + pkt->size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1621
1622    // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
1623    if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
1624        pkt->stream_index = pes->sub_st->index;
1625    else
1626        pkt->stream_index = pes->st->index;
1627    pkt->pts = pes->pts;
1628    pkt->dts = pes->dts;
1629    /* store position of first TS packet of this PES packet */
1630    pkt->pos   = pes->ts_packet_pos;
1631    pkt->flags = pes->flags;
1632
1633    pes->buffer = NULL;
1634    reset_pes_packet_state(pes);
1635
1636    sd = av_packet_new_side_data(pkt, AV_PKT_DATA_MPEGTS_STREAM_ID, 1);
1637    if (!sd)
1638        return AVERROR(ENOMEM);
1639    *sd = pes->stream_id;
1640
1641    return 0;
1642}
1643
1644static uint64_t get_ts64(GetBitContext *gb, int bits)
1645{
1646    if (get_bits_left(gb) < bits)
1647        return AV_NOPTS_VALUE;
1648    return get_bits64(gb, bits);
1649}
1650
1651static int read_sl_header(PESContext *pes, SLConfigDescr *sl,
1652                          const uint8_t *buf, int buf_size)
1653{
1654    GetBitContext gb;
1655    int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
1656    int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
1657    int dts_flag = -1, cts_flag = -1;
1658    int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
1659    uint8_t buf_padded[128 + AV_INPUT_BUFFER_PADDING_SIZE];
1660    int buf_padded_size = FFMIN(buf_size, sizeof(buf_padded) - AV_INPUT_BUFFER_PADDING_SIZE);
1661
1662    memcpy(buf_padded, buf, buf_padded_size);
1663
1664    init_get_bits(&gb, buf_padded, buf_padded_size * 8);
1665
1666    if (sl->use_au_start)
1667        au_start_flag = get_bits1(&gb);
1668    if (sl->use_au_end)
1669        au_end_flag = get_bits1(&gb);
1670    if (!sl->use_au_start && !sl->use_au_end)
1671        au_start_flag = au_end_flag = 1;
1672    if (sl->ocr_len > 0)
1673        ocr_flag = get_bits1(&gb);
1674    if (sl->use_idle)
1675        idle_flag = get_bits1(&gb);
1676    if (sl->use_padding)
1677        padding_flag = get_bits1(&gb);
1678    if (padding_flag)
1679        padding_bits = get_bits(&gb, 3);
1680
1681    if (!idle_flag && (!padding_flag || padding_bits != 0)) {
1682        if (sl->packet_seq_num_len)
1683            skip_bits_long(&gb, sl->packet_seq_num_len);
1684        if (sl->degr_prior_len)
1685            if (get_bits1(&gb))
1686                skip_bits(&gb, sl->degr_prior_len);
1687        if (ocr_flag)
1688            skip_bits_long(&gb, sl->ocr_len);
1689        if (au_start_flag) {
1690            if (sl->use_rand_acc_pt)
1691                get_bits1(&gb);
1692            if (sl->au_seq_num_len > 0)
1693                skip_bits_long(&gb, sl->au_seq_num_len);
1694            if (sl->use_timestamps) {
1695                dts_flag = get_bits1(&gb);
1696                cts_flag = get_bits1(&gb);
1697            }
1698        }
1699        if (sl->inst_bitrate_len)
1700            inst_bitrate_flag = get_bits1(&gb);
1701        if (dts_flag == 1)
1702            dts = get_ts64(&gb, sl->timestamp_len);
1703        if (cts_flag == 1)
1704            cts = get_ts64(&gb, sl->timestamp_len);
1705        if (sl->au_len > 0)
1706            skip_bits_long(&gb, sl->au_len);
1707        if (inst_bitrate_flag)
1708            skip_bits_long(&gb, sl->inst_bitrate_len);
1709    }
1710
1711    if (dts != AV_NOPTS_VALUE)
1712        pes->dts = dts;
1713    if (cts != AV_NOPTS_VALUE)
1714        pes->pts = cts;
1715
1716    if (sl->timestamp_len && sl->timestamp_res)
1717        avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
1718
1719    return (get_bits_count(&gb) + 7) >> 3;
1720}
1721
1722static AVBufferRef *buffer_pool_get(MpegTSContext *ts, int size)
1723{
1724    int index = av_log2(size + AV_INPUT_BUFFER_PADDING_SIZE);
1725    if (!ts->pools[index]) {
1726        int pool_size = FFMIN(ts->max_packet_size + AV_INPUT_BUFFER_PADDING_SIZE, 2 << index);
1727        ts->pools[index] = av_buffer_pool_init(pool_size, NULL);
1728        if (!ts->pools[index])
1729            return NULL;
1730    }
1731    return av_buffer_pool_get(ts->pools[index]);
1732}
1733
1734/* return non zero if a packet could be constructed */
1735static int mpegts_push_data(MpegTSFilter *filter,
1736                            const uint8_t *buf, int buf_size, int is_start,
1737                            int64_t pos)
1738{
1739    PESContext *pes   = filter->u.pes_filter.opaque;
1740    MpegTSContext *ts = pes->ts;
1741    const uint8_t *p;
1742    int ret, len;
1743
1744    if (!ts->pkt)
1745        return 0;
1746
1747    if (is_start) {
1748        if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1749            ret = new_pes_packet(pes, ts->pkt);
1750            if (ret < 0)
1751                return ret;
1752            ts->stop_parse = 1;
1753        } else {
1754            reset_pes_packet_state(pes);
1755        }
1756        pes->state         = MPEGTS_HEADER;
1757        pes->ts_packet_pos = pos;
1758    }
1759    p = buf;
1760    while (buf_size > 0) {
1761        switch (pes->state) {
1762        case MPEGTS_HEADER:
1763            len = PES_START_SIZE - pes->data_index;
1764            if (len > buf_size)
1765                len = buf_size;
1766            memcpy(pes->header + pes->data_index, p, len);
1767            pes->data_index += len;
1768            p += len;
1769            buf_size -= len;
1770            if (pes->data_index == PES_START_SIZE) {
1771                /* we got all the PES or section header. We can now
1772                 * decide */
1773                if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
1774                    pes->header[2] == 0x01) {
1775                    /* it must be an MPEG-2 PES stream */
1776                    pes->stream_id = pes->header[3];
1777                    av_log(pes->stream, AV_LOG_TRACE, "pid=%x stream_id=%#x\n", pes->pid, pes->stream_id);
1778
1779                    if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
1780                         (!pes->sub_st ||
1781                          pes->sub_st->discard == AVDISCARD_ALL)) ||
1782                        pes->stream_id == STREAM_ID_PADDING_STREAM)
1783                        goto skip;
1784
1785                    /* stream not present in PMT */
1786                    if (!pes->st) {
1787                        if (ts->skip_changes)
1788                            goto skip;
1789                        if (ts->merge_pmt_versions)
1790                            goto skip; /* wait for PMT to merge new stream */
1791
1792                        pes->st = avformat_new_stream(ts->stream, NULL);
1793                        if (!pes->st)
1794                            return AVERROR(ENOMEM);
1795                        pes->st->id = pes->pid;
1796                        mpegts_set_stream_info(pes->st, pes, 0, 0);
1797                    }
1798
1799                    pes->PES_packet_length = AV_RB16(pes->header + 4);
1800                    /* NOTE: zero length means the PES size is unbounded */
1801
1802                    if (pes->stream_id != STREAM_ID_PROGRAM_STREAM_MAP &&
1803                        pes->stream_id != STREAM_ID_PRIVATE_STREAM_2 &&
1804                        pes->stream_id != STREAM_ID_ECM_STREAM &&
1805                        pes->stream_id != STREAM_ID_EMM_STREAM &&
1806                        pes->stream_id != STREAM_ID_PROGRAM_STREAM_DIRECTORY &&
1807                        pes->stream_id != STREAM_ID_DSMCC_STREAM &&
1808                        pes->stream_id != STREAM_ID_TYPE_E_STREAM) {
1809                        FFStream *const pes_sti = ffstream(pes->st);
1810                        pes->state = MPEGTS_PESHEADER;
1811                        if (pes->st->codecpar->codec_id == AV_CODEC_ID_NONE && !pes_sti->request_probe) {
1812                            av_log(pes->stream, AV_LOG_TRACE,
1813                                    "pid=%x stream_type=%x probing\n",
1814                                    pes->pid,
1815                                    pes->stream_type);
1816                            pes_sti->request_probe = 1;
1817                        }
1818                    } else {
1819                        pes->pes_header_size = 6;
1820                        pes->state      = MPEGTS_PAYLOAD;
1821                        pes->data_index = 0;
1822                    }
1823                } else {
1824                    /* otherwise, it should be a table */
1825                    /* skip packet */
1826skip:
1827                    pes->state = MPEGTS_SKIP;
1828                    continue;
1829                }
1830            }
1831            break;
1832        /**********************************************/
1833        /* PES packing parsing */
1834        case MPEGTS_PESHEADER:
1835            len = PES_HEADER_SIZE - pes->data_index;
1836            if (len < 0)
1837                return AVERROR_INVALIDDATA;
1838            if (len > buf_size)
1839                len = buf_size;
1840            memcpy(pes->header + pes->data_index, p, len);
1841            pes->data_index += len;
1842            p += len;
1843            buf_size -= len;
1844            if (pes->data_index == PES_HEADER_SIZE) {
1845                pes->pes_header_size = pes->header[8] + 9;
1846                pes->state           = MPEGTS_PESHEADER_FILL;
1847            }
1848            break;
1849        case MPEGTS_PESHEADER_FILL:
1850            len = pes->pes_header_size - pes->data_index;
1851            if (len < 0)
1852                return AVERROR_INVALIDDATA;
1853            if (len > buf_size)
1854                len = buf_size;
1855            memcpy(pes->header + pes->data_index, p, len);
1856            pes->data_index += len;
1857            p += len;
1858            buf_size -= len;
1859            if (pes->data_index == pes->pes_header_size) {
1860                const uint8_t *r;
1861                unsigned int flags, pes_ext, skip;
1862
1863                flags = pes->header[7];
1864                r = pes->header + 9;
1865                pes->pts = AV_NOPTS_VALUE;
1866                pes->dts = AV_NOPTS_VALUE;
1867                if ((flags & 0xc0) == 0x80) {
1868                    pes->dts = pes->pts = ff_parse_pes_pts(r);
1869                    r += 5;
1870                } else if ((flags & 0xc0) == 0xc0) {
1871                    pes->pts = ff_parse_pes_pts(r);
1872                    r += 5;
1873                    pes->dts = ff_parse_pes_pts(r);
1874                    r += 5;
1875                }
1876                pes->extended_stream_id = -1;
1877                if (flags & 0x01) { /* PES extension */
1878                    pes_ext = *r++;
1879                    /* Skip PES private data, program packet sequence counter and P-STD buffer */
1880                    skip  = (pes_ext >> 4) & 0xb;
1881                    skip += skip & 0x9;
1882                    r    += skip;
1883                    if ((pes_ext & 0x41) == 0x01 &&
1884                        (r + 2) <= (pes->header + pes->pes_header_size)) {
1885                        /* PES extension 2 */
1886                        if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
1887                            pes->extended_stream_id = r[1];
1888                    }
1889                }
1890
1891                /* we got the full header. We parse it and get the payload */
1892                pes->state = MPEGTS_PAYLOAD;
1893                pes->data_index = 0;
1894                if (pes->stream_type == 0x12 && buf_size > 0) {
1895                    int sl_header_bytes = read_sl_header(pes, &pes->sl, p,
1896                                                         buf_size);
1897                    pes->pes_header_size += sl_header_bytes;
1898                    p += sl_header_bytes;
1899                    buf_size -= sl_header_bytes;
1900                }
1901                if (pes->stream_type == 0x15 && buf_size >= 5) {
1902                    /* skip metadata access unit header */
1903                    pes->pes_header_size += 5;
1904                    p += 5;
1905                    buf_size -= 5;
1906                }
1907                if (   pes->ts->fix_teletext_pts
1908                    && (   pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT
1909                        || pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
1910                    ) {
1911                    AVProgram *p = NULL;
1912                    int pcr_found = 0;
1913                    while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
1914                        if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
1915                            MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
1916                            if (f) {
1917                                AVStream *st = NULL;
1918                                if (f->type == MPEGTS_PES) {
1919                                    PESContext *pcrpes = f->u.pes_filter.opaque;
1920                                    if (pcrpes)
1921                                        st = pcrpes->st;
1922                                } else if (f->type == MPEGTS_PCR) {
1923                                    int i;
1924                                    for (i = 0; i < p->nb_stream_indexes; i++) {
1925                                        AVStream *pst = pes->stream->streams[p->stream_index[i]];
1926                                        if (pst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
1927                                            st = pst;
1928                                    }
1929                                }
1930                                if (f->last_pcr != -1 && !f->discard) {
1931                                    // teletext packets do not always have correct timestamps,
1932                                    // the standard says they should be handled after 40.6 ms at most,
1933                                    // and the pcr error to this packet should be no more than 100 ms.
1934                                    // TODO: we should interpolate the PCR, not just use the last one
1935                                    int64_t pcr = f->last_pcr / 300;
1936                                    pcr_found = 1;
1937                                    if (st) {
1938                                        const FFStream *const sti = ffstream(st);
1939                                        FFStream *const pes_sti   = ffstream(pes->st);
1940
1941                                        pes_sti->pts_wrap_reference = sti->pts_wrap_reference;
1942                                        pes_sti->pts_wrap_behavior  = sti->pts_wrap_behavior;
1943                                    }
1944                                    if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
1945                                        pes->pts = pes->dts = pcr;
1946                                    } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT &&
1947                                               pes->dts > pcr + 3654 + 9000) {
1948                                        pes->pts = pes->dts = pcr + 3654 + 9000;
1949                                    } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
1950                                               pes->dts > pcr + 10*90000) { //10sec
1951                                        pes->pts = pes->dts = pcr + 3654 + 9000;
1952                                    }
1953                                    break;
1954                                }
1955                            }
1956                        }
1957                    }
1958
1959                    if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT &&
1960                        !pcr_found) {
1961                        av_log(pes->stream, AV_LOG_VERBOSE,
1962                               "Forcing DTS/PTS to be unset for a "
1963                               "non-trustworthy PES packet for PID %d as "
1964                               "PCR hasn't been received yet.\n",
1965                               pes->pid);
1966                        pes->dts = pes->pts = AV_NOPTS_VALUE;
1967                    }
1968                }
1969            }
1970            break;
1971        case MPEGTS_PAYLOAD:
1972            do {
1973                int max_packet_size = ts->max_packet_size;
1974                if (pes->PES_packet_length && pes->PES_packet_length + PES_START_SIZE > pes->pes_header_size)
1975                    max_packet_size = pes->PES_packet_length + PES_START_SIZE - pes->pes_header_size;
1976
1977                if (pes->data_index > 0 &&
1978                    pes->data_index + buf_size > max_packet_size) {
1979                    ret = new_pes_packet(pes, ts->pkt);
1980                    if (ret < 0)
1981                        return ret;
1982                    pes->PES_packet_length = 0;
1983                    max_packet_size = ts->max_packet_size;
1984                    ts->stop_parse = 1;
1985                } else if (pes->data_index == 0 &&
1986                           buf_size > max_packet_size) {
1987                    // pes packet size is < ts size packet and pes data is padded with 0xff
1988                    // not sure if this is legal in ts but see issue #2392
1989                    buf_size = max_packet_size;
1990                }
1991
1992                if (!pes->buffer) {
1993                    pes->buffer = buffer_pool_get(ts, max_packet_size);
1994                    if (!pes->buffer)
1995                        return AVERROR(ENOMEM);
1996                }
1997
1998                memcpy(pes->buffer->data + pes->data_index, p, buf_size);
1999                pes->data_index += buf_size;
2000                /* emit complete packets with known packet size
2001                 * decreases demuxer delay for infrequent packets like subtitles from
2002                 * a couple of seconds to milliseconds for properly muxed files. */
2003                if (!ts->stop_parse && pes->PES_packet_length &&
2004                    pes->pes_header_size + pes->data_index == pes->PES_packet_length + PES_START_SIZE) {
2005                    ts->stop_parse = 1;
2006                    ret = new_pes_packet(pes, ts->pkt);
2007                    pes->state = MPEGTS_SKIP;
2008                    if (ret < 0)
2009                        return ret;
2010                }
2011            } while (0);
2012            buf_size = 0;
2013            break;
2014        case MPEGTS_SKIP:
2015            buf_size = 0;
2016            break;
2017        }
2018    }
2019
2020    return 0;
2021}
2022
2023static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
2024{
2025    MpegTSFilter *tss;
2026    PESContext *pes;
2027
2028    /* if no pid found, then add a pid context */
2029    pes = av_mallocz(sizeof(PESContext));
2030    if (!pes)
2031        return 0;
2032    pes->ts      = ts;
2033    pes->stream  = ts->stream;
2034    pes->pid     = pid;
2035    pes->pcr_pid = pcr_pid;
2036    pes->state   = MPEGTS_SKIP;
2037    pes->pts     = AV_NOPTS_VALUE;
2038    pes->dts     = AV_NOPTS_VALUE;
2039    tss          = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
2040    if (!tss) {
2041        av_free(pes);
2042        return 0;
2043    }
2044    return pes;
2045}
2046
2047#define MAX_LEVEL 4
2048typedef struct MP4DescrParseContext {
2049    AVFormatContext *s;
2050    FFIOContext pb;
2051    Mp4Descr *descr;
2052    Mp4Descr *active_descr;
2053    int descr_count;
2054    int max_descr_count;
2055    int level;
2056    int predefined_SLConfigDescriptor_seen;
2057} MP4DescrParseContext;
2058
2059static int init_MP4DescrParseContext(MP4DescrParseContext *d, AVFormatContext *s,
2060                                     const uint8_t *buf, unsigned size,
2061                                     Mp4Descr *descr, int max_descr_count)
2062{
2063    if (size > (1 << 30))
2064        return AVERROR_INVALIDDATA;
2065
2066    ffio_init_context(&d->pb, (unsigned char *)buf, size,
2067                      0, NULL, NULL, NULL, NULL);
2068
2069    d->s               = s;
2070    d->level           = 0;
2071    d->descr_count     = 0;
2072    d->descr           = descr;
2073    d->active_descr    = NULL;
2074    d->max_descr_count = max_descr_count;
2075
2076    return 0;
2077}
2078
2079static void update_offsets(AVIOContext *pb, int64_t *off, int *len)
2080{
2081    int64_t new_off = avio_tell(pb);
2082    (*len) -= new_off - *off;
2083    *off    = new_off;
2084}
2085
2086static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
2087                           int target_tag);
2088
2089static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
2090{
2091    while (len > 0) {
2092        int ret = parse_mp4_descr(d, off, len, 0);
2093        if (ret < 0)
2094            return ret;
2095        update_offsets(&d->pb.pub, &off, &len);
2096    }
2097    return 0;
2098}
2099
2100static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
2101{
2102    AVIOContext *const pb = &d->pb.pub;
2103    avio_rb16(pb); // ID
2104    avio_r8(pb);
2105    avio_r8(pb);
2106    avio_r8(pb);
2107    avio_r8(pb);
2108    avio_r8(pb);
2109    update_offsets(pb, &off, &len);
2110    return parse_mp4_descr_arr(d, off, len);
2111}
2112
2113static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
2114{
2115    int id_flags;
2116    if (len < 2)
2117        return 0;
2118    id_flags = avio_rb16(&d->pb.pub);
2119    if (!(id_flags & 0x0020)) { // URL_Flag
2120        update_offsets(&d->pb.pub, &off, &len);
2121        return parse_mp4_descr_arr(d, off, len); // ES_Descriptor[]
2122    } else {
2123        return 0;
2124    }
2125}
2126
2127static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
2128{
2129    AVIOContext *const pb = &d->pb.pub;
2130    int es_id = 0;
2131    int ret   = 0;
2132
2133    if (d->descr_count >= d->max_descr_count)
2134        return AVERROR_INVALIDDATA;
2135    ff_mp4_parse_es_descr(pb, &es_id);
2136    d->active_descr = d->descr + (d->descr_count++);
2137
2138    d->active_descr->es_id = es_id;
2139    update_offsets(pb, &off, &len);
2140    if ((ret = parse_mp4_descr(d, off, len, MP4DecConfigDescrTag)) < 0)
2141        return ret;
2142    update_offsets(pb, &off, &len);
2143    if (len > 0)
2144        ret = parse_mp4_descr(d, off, len, MP4SLDescrTag);
2145    d->active_descr = NULL;
2146    return ret;
2147}
2148
2149static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off,
2150                                      int len)
2151{
2152    Mp4Descr *descr = d->active_descr;
2153    if (!descr)
2154        return AVERROR_INVALIDDATA;
2155    d->active_descr->dec_config_descr = av_malloc(len);
2156    if (!descr->dec_config_descr)
2157        return AVERROR(ENOMEM);
2158    descr->dec_config_descr_len = len;
2159    avio_read(&d->pb.pub, descr->dec_config_descr, len);
2160    return 0;
2161}
2162
2163static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
2164{
2165    Mp4Descr *descr = d->active_descr;
2166    AVIOContext *const pb = &d->pb.pub;
2167    int predefined;
2168    if (!descr)
2169        return AVERROR_INVALIDDATA;
2170
2171#define R8_CHECK_CLIP_MAX(dst, maxv) do {                       \
2172    descr->sl.dst = avio_r8(pb);                                \
2173    if (descr->sl.dst > maxv) {                                 \
2174        descr->sl.dst = maxv;                                   \
2175        return AVERROR_INVALIDDATA;                             \
2176    }                                                           \
2177} while (0)
2178
2179    predefined = avio_r8(pb);
2180    if (!predefined) {
2181        int lengths;
2182        int flags = avio_r8(pb);
2183        descr->sl.use_au_start    = !!(flags & 0x80);
2184        descr->sl.use_au_end      = !!(flags & 0x40);
2185        descr->sl.use_rand_acc_pt = !!(flags & 0x20);
2186        descr->sl.use_padding     = !!(flags & 0x08);
2187        descr->sl.use_timestamps  = !!(flags & 0x04);
2188        descr->sl.use_idle        = !!(flags & 0x02);
2189        descr->sl.timestamp_res   = avio_rb32(pb);
2190        avio_rb32(pb);
2191        R8_CHECK_CLIP_MAX(timestamp_len, 63);
2192        R8_CHECK_CLIP_MAX(ocr_len,       63);
2193        R8_CHECK_CLIP_MAX(au_len,        31);
2194        descr->sl.inst_bitrate_len   = avio_r8(pb);
2195        lengths                      = avio_rb16(pb);
2196        descr->sl.degr_prior_len     = lengths >> 12;
2197        descr->sl.au_seq_num_len     = (lengths >> 7) & 0x1f;
2198        descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
2199    } else if (!d->predefined_SLConfigDescriptor_seen){
2200        avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
2201        d->predefined_SLConfigDescriptor_seen = 1;
2202    }
2203    return 0;
2204}
2205
2206static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
2207                           int target_tag)
2208{
2209    int tag;
2210    AVIOContext *const pb = &d->pb.pub;
2211    int len1 = ff_mp4_read_descr(d->s, pb, &tag);
2212    int ret = 0;
2213
2214    update_offsets(pb, &off, &len);
2215    if (len < 0 || len1 > len || len1 <= 0) {
2216        av_log(d->s, AV_LOG_ERROR,
2217               "Tag %x length violation new length %d bytes remaining %d\n",
2218               tag, len1, len);
2219        return AVERROR_INVALIDDATA;
2220    }
2221
2222    if (d->level++ >= MAX_LEVEL) {
2223        av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
2224        ret = AVERROR_INVALIDDATA;
2225        goto done;
2226    }
2227
2228    if (target_tag && tag != target_tag) {
2229        av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag,
2230               target_tag);
2231        ret = AVERROR_INVALIDDATA;
2232        goto done;
2233    }
2234
2235    switch (tag) {
2236    case MP4IODescrTag:
2237        ret = parse_MP4IODescrTag(d, off, len1);
2238        break;
2239    case MP4ODescrTag:
2240        ret = parse_MP4ODescrTag(d, off, len1);
2241        break;
2242    case MP4ESDescrTag:
2243        ret = parse_MP4ESDescrTag(d, off, len1);
2244        break;
2245    case MP4DecConfigDescrTag:
2246        ret = parse_MP4DecConfigDescrTag(d, off, len1);
2247        break;
2248    case MP4SLDescrTag:
2249        ret = parse_MP4SLDescrTag(d, off, len1);
2250        break;
2251    }
2252
2253
2254done:
2255    d->level--;
2256    avio_seek(pb, off + len1, SEEK_SET);
2257    return ret;
2258}
2259
2260static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
2261                         Mp4Descr *descr, int *descr_count, int max_descr_count)
2262{
2263    MP4DescrParseContext d;
2264    int ret;
2265
2266    ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
2267    if (ret < 0)
2268        return ret;
2269
2270    ret = parse_mp4_descr(&d, avio_tell(&d.pb.pub), size, MP4IODescrTag);
2271
2272    *descr_count = d.descr_count;
2273    return ret;
2274}
2275
2276static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
2277                       Mp4Descr *descr, int *descr_count, int max_descr_count)
2278{
2279    MP4DescrParseContext d;
2280    int ret;
2281
2282    ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
2283    if (ret < 0)
2284        return ret;
2285
2286    ret = parse_mp4_descr_arr(&d, avio_tell(&d.pb.pub), size);
2287
2288    *descr_count = d.descr_count;
2289    return ret;
2290}
2291
2292static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section,
2293                    int section_len)
2294{
2295    MpegTSContext *ts = filter->u.section_filter.opaque;
2296    MpegTSSectionFilter *tssf = &filter->u.section_filter;
2297    SectionHeader h;
2298    const uint8_t *p, *p_end;
2299    int mp4_descr_count = 0;
2300    Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
2301    int i, pid;
2302    AVFormatContext *s = ts->stream;
2303
2304    p_end = section + section_len - 4;
2305    p = section;
2306    if (parse_section_header(&h, &p, p_end) < 0)
2307        return;
2308    if (h.tid != M4OD_TID)
2309        return;
2310    if (skip_identical(&h, tssf))
2311        return;
2312
2313    mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count,
2314                MAX_MP4_DESCR_COUNT);
2315
2316    for (pid = 0; pid < NB_PID_MAX; pid++) {
2317        if (!ts->pids[pid])
2318            continue;
2319        for (i = 0; i < mp4_descr_count; i++) {
2320            PESContext *pes;
2321            AVStream *st;
2322            FFStream *sti;
2323            FFIOContext pb;
2324            if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
2325                continue;
2326            if (ts->pids[pid]->type != MPEGTS_PES) {
2327                av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
2328                continue;
2329            }
2330            pes = ts->pids[pid]->u.pes_filter.opaque;
2331            st  = pes->st;
2332            if (!st)
2333                continue;
2334            sti = ffstream(st);
2335
2336            pes->sl = mp4_descr[i].sl;
2337
2338            ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
2339                              mp4_descr[i].dec_config_descr_len, 0,
2340                              NULL, NULL, NULL, NULL);
2341            ff_mp4_read_dec_config_descr(s, st, &pb.pub);
2342            if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
2343                st->codecpar->extradata_size > 0)
2344                sti->need_parsing = 0;
2345            if (st->codecpar->codec_id == AV_CODEC_ID_H264 &&
2346                st->codecpar->extradata_size > 0)
2347                sti->need_parsing = 0;
2348
2349            st->codecpar->codec_type = avcodec_get_type(st->codecpar->codec_id);
2350            sti->need_context_update = 1;
2351        }
2352    }
2353    for (i = 0; i < mp4_descr_count; i++)
2354        av_free(mp4_descr[i].dec_config_descr);
2355}
2356
2357static void scte_data_cb(MpegTSFilter *filter, const uint8_t *section,
2358                    int section_len)
2359{
2360    AVProgram *prg = NULL;
2361    MpegTSContext *ts = filter->u.section_filter.opaque;
2362
2363    int idx = ff_find_stream_index(ts->stream, filter->pid);
2364    if (idx < 0)
2365        return;
2366
2367    /**
2368     * In case we receive an SCTE-35 packet before mpegts context is fully
2369     * initialized.
2370     */
2371    if (!ts->pkt)
2372        return;
2373
2374    new_data_packet(section, section_len, ts->pkt);
2375    ts->pkt->stream_index = idx;
2376    prg = av_find_program_from_stream(ts->stream, NULL, idx);
2377    if (prg && prg->pcr_pid != -1 && prg->discard != AVDISCARD_ALL) {
2378        MpegTSFilter *f = ts->pids[prg->pcr_pid];
2379        if (f && f->last_pcr != -1)
2380            ts->pkt->pts = ts->pkt->dts = f->last_pcr/300;
2381    }
2382    ts->stop_parse = 1;
2383
2384}
2385
2386static const uint8_t opus_coupled_stream_cnt[9] = {
2387    1, 0, 1, 1, 2, 2, 2, 3, 3
2388};
2389
2390static const uint8_t opus_stream_cnt[9] = {
2391    1, 1, 1, 2, 2, 3, 4, 4, 5,
2392};
2393
2394static const uint8_t opus_channel_map[8][8] = {
2395    { 0 },
2396    { 0,1 },
2397    { 0,2,1 },
2398    { 0,1,2,3 },
2399    { 0,4,1,2,3 },
2400    { 0,4,1,2,3,5 },
2401    { 0,4,1,2,3,5,6 },
2402    { 0,6,1,2,3,4,5,7 },
2403};
2404
2405int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
2406                              const uint8_t **pp, const uint8_t *desc_list_end,
2407                              Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
2408                              MpegTSContext *ts)
2409{
2410    FFStream *const sti = ffstream(st);
2411    const uint8_t *desc_end;
2412    int desc_len, desc_tag, desc_es_id, ext_desc_tag, channels, channel_config_code;
2413    char language[252];
2414    int i;
2415
2416    desc_tag = get8(pp, desc_list_end);
2417    if (desc_tag < 0)
2418        return AVERROR_INVALIDDATA;
2419    desc_len = get8(pp, desc_list_end);
2420    if (desc_len < 0)
2421        return AVERROR_INVALIDDATA;
2422    desc_end = *pp + desc_len;
2423    if (desc_end > desc_list_end)
2424        return AVERROR_INVALIDDATA;
2425
2426    av_log(fc, AV_LOG_TRACE, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
2427
2428    if ((st->codecpar->codec_id == AV_CODEC_ID_NONE || sti->request_probe > 0) &&
2429        stream_type == STREAM_TYPE_PRIVATE_DATA)
2430        mpegts_find_stream_type(st, desc_tag, DESC_types);
2431
2432    switch (desc_tag) {
2433    case VIDEO_STREAM_DESCRIPTOR:
2434        if (get8(pp, desc_end) & 0x1) {
2435            st->disposition |= AV_DISPOSITION_STILL_IMAGE;
2436        }
2437        break;
2438    case SL_DESCRIPTOR:
2439        desc_es_id = get16(pp, desc_end);
2440        if (desc_es_id < 0)
2441            break;
2442        if (ts && ts->pids[pid])
2443            ts->pids[pid]->es_id = desc_es_id;
2444        for (i = 0; i < mp4_descr_count; i++)
2445            if (mp4_descr[i].dec_config_descr_len &&
2446                mp4_descr[i].es_id == desc_es_id) {
2447                FFIOContext pb;
2448                ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
2449                                  mp4_descr[i].dec_config_descr_len, 0,
2450                                  NULL, NULL, NULL, NULL);
2451                ff_mp4_read_dec_config_descr(fc, st, &pb.pub);
2452                if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
2453                    st->codecpar->extradata_size > 0) {
2454                    sti->need_parsing        = 0;
2455                    sti->need_context_update = 1;
2456                }
2457                if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
2458                    mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
2459            }
2460        break;
2461    case FMC_DESCRIPTOR:
2462        if (get16(pp, desc_end) < 0)
2463            break;
2464        if (mp4_descr_count > 0 &&
2465            (st->codecpar->codec_id == AV_CODEC_ID_AAC_LATM ||
2466             (sti->request_probe == 0 && st->codecpar->codec_id == AV_CODEC_ID_NONE) ||
2467             sti->request_probe > 0) &&
2468            mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
2469            FFIOContext pb;
2470            ffio_init_context(&pb, mp4_descr->dec_config_descr,
2471                              mp4_descr->dec_config_descr_len, 0,
2472                              NULL, NULL, NULL, NULL);
2473            ff_mp4_read_dec_config_descr(fc, st, &pb.pub);
2474            if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
2475                st->codecpar->extradata_size > 0) {
2476                sti->request_probe = sti->need_parsing = 0;
2477                st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2478                sti->need_context_update = 1;
2479            }
2480        }
2481        break;
2482    case 0x56: /* DVB teletext descriptor */
2483        {
2484            uint8_t *extradata = NULL;
2485            int language_count = desc_len / 5, ret;
2486
2487            if (desc_len > 0 && desc_len % 5 != 0)
2488                return AVERROR_INVALIDDATA;
2489
2490            if (language_count > 0) {
2491                /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
2492                av_assert0(language_count <= sizeof(language) / 4);
2493
2494                if (st->codecpar->extradata == NULL) {
2495                    ret = ff_alloc_extradata(st->codecpar, language_count * 2);
2496                    if (ret < 0)
2497                        return ret;
2498                }
2499
2500                if (st->codecpar->extradata_size < language_count * 2)
2501                    return AVERROR_INVALIDDATA;
2502
2503                extradata = st->codecpar->extradata;
2504
2505                for (i = 0; i < language_count; i++) {
2506                    language[i * 4 + 0] = get8(pp, desc_end);
2507                    language[i * 4 + 1] = get8(pp, desc_end);
2508                    language[i * 4 + 2] = get8(pp, desc_end);
2509                    language[i * 4 + 3] = ',';
2510
2511                    memcpy(extradata, *pp, 2);
2512                    extradata += 2;
2513
2514                    *pp += 2;
2515                }
2516
2517                language[i * 4 - 1] = 0;
2518                av_dict_set(&st->metadata, "language", language, 0);
2519                sti->need_context_update = 1;
2520            }
2521        }
2522        break;
2523    case 0x59: /* subtitling descriptor */
2524        {
2525            /* 8 bytes per DVB subtitle substream data:
2526             * ISO_639_language_code (3 bytes),
2527             * subtitling_type (1 byte),
2528             * composition_page_id (2 bytes),
2529             * ancillary_page_id (2 bytes) */
2530            int language_count = desc_len / 8, ret;
2531
2532            if (desc_len > 0 && desc_len % 8 != 0)
2533                return AVERROR_INVALIDDATA;
2534
2535            if (language_count > 1) {
2536                avpriv_request_sample(fc, "DVB subtitles with multiple languages");
2537            }
2538
2539            if (language_count > 0) {
2540                uint8_t *extradata;
2541
2542                /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
2543                av_assert0(language_count <= sizeof(language) / 4);
2544
2545                if (st->codecpar->extradata == NULL) {
2546                    ret = ff_alloc_extradata(st->codecpar, language_count * 5);
2547                    if (ret < 0)
2548                        return ret;
2549                }
2550
2551                if (st->codecpar->extradata_size < language_count * 5)
2552                    return AVERROR_INVALIDDATA;
2553
2554                extradata = st->codecpar->extradata;
2555
2556                for (i = 0; i < language_count; i++) {
2557                    language[i * 4 + 0] = get8(pp, desc_end);
2558                    language[i * 4 + 1] = get8(pp, desc_end);
2559                    language[i * 4 + 2] = get8(pp, desc_end);
2560                    language[i * 4 + 3] = ',';
2561
2562                    /* hearing impaired subtitles detection using subtitling_type */
2563                    switch (*pp[0]) {
2564                    case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
2565                    case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
2566                    case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
2567                    case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
2568                    case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
2569                    case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
2570                        st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
2571                        break;
2572                    }
2573
2574                    extradata[4] = get8(pp, desc_end); /* subtitling_type */
2575                    memcpy(extradata, *pp, 4); /* composition_page_id and ancillary_page_id */
2576                    extradata += 5;
2577
2578                    *pp += 4;
2579                }
2580
2581                language[i * 4 - 1] = 0;
2582                av_dict_set(&st->metadata, "language", language, 0);
2583                sti->need_context_update = 1;
2584            }
2585        }
2586        break;
2587    case ISO_639_LANGUAGE_DESCRIPTOR:
2588        for (i = 0; i + 4 <= desc_len; i += 4) {
2589            language[i + 0] = get8(pp, desc_end);
2590            language[i + 1] = get8(pp, desc_end);
2591            language[i + 2] = get8(pp, desc_end);
2592            language[i + 3] = ',';
2593            switch (get8(pp, desc_end)) {
2594            case 0x01:
2595                st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;
2596                break;
2597            case 0x02:
2598                st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
2599                break;
2600            case 0x03:
2601                st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
2602                st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2603                break;
2604            }
2605        }
2606        if (i && language[0]) {
2607            language[i - 1] = 0;
2608            /* don't overwrite language, as it may already have been set by
2609             * another, more specific descriptor (e.g. supplementary audio) */
2610            av_dict_set(&st->metadata, "language", language, AV_DICT_DONT_OVERWRITE);
2611        }
2612        break;
2613    case REGISTRATION_DESCRIPTOR:
2614        st->codecpar->codec_tag = bytestream_get_le32(pp);
2615        av_log(fc, AV_LOG_TRACE, "reg_desc=%.4s\n", (char *)&st->codecpar->codec_tag);
2616        if (st->codecpar->codec_id == AV_CODEC_ID_NONE || sti->request_probe > 0) {
2617            mpegts_find_stream_type(st, st->codecpar->codec_tag, REGD_types);
2618            if (st->codecpar->codec_tag == MKTAG('B', 'S', 'S', 'D'))
2619                sti->request_probe = 50;
2620        }
2621        break;
2622    case 0x52: /* stream identifier descriptor */
2623        sti->stream_identifier = 1 + get8(pp, desc_end);
2624        break;
2625    case METADATA_DESCRIPTOR:
2626        if (get16(pp, desc_end) == 0xFFFF)
2627            *pp += 4;
2628        if (get8(pp, desc_end) == 0xFF) {
2629            st->codecpar->codec_tag = bytestream_get_le32(pp);
2630            if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
2631                mpegts_find_stream_type(st, st->codecpar->codec_tag, METADATA_types);
2632        }
2633        break;
2634    case 0x7f: /* DVB extension descriptor */
2635        ext_desc_tag = get8(pp, desc_end);
2636        if (ext_desc_tag < 0)
2637            return AVERROR_INVALIDDATA;
2638        if (st->codecpar->codec_id == AV_CODEC_ID_OPUS &&
2639            ext_desc_tag == 0x80) { /* User defined (provisional Opus) */
2640            if (!st->codecpar->extradata) {
2641                st->codecpar->extradata = av_mallocz(sizeof(opus_default_extradata) +
2642                                                     AV_INPUT_BUFFER_PADDING_SIZE);
2643                if (!st->codecpar->extradata)
2644                    return AVERROR(ENOMEM);
2645
2646                st->codecpar->extradata_size = sizeof(opus_default_extradata);
2647                memcpy(st->codecpar->extradata, opus_default_extradata, sizeof(opus_default_extradata));
2648
2649                channel_config_code = get8(pp, desc_end);
2650                if (channel_config_code < 0)
2651                    return AVERROR_INVALIDDATA;
2652                if (channel_config_code <= 0x8) {
2653                    st->codecpar->extradata[9]  = channels = channel_config_code ? channel_config_code : 2;
2654                    AV_WL32(&st->codecpar->extradata[12], 48000);
2655                    st->codecpar->extradata[18] = channel_config_code ? (channels > 2) : /* Dual Mono */ 255;
2656                    st->codecpar->extradata[19] = opus_stream_cnt[channel_config_code];
2657                    st->codecpar->extradata[20] = opus_coupled_stream_cnt[channel_config_code];
2658                    memcpy(&st->codecpar->extradata[21], opus_channel_map[channels - 1], channels);
2659                    st->codecpar->extradata_size = st->codecpar->extradata[18] ? 21 + channels : 19;
2660                } else {
2661                    avpriv_request_sample(fc, "Opus in MPEG-TS - channel_config_code > 0x8");
2662                }
2663                sti->need_parsing = AVSTREAM_PARSE_FULL;
2664                sti->need_context_update = 1;
2665            }
2666        }
2667        if (ext_desc_tag == 0x06) { /* supplementary audio descriptor */
2668            int flags;
2669
2670            if (desc_len < 1)
2671                return AVERROR_INVALIDDATA;
2672            flags = get8(pp, desc_end);
2673
2674            if ((flags & 0x80) == 0) /* mix_type */
2675                st->disposition |= AV_DISPOSITION_DEPENDENT;
2676
2677            switch ((flags >> 2) & 0x1F) { /* editorial_classification */
2678            case 0x01:
2679                st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
2680                st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2681                break;
2682            case 0x02:
2683                st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
2684                break;
2685            case 0x03:
2686                st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
2687                break;
2688            }
2689
2690            if (flags & 0x01) { /* language_code_present */
2691                if (desc_len < 4)
2692                    return AVERROR_INVALIDDATA;
2693                language[0] = get8(pp, desc_end);
2694                language[1] = get8(pp, desc_end);
2695                language[2] = get8(pp, desc_end);
2696                language[3] = 0;
2697
2698                /* This language always has to override a possible
2699                 * ISO 639 language descriptor language */
2700                if (language[0])
2701                    av_dict_set(&st->metadata, "language", language, 0);
2702            }
2703        }
2704        break;
2705    case 0x6a: /* ac-3_descriptor */
2706        {
2707            int component_type_flag = get8(pp, desc_end) & (1 << 7);
2708            if (component_type_flag) {
2709                int component_type = get8(pp, desc_end);
2710                int service_type_mask = 0x38;  // 0b00111000
2711                int service_type = ((component_type & service_type_mask) >> 3);
2712                if (service_type == 0x02 /* 0b010 */) {
2713                    st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2714                    av_log(ts ? ts->stream : fc, AV_LOG_DEBUG, "New track disposition for id %u: %u\n", st->id, st->disposition);
2715                }
2716            }
2717        }
2718        break;
2719    case 0x7a: /* enhanced_ac-3_descriptor */
2720        {
2721            int component_type_flag = get8(pp, desc_end) & (1 << 7);
2722            if (component_type_flag) {
2723                int component_type = get8(pp, desc_end);
2724                int service_type_mask = 0x38;  // 0b00111000
2725                int service_type = ((component_type & service_type_mask) >> 3);
2726                if (service_type == 0x02 /* 0b010 */) {
2727                    st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2728                    av_log(ts ? ts->stream : fc, AV_LOG_DEBUG, "New track disposition for id %u: %u\n", st->id, st->disposition);
2729                }
2730            }
2731        }
2732        break;
2733#ifdef OHOS_DRM
2734    case DRM_DESCRIPTOR:
2735        {
2736            int ret;
2737            AV_DrmInfo drm_info;
2738            ret = mpegts_get_drm_info(*pp, desc_len, &drm_info);
2739            if (ret == 0) {
2740                AV_DrmCencInfo cenc_info;
2741                mpegts_avstream_set_drm_info(st, &drm_info);
2742                mpegts_get_cenc_info(*pp, desc_len, &cenc_info);
2743                mpegts_avstream_set_cenc_info(st, &cenc_info);
2744            }
2745        }
2746        break;
2747#endif
2748    case 0xfd: /* ARIB data coding type descriptor */
2749        // STD-B24, fascicle 3, chapter 4 defines private_stream_1
2750        // for captions
2751        if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
2752            // This structure is defined in STD-B10, part 1, listing 5.4 and
2753            // part 2, 6.2.20).
2754            // Listing of data_component_ids is in STD-B10, part 2, Annex J.
2755            // Component tag limits are documented in TR-B14, fascicle 2,
2756            // Vol. 3, Section 2, 4.2.8.1
2757            int actual_component_tag = sti->stream_identifier - 1;
2758            int picked_profile = FF_PROFILE_UNKNOWN;
2759            int data_component_id = get16(pp, desc_end);
2760            if (data_component_id < 0)
2761                return AVERROR_INVALIDDATA;
2762
2763            switch (data_component_id) {
2764            case 0x0008:
2765                // [0x30..0x37] are component tags utilized for
2766                // non-mobile captioning service ("profile A").
2767                if (actual_component_tag >= 0x30 &&
2768                    actual_component_tag <= 0x37) {
2769                    picked_profile = FF_PROFILE_ARIB_PROFILE_A;
2770                }
2771                break;
2772            case 0x0012:
2773                // component tag 0x87 signifies a mobile/partial reception
2774                // (1seg) captioning service ("profile C").
2775                if (actual_component_tag == 0x87) {
2776                    picked_profile = FF_PROFILE_ARIB_PROFILE_C;
2777                }
2778                break;
2779            default:
2780                break;
2781            }
2782
2783            if (picked_profile == FF_PROFILE_UNKNOWN)
2784                break;
2785
2786            st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
2787            st->codecpar->codec_id   = AV_CODEC_ID_ARIB_CAPTION;
2788            st->codecpar->profile    = picked_profile;
2789            sti->request_probe = 0;
2790        }
2791        break;
2792    case 0xb0: /* DOVI video stream descriptor */
2793        {
2794            uint32_t buf;
2795            AVDOVIDecoderConfigurationRecord *dovi;
2796            size_t dovi_size;
2797            int ret;
2798            int dependency_pid;
2799
2800            if (desc_end - *pp < 4) // (8 + 8 + 7 + 6 + 1 + 1 + 1) / 8
2801                return AVERROR_INVALIDDATA;
2802
2803            dovi = av_dovi_alloc(&dovi_size);
2804            if (!dovi)
2805                return AVERROR(ENOMEM);
2806
2807            dovi->dv_version_major = get8(pp, desc_end);
2808            dovi->dv_version_minor = get8(pp, desc_end);
2809            buf = get16(pp, desc_end);
2810            dovi->dv_profile        = (buf >> 9) & 0x7f;    // 7 bits
2811            dovi->dv_level          = (buf >> 3) & 0x3f;    // 6 bits
2812            dovi->rpu_present_flag  = (buf >> 2) & 0x01;    // 1 bit
2813            dovi->el_present_flag   = (buf >> 1) & 0x01;    // 1 bit
2814            dovi->bl_present_flag   =  buf       & 0x01;    // 1 bit
2815            if (!dovi->bl_present_flag && desc_end - *pp >= 2) {
2816                buf = get16(pp, desc_end);
2817                dependency_pid = buf >> 3; // 13 bits
2818            }
2819            if (desc_end - *pp >= 1) {  // 8 bits
2820                buf = get8(pp, desc_end);
2821                dovi->dv_bl_signal_compatibility_id = (buf >> 4) & 0x0f; // 4 bits
2822            } else {
2823                // 0 stands for None
2824                // Dolby Vision V1.2.93 profiles and levels
2825                dovi->dv_bl_signal_compatibility_id = 0;
2826            }
2827
2828            ret = av_stream_add_side_data(st, AV_PKT_DATA_DOVI_CONF,
2829                                          (uint8_t *)dovi, dovi_size);
2830            if (ret < 0) {
2831                av_free(dovi);
2832                return ret;
2833            }
2834
2835            av_log(fc, AV_LOG_TRACE, "DOVI, version: %d.%d, profile: %d, level: %d, "
2836                   "rpu flag: %d, el flag: %d, bl flag: %d, dependency_pid: %d, compatibility id: %d\n",
2837                   dovi->dv_version_major, dovi->dv_version_minor,
2838                   dovi->dv_profile, dovi->dv_level,
2839                   dovi->rpu_present_flag,
2840                   dovi->el_present_flag,
2841                   dovi->bl_present_flag,
2842                   dependency_pid,
2843                   dovi->dv_bl_signal_compatibility_id);
2844        }
2845        break;
2846    default:
2847        break;
2848    }
2849    *pp = desc_end;
2850    return 0;
2851}
2852
2853static AVStream *find_matching_stream(MpegTSContext *ts, int pid, unsigned int programid,
2854                                      int stream_identifier, int pmt_stream_idx, struct Program *p)
2855{
2856    AVFormatContext *s = ts->stream;
2857    AVStream *found = NULL;
2858
2859    if (stream_identifier) { /* match based on "stream identifier descriptor" if present */
2860        for (int i = 0; i < p->nb_streams; i++) {
2861            if (p->streams[i].stream_identifier == stream_identifier)
2862                if (!found || pmt_stream_idx == i) /* fallback to idx based guess if multiple streams have the same identifier */
2863                    found = s->streams[p->streams[i].idx];
2864        }
2865    } else if (pmt_stream_idx < p->nb_streams) { /* match based on position within the PMT */
2866        found = s->streams[p->streams[pmt_stream_idx].idx];
2867    }
2868
2869    if (found) {
2870        av_log(ts->stream, AV_LOG_VERBOSE,
2871               "re-using existing %s stream %d (pid=0x%x) for new pid=0x%x\n",
2872               av_get_media_type_string(found->codecpar->codec_type),
2873               found->index, found->id, pid);
2874    }
2875
2876    return found;
2877}
2878
2879static int parse_stream_identifier_desc(const uint8_t *p, const uint8_t *p_end)
2880{
2881    const uint8_t **pp = &p;
2882    const uint8_t *desc_list_end;
2883    const uint8_t *desc_end;
2884    int desc_list_len;
2885    int desc_len, desc_tag;
2886
2887    desc_list_len = get16(pp, p_end);
2888    if (desc_list_len < 0)
2889        return -1;
2890    desc_list_len &= 0xfff;
2891    desc_list_end  = p + desc_list_len;
2892    if (desc_list_end > p_end)
2893        return -1;
2894
2895    while (1) {
2896        desc_tag = get8(pp, desc_list_end);
2897        if (desc_tag < 0)
2898            return -1;
2899        desc_len = get8(pp, desc_list_end);
2900        if (desc_len < 0)
2901            return -1;
2902        desc_end = *pp + desc_len;
2903        if (desc_end > desc_list_end)
2904            return -1;
2905
2906        if (desc_tag == 0x52) {
2907            return get8(pp, desc_end);
2908        }
2909        *pp = desc_end;
2910    }
2911
2912    return -1;
2913}
2914
2915static int is_pes_stream(int stream_type, uint32_t prog_reg_desc)
2916{
2917    return !(stream_type == 0x13 ||
2918             (stream_type == 0x86 && prog_reg_desc == AV_RL32("CUEI")) );
2919}
2920
2921static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2922{
2923    MpegTSContext *ts = filter->u.section_filter.opaque;
2924    MpegTSSectionFilter *tssf = &filter->u.section_filter;
2925    struct Program old_program;
2926    SectionHeader h1, *h = &h1;
2927    PESContext *pes;
2928    AVStream *st;
2929    const uint8_t *p, *p_end, *desc_list_end;
2930    int program_info_length, pcr_pid, pid, stream_type;
2931    int desc_list_len;
2932    uint32_t prog_reg_desc = 0; /* registration descriptor */
2933    int stream_identifier = -1;
2934    struct Program *prg;
2935#ifdef OHOS_DRM
2936    AV_DrmInfo drm_info;
2937    AV_DrmCencInfo cenc_info;
2938#endif
2939
2940    int mp4_descr_count = 0;
2941    Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
2942    int i;
2943
2944    av_log(ts->stream, AV_LOG_TRACE, "PMT: len %i\n", section_len);
2945    hex_dump_debug(ts->stream, section, section_len);
2946
2947#ifdef OHOS_DRM
2948    memset(&drm_info, 0, sizeof(AV_DrmInfo));
2949    memset(&cenc_info, 0, sizeof(AV_DrmCencInfo));
2950#endif
2951
2952    p_end = section + section_len - 4;
2953    p = section;
2954    if (parse_section_header(h, &p, p_end) < 0)
2955        return;
2956    if (h->tid != PMT_TID)
2957        return;
2958    if (!h->current_next)
2959        return;
2960    if (skip_identical(h, tssf))
2961        return;
2962
2963    av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x sec_num=%d/%d version=%d tid=%d\n",
2964            h->id, h->sec_num, h->last_sec_num, h->version, h->tid);
2965
2966    if (!ts->scan_all_pmts && ts->skip_changes)
2967        return;
2968
2969    prg = get_program(ts, h->id);
2970    if (prg)
2971        old_program = *prg;
2972    else
2973        clear_program(&old_program);
2974
2975    if (ts->skip_unknown_pmt && !prg)
2976        return;
2977    if (prg && prg->nb_pids && prg->pids[0] != ts->current_pid)
2978        return;
2979    if (!ts->skip_clear)
2980        clear_avprogram(ts, h->id);
2981    clear_program(prg);
2982    add_pid_to_program(prg, ts->current_pid);
2983
2984    pcr_pid = get16(&p, p_end);
2985    if (pcr_pid < 0)
2986        return;
2987    pcr_pid &= 0x1fff;
2988    add_pid_to_program(prg, pcr_pid);
2989    update_av_program_info(ts->stream, h->id, pcr_pid, h->version);
2990
2991    av_log(ts->stream, AV_LOG_TRACE, "pcr_pid=0x%x\n", pcr_pid);
2992
2993    program_info_length = get16(&p, p_end);
2994    if (program_info_length < 0)
2995        return;
2996    program_info_length &= 0xfff;
2997    while (program_info_length >= 2) {
2998        uint8_t tag, len;
2999        tag = get8(&p, p_end);
3000        len = get8(&p, p_end);
3001
3002        av_log(ts->stream, AV_LOG_TRACE, "program tag: 0x%02x len=%d\n", tag, len);
3003
3004        program_info_length -= 2;
3005        if (len > program_info_length)
3006            // something else is broken, exit the program_descriptors_loop
3007            break;
3008        program_info_length -= len;
3009        if (tag == IOD_DESCRIPTOR) {
3010            get8(&p, p_end); // scope
3011            get8(&p, p_end); // label
3012            len -= 2;
3013            mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
3014                          &mp4_descr_count, MAX_MP4_DESCR_COUNT);
3015        } else if (tag == REGISTRATION_DESCRIPTOR && len >= 4) {
3016            prog_reg_desc = bytestream_get_le32(&p);
3017            len -= 4;
3018#ifdef OHOS_DRM
3019        } else if ((tag == DRM_DESCRIPTOR) && (len > DRM_MIN_DRM_INFO_LEN)) {
3020            int ret = mpegts_get_drm_info(p, (uint32_t)len, &drm_info);
3021            if (ret != 0) {
3022                memset(&drm_info, 0, sizeof(AV_DrmInfo));
3023                drm_info.pssh_len = 0;
3024                drm_info.uuid_len = 0;
3025            } else {
3026                mpegts_get_cenc_info(p, (uint32_t)len, &cenc_info);
3027            }
3028#endif
3029        }
3030        p += len;
3031    }
3032    p += program_info_length;
3033    if (p >= p_end)
3034        goto out;
3035
3036    // stop parsing after pmt, we found header
3037    if (!ts->pkt)
3038        ts->stop_parse = 2;
3039
3040    if (prg)
3041        prg->pmt_found = 1;
3042
3043    for (i = 0; i < MAX_STREAMS_PER_PROGRAM; i++) {
3044        st = 0;
3045        pes = NULL;
3046        stream_type = get8(&p, p_end);
3047        if (stream_type < 0)
3048            break;
3049        pid = get16(&p, p_end);
3050        if (pid < 0)
3051            goto out;
3052        pid &= 0x1fff;
3053        if (pid == ts->current_pid)
3054            goto out;
3055
3056        stream_identifier = parse_stream_identifier_desc(p, p_end) + 1;
3057
3058        /* now create stream */
3059        if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
3060            pes = ts->pids[pid]->u.pes_filter.opaque;
3061            if (ts->merge_pmt_versions && !pes->st) {
3062                st = find_matching_stream(ts, pid, h->id, stream_identifier, i, &old_program);
3063                if (st) {
3064                    pes->st = st;
3065                    pes->stream_type = stream_type;
3066                    pes->merged_st = 1;
3067                }
3068            }
3069            if (!pes->st) {
3070                pes->st = avformat_new_stream(pes->stream, NULL);
3071                if (!pes->st)
3072                    goto out;
3073                pes->st->id = pes->pid;
3074            }
3075            st = pes->st;
3076        } else if (is_pes_stream(stream_type, prog_reg_desc)) {
3077            if (ts->pids[pid])
3078                mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
3079            pes = add_pes_stream(ts, pid, pcr_pid);
3080            if (ts->merge_pmt_versions && pes && !pes->st) {
3081                st = find_matching_stream(ts, pid, h->id, stream_identifier, i, &old_program);
3082                if (st) {
3083                    pes->st = st;
3084                    pes->stream_type = stream_type;
3085                    pes->merged_st = 1;
3086                }
3087            }
3088            if (pes && !pes->st) {
3089                st = avformat_new_stream(pes->stream, NULL);
3090                if (!st)
3091                    goto out;
3092                st->id = pes->pid;
3093            }
3094        } else {
3095            int idx = ff_find_stream_index(ts->stream, pid);
3096            if (idx >= 0) {
3097                st = ts->stream->streams[idx];
3098            }
3099            if (ts->merge_pmt_versions && !st) {
3100                st = find_matching_stream(ts, pid, h->id, stream_identifier, i, &old_program);
3101            }
3102            if (!st) {
3103                st = avformat_new_stream(ts->stream, NULL);
3104                if (!st)
3105                    goto out;
3106                st->id = pid;
3107                st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
3108                if (stream_type == 0x86 && prog_reg_desc == AV_RL32("CUEI")) {
3109                    mpegts_find_stream_type(st, stream_type, SCTE_types);
3110                    mpegts_open_section_filter(ts, pid, scte_data_cb, ts, 1);
3111                }
3112            }
3113        }
3114
3115        if (!st)
3116            goto out;
3117
3118#ifdef OHOS_DRM
3119        if ((drm_info.pssh_len != 0) && (drm_info.uuid_len != 0)) {
3120            mpegts_avstream_set_drm_info(st, &drm_info);
3121            mpegts_avstream_set_cenc_info(st, &cenc_info);
3122        }
3123#endif
3124
3125        if (pes && !pes->stream_type)
3126            mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
3127
3128        add_pid_to_program(prg, pid);
3129        if (prg) {
3130            prg->streams[i].idx = st->index;
3131            prg->streams[i].stream_identifier = stream_identifier;
3132            prg->nb_streams++;
3133        }
3134
3135        av_program_add_stream_index(ts->stream, h->id, st->index);
3136
3137        desc_list_len = get16(&p, p_end);
3138        if (desc_list_len < 0)
3139            goto out;
3140        desc_list_len &= 0xfff;
3141        desc_list_end  = p + desc_list_len;
3142        if (desc_list_end > p_end)
3143            goto out;
3144        for (;;) {
3145            if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
3146                                          desc_list_end, mp4_descr,
3147                                          mp4_descr_count, pid, ts) < 0)
3148                break;
3149
3150            if (pes && prog_reg_desc == AV_RL32("HDMV") &&
3151                stream_type == 0x83 && pes->sub_st) {
3152                av_program_add_stream_index(ts->stream, h->id,
3153                                            pes->sub_st->index);
3154                pes->sub_st->codecpar->codec_tag = st->codecpar->codec_tag;
3155            }
3156        }
3157        p = desc_list_end;
3158    }
3159
3160    if (!ts->pids[pcr_pid])
3161        mpegts_open_pcr_filter(ts, pcr_pid);
3162
3163out:
3164    for (i = 0; i < mp4_descr_count; i++)
3165        av_free(mp4_descr[i].dec_config_descr);
3166}
3167
3168static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
3169{
3170    MpegTSContext *ts = filter->u.section_filter.opaque;
3171    MpegTSSectionFilter *tssf = &filter->u.section_filter;
3172    SectionHeader h1, *h = &h1;
3173    const uint8_t *p, *p_end;
3174    int sid, pmt_pid;
3175    int nb_prg = 0;
3176    AVProgram *program;
3177
3178    av_log(ts->stream, AV_LOG_TRACE, "PAT:\n");
3179    hex_dump_debug(ts->stream, section, section_len);
3180
3181    p_end = section + section_len - 4;
3182    p     = section;
3183    if (parse_section_header(h, &p, p_end) < 0)
3184        return;
3185    if (h->tid != PAT_TID)
3186        return;
3187    if (!h->current_next)
3188        return;
3189    if (ts->skip_changes)
3190        return;
3191
3192    if (skip_identical(h, tssf))
3193        return;
3194    ts->stream->ts_id = h->id;
3195
3196    for (;;) {
3197        sid = get16(&p, p_end);
3198        if (sid < 0)
3199            break;
3200        pmt_pid = get16(&p, p_end);
3201        if (pmt_pid < 0)
3202            break;
3203        pmt_pid &= 0x1fff;
3204
3205        if (pmt_pid == ts->current_pid)
3206            break;
3207
3208        av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
3209
3210        if (sid == 0x0000) {
3211            /* NIT info */
3212        } else {
3213            MpegTSFilter *fil = ts->pids[pmt_pid];
3214            struct Program *prg;
3215            program = av_new_program(ts->stream, sid);
3216            if (program) {
3217                program->program_num = sid;
3218                program->pmt_pid = pmt_pid;
3219            }
3220            if (fil)
3221                if (   fil->type != MPEGTS_SECTION
3222                    || fil->pid != pmt_pid
3223                    || fil->u.section_filter.section_cb != pmt_cb)
3224                    mpegts_close_filter(ts, ts->pids[pmt_pid]);
3225
3226            if (!ts->pids[pmt_pid])
3227                mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
3228            prg = add_program(ts, sid);
3229            if (prg) {
3230                unsigned prg_idx = prg - ts->prg;
3231                if (prg->nb_pids && prg->pids[0] != pmt_pid)
3232                    clear_program(prg);
3233                add_pid_to_program(prg, pmt_pid);
3234                if (prg_idx > nb_prg)
3235                    FFSWAP(struct Program, ts->prg[nb_prg], ts->prg[prg_idx]);
3236                if (prg_idx >= nb_prg)
3237                    nb_prg++;
3238            } else
3239                nb_prg = 0;
3240        }
3241    }
3242    ts->nb_prg = nb_prg;
3243
3244    if (sid < 0) {
3245        int i,j;
3246        for (j=0; j<ts->stream->nb_programs; j++) {
3247            for (i = 0; i < ts->nb_prg; i++)
3248                if (ts->prg[i].id == ts->stream->programs[j]->id)
3249                    break;
3250            if (i==ts->nb_prg && !ts->skip_clear)
3251                clear_avprogram(ts, ts->stream->programs[j]->id);
3252        }
3253    }
3254}
3255
3256static void eit_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
3257{
3258    MpegTSContext *ts = filter->u.section_filter.opaque;
3259    const uint8_t *p, *p_end;
3260    SectionHeader h1, *h = &h1;
3261
3262    /*
3263     * Sometimes we receive EPG packets but SDT table do not have
3264     * eit_pres_following or eit_sched turned on, so we open EPG
3265     * stream directly here.
3266     */
3267    if (!ts->epg_stream) {
3268        ts->epg_stream = avformat_new_stream(ts->stream, NULL);
3269        if (!ts->epg_stream)
3270            return;
3271        ts->epg_stream->id = EIT_PID;
3272        ts->epg_stream->codecpar->codec_type = AVMEDIA_TYPE_DATA;
3273        ts->epg_stream->codecpar->codec_id = AV_CODEC_ID_EPG;
3274    }
3275
3276    if (ts->epg_stream->discard == AVDISCARD_ALL)
3277        return;
3278
3279    p_end = section + section_len - 4;
3280    p     = section;
3281
3282    if (parse_section_header(h, &p, p_end) < 0)
3283        return;
3284    if (h->tid < EIT_TID || h->tid > OEITS_END_TID)
3285        return;
3286
3287    av_log(ts->stream, AV_LOG_TRACE, "EIT: tid received = %.02x\n", h->tid);
3288
3289    /**
3290     * Service_id 0xFFFF is reserved, it indicates that the current EIT table
3291     * is scrambled.
3292     */
3293    if (h->id == 0xFFFF) {
3294        av_log(ts->stream, AV_LOG_TRACE, "Scrambled EIT table received.\n");
3295        return;
3296    }
3297
3298    /**
3299     * In case we receive an EPG packet before mpegts context is fully
3300     * initialized.
3301     */
3302    if (!ts->pkt)
3303        return;
3304
3305    new_data_packet(section, section_len, ts->pkt);
3306    ts->pkt->stream_index = ts->epg_stream->index;
3307    ts->stop_parse = 1;
3308}
3309
3310static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
3311{
3312    MpegTSContext *ts = filter->u.section_filter.opaque;
3313    MpegTSSectionFilter *tssf = &filter->u.section_filter;
3314    SectionHeader h1, *h = &h1;
3315    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
3316    int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
3317    char *name, *provider_name;
3318
3319    av_log(ts->stream, AV_LOG_TRACE, "SDT:\n");
3320    hex_dump_debug(ts->stream, section, section_len);
3321
3322    p_end = section + section_len - 4;
3323    p     = section;
3324    if (parse_section_header(h, &p, p_end) < 0)
3325        return;
3326    if (h->tid != SDT_TID)
3327        return;
3328    if (!h->current_next)
3329        return;
3330    if (ts->skip_changes)
3331        return;
3332    if (skip_identical(h, tssf))
3333        return;
3334
3335    onid = get16(&p, p_end);
3336    if (onid < 0)
3337        return;
3338    val = get8(&p, p_end);
3339    if (val < 0)
3340        return;
3341    for (;;) {
3342        sid = get16(&p, p_end);
3343        if (sid < 0)
3344            break;
3345        val = get8(&p, p_end);
3346        if (val < 0)
3347            break;
3348        desc_list_len = get16(&p, p_end);
3349        if (desc_list_len < 0)
3350            break;
3351        desc_list_len &= 0xfff;
3352        desc_list_end  = p + desc_list_len;
3353        if (desc_list_end > p_end)
3354            break;
3355        for (;;) {
3356            desc_tag = get8(&p, desc_list_end);
3357            if (desc_tag < 0)
3358                break;
3359            desc_len = get8(&p, desc_list_end);
3360            desc_end = p + desc_len;
3361            if (desc_len < 0 || desc_end > desc_list_end)
3362                break;
3363
3364            av_log(ts->stream, AV_LOG_TRACE, "tag: 0x%02x len=%d\n",
3365                    desc_tag, desc_len);
3366
3367            switch (desc_tag) {
3368            case 0x48:
3369                service_type = get8(&p, desc_end);
3370                if (service_type < 0)
3371                    break;
3372                provider_name = getstr8(&p, desc_end);
3373                if (!provider_name)
3374                    break;
3375                name = getstr8(&p, desc_end);
3376                if (name) {
3377                    AVProgram *program = av_new_program(ts->stream, sid);
3378                    if (program) {
3379                        av_dict_set(&program->metadata, "service_name", name, 0);
3380                        av_dict_set(&program->metadata, "service_provider",
3381                                    provider_name, 0);
3382                    }
3383                }
3384                av_free(name);
3385                av_free(provider_name);
3386                break;
3387            default:
3388                break;
3389            }
3390            p = desc_end;
3391        }
3392        p = desc_list_end;
3393    }
3394}
3395
3396static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
3397                     const uint8_t *packet);
3398
3399/* handle one TS packet */
3400static int handle_packet(MpegTSContext *ts, const uint8_t *packet, int64_t pos)
3401{
3402    MpegTSFilter *tss;
3403    int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
3404        has_adaptation, has_payload;
3405    const uint8_t *p, *p_end;
3406
3407    pid = AV_RB16(packet + 1) & 0x1fff;
3408    is_start = packet[1] & 0x40;
3409    tss = ts->pids[pid];
3410    if (ts->auto_guess && !tss && is_start) {
3411        add_pes_stream(ts, pid, -1);
3412        tss = ts->pids[pid];
3413    }
3414    if (!tss)
3415        return 0;
3416    if (is_start)
3417        tss->discard = discard_pid(ts, pid);
3418    if (tss->discard)
3419        return 0;
3420    ts->current_pid = pid;
3421
3422    afc = (packet[3] >> 4) & 3;
3423    if (afc == 0) /* reserved value */
3424        return 0;
3425    has_adaptation   = afc & 2;
3426    has_payload      = afc & 1;
3427    is_discontinuity = has_adaptation &&
3428                       packet[4] != 0 && /* with length > 0 */
3429                       (packet[5] & 0x80); /* and discontinuity indicated */
3430
3431    /* continuity check (currently not used) */
3432    cc = (packet[3] & 0xf);
3433    expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
3434    cc_ok = pid == 0x1FFF || // null packet PID
3435            is_discontinuity ||
3436            tss->last_cc < 0 ||
3437            expected_cc == cc;
3438
3439    tss->last_cc = cc;
3440    if (!cc_ok) {
3441        av_log(ts->stream, AV_LOG_DEBUG,
3442               "Continuity check failed for pid %d expected %d got %d\n",
3443               pid, expected_cc, cc);
3444        if (tss->type == MPEGTS_PES) {
3445            PESContext *pc = tss->u.pes_filter.opaque;
3446            pc->flags |= AV_PKT_FLAG_CORRUPT;
3447        }
3448    }
3449
3450    if (packet[1] & 0x80) {
3451        av_log(ts->stream, AV_LOG_DEBUG, "Packet had TEI flag set; marking as corrupt\n");
3452        if (tss->type == MPEGTS_PES) {
3453            PESContext *pc = tss->u.pes_filter.opaque;
3454            pc->flags |= AV_PKT_FLAG_CORRUPT;
3455        }
3456    }
3457
3458    p = packet + 4;
3459    if (has_adaptation) {
3460        int64_t pcr_h;
3461        int pcr_l;
3462        if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
3463            tss->last_pcr = pcr_h * 300 + pcr_l;
3464        /* skip adaptation field */
3465        p += p[0] + 1;
3466    }
3467    /* if past the end of packet, ignore */
3468    p_end = packet + TS_PACKET_SIZE;
3469    if (p >= p_end || !has_payload)
3470        return 0;
3471
3472    if (pos >= 0) {
3473        av_assert0(pos >= TS_PACKET_SIZE);
3474        ts->pos47_full = pos - TS_PACKET_SIZE;
3475    }
3476
3477    if (tss->type == MPEGTS_SECTION) {
3478        if (is_start) {
3479            /* pointer field present */
3480            len = *p++;
3481            if (len > p_end - p)
3482                return 0;
3483            if (len && cc_ok) {
3484                /* write remaining section bytes */
3485                write_section_data(ts, tss,
3486                                   p, len, 0);
3487                /* check whether filter has been closed */
3488                if (!ts->pids[pid])
3489                    return 0;
3490            }
3491            p += len;
3492            if (p < p_end) {
3493                write_section_data(ts, tss,
3494                                   p, p_end - p, 1);
3495            }
3496        } else {
3497            if (cc_ok) {
3498                write_section_data(ts, tss,
3499                                   p, p_end - p, 0);
3500            }
3501        }
3502
3503        // stop find_stream_info from waiting for more streams
3504        // when all programs have received a PMT
3505        if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER && ts->scan_all_pmts <= 0) {
3506            int i;
3507            for (i = 0; i < ts->nb_prg; i++) {
3508                if (!ts->prg[i].pmt_found)
3509                    break;
3510            }
3511            if (i == ts->nb_prg && ts->nb_prg > 0) {
3512                av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
3513                ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
3514            }
3515        }
3516
3517    } else {
3518        int ret;
3519        // Note: The position here points actually behind the current packet.
3520        if (tss->type == MPEGTS_PES) {
3521            if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
3522                                                pos - ts->raw_packet_size)) < 0)
3523                return ret;
3524        }
3525    }
3526
3527    return 0;
3528}
3529
3530static int mpegts_resync(AVFormatContext *s, int seekback, const uint8_t *current_packet)
3531{
3532    MpegTSContext *ts = s->priv_data;
3533    AVIOContext *pb = s->pb;
3534    int c, i;
3535    uint64_t pos = avio_tell(pb);
3536    int64_t back = FFMIN(seekback, pos);
3537
3538    //Special case for files like 01c56b0dc1.ts
3539    if (current_packet[0] == 0x80 && current_packet[12] == 0x47 && pos >= TS_PACKET_SIZE) {
3540        avio_seek(pb, 12 - TS_PACKET_SIZE, SEEK_CUR);
3541        return 0;
3542    }
3543
3544    avio_seek(pb, -back, SEEK_CUR);
3545
3546    for (i = 0; i < ts->resync_size; i++) {
3547        c = avio_r8(pb);
3548        if (avio_feof(pb))
3549            return AVERROR_EOF;
3550        if (c == 0x47) {
3551            int new_packet_size, ret;
3552            avio_seek(pb, -1, SEEK_CUR);
3553            pos = avio_tell(pb);
3554            ret = ffio_ensure_seekback(pb, PROBE_PACKET_MAX_BUF);
3555            if (ret < 0)
3556                return ret;
3557            new_packet_size = get_packet_size(s);
3558            if (new_packet_size > 0 && new_packet_size != ts->raw_packet_size) {
3559                av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", new_packet_size);
3560                ts->raw_packet_size = new_packet_size;
3561            }
3562            avio_seek(pb, pos, SEEK_SET);
3563            return 0;
3564        }
3565    }
3566    av_log(s, AV_LOG_ERROR,
3567           "max resync size reached, could not find sync byte\n");
3568    /* no sync found */
3569    return AVERROR_INVALIDDATA;
3570}
3571
3572/* return AVERROR_something if error or EOF. Return 0 if OK. */
3573static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
3574                       const uint8_t **data)
3575{
3576    AVIOContext *pb = s->pb;
3577    int len;
3578
3579    for (;;) {
3580        len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
3581        if (len != TS_PACKET_SIZE)
3582            return len < 0 ? len : AVERROR_EOF;
3583        /* check packet sync byte */
3584        if ((*data)[0] != 0x47) {
3585            /* find a new packet start */
3586
3587            if (mpegts_resync(s, raw_packet_size, *data) < 0)
3588                return AVERROR(EAGAIN);
3589            else
3590                continue;
3591        } else {
3592            break;
3593        }
3594    }
3595    return 0;
3596}
3597
3598static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
3599{
3600    AVIOContext *pb = s->pb;
3601    int skip = raw_packet_size - TS_PACKET_SIZE;
3602    if (skip > 0)
3603        avio_skip(pb, skip);
3604}
3605
3606static int handle_packets(MpegTSContext *ts, int64_t nb_packets)
3607{
3608    AVFormatContext *s = ts->stream;
3609    uint8_t packet[TS_PACKET_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
3610    const uint8_t *data;
3611    int64_t packet_num;
3612    int ret = 0;
3613
3614    if (avio_tell(s->pb) != ts->last_pos) {
3615        int i;
3616        av_log(ts->stream, AV_LOG_TRACE, "Skipping after seek\n");
3617        /* seek detected, flush pes buffer */
3618        for (i = 0; i < NB_PID_MAX; i++) {
3619            if (ts->pids[i]) {
3620                if (ts->pids[i]->type == MPEGTS_PES) {
3621                    PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
3622                    av_buffer_unref(&pes->buffer);
3623                    pes->data_index = 0;
3624                    pes->state = MPEGTS_SKIP; /* skip until pes header */
3625                } else if (ts->pids[i]->type == MPEGTS_SECTION) {
3626                    ts->pids[i]->u.section_filter.last_ver = -1;
3627                }
3628                ts->pids[i]->last_cc = -1;
3629                ts->pids[i]->last_pcr = -1;
3630            }
3631        }
3632    }
3633
3634    ts->stop_parse = 0;
3635    packet_num = 0;
3636    memset(packet + TS_PACKET_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
3637    for (;;) {
3638        packet_num++;
3639        if (nb_packets != 0 && packet_num >= nb_packets ||
3640            ts->stop_parse > 1) {
3641            ret = AVERROR(EAGAIN);
3642            break;
3643        }
3644        if (ts->stop_parse > 0)
3645            break;
3646
3647        ret = read_packet(s, packet, ts->raw_packet_size, &data);
3648        if (ret != 0)
3649            break;
3650        ret = handle_packet(ts, data, avio_tell(s->pb));
3651        finished_reading_packet(s, ts->raw_packet_size);
3652        if (ret != 0)
3653            break;
3654    }
3655    ts->last_pos = avio_tell(s->pb);
3656    return ret;
3657}
3658
3659static int mpegts_probe(const AVProbeData *p)
3660{
3661    const int size = p->buf_size;
3662    int maxscore = 0;
3663    int sumscore = 0;
3664    int i;
3665    int check_count = size / TS_FEC_PACKET_SIZE;
3666#define CHECK_COUNT 10
3667#define CHECK_BLOCK 100
3668
3669    if (!check_count)
3670        return 0;
3671
3672    for (i = 0; i<check_count; i+=CHECK_BLOCK) {
3673        int left = FFMIN(check_count - i, CHECK_BLOCK);
3674        int score      = analyze(p->buf + TS_PACKET_SIZE     *i, TS_PACKET_SIZE     *left, TS_PACKET_SIZE     , 1);
3675        int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, 1);
3676        int fec_score  = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , 1);
3677        score = FFMAX3(score, dvhs_score, fec_score);
3678        sumscore += score;
3679        maxscore = FFMAX(maxscore, score);
3680    }
3681
3682    sumscore = sumscore * CHECK_COUNT / check_count;
3683    maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;
3684
3685    ff_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
3686
3687    if        (check_count > CHECK_COUNT && sumscore > 6) {
3688        return AVPROBE_SCORE_MAX   + sumscore - CHECK_COUNT;
3689    } else if (check_count >= CHECK_COUNT && sumscore > 6) {
3690        return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
3691    } else if (check_count >= CHECK_COUNT && maxscore > 6) {
3692        return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
3693    } else if (sumscore > 6) {
3694        return 2;
3695    } else {
3696        return 0;
3697    }
3698}
3699
3700/* return the 90kHz PCR and the extension for the 27MHz PCR. return
3701 * (-1) if not available */
3702static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
3703{
3704    int afc, len, flags;
3705    const uint8_t *p;
3706    unsigned int v;
3707
3708    afc = (packet[3] >> 4) & 3;
3709    if (afc <= 1)
3710        return AVERROR_INVALIDDATA;
3711    p   = packet + 4;
3712    len = p[0];
3713    p++;
3714    if (len == 0)
3715        return AVERROR_INVALIDDATA;
3716    flags = *p++;
3717    len--;
3718    if (!(flags & 0x10))
3719        return AVERROR_INVALIDDATA;
3720    if (len < 6)
3721        return AVERROR_INVALIDDATA;
3722    v          = AV_RB32(p);
3723    *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
3724    *ppcr_low  = ((p[4] & 1) << 8) | p[5];
3725    return 0;
3726}
3727
3728static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
3729
3730    /* NOTE: We attempt to seek on non-seekable files as well, as the
3731     * probe buffer usually is big enough. Only warn if the seek failed
3732     * on files where the seek should work. */
3733    if (avio_seek(pb, pos, SEEK_SET) < 0)
3734        av_log(s, (pb->seekable & AVIO_SEEKABLE_NORMAL) ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
3735}
3736
3737static int mpegts_read_header(AVFormatContext *s)
3738{
3739    MpegTSContext *ts = s->priv_data;
3740    AVIOContext *pb   = s->pb;
3741    int64_t pos, probesize = s->probesize;
3742    int64_t seekback = FFMAX(s->probesize, (int64_t)ts->resync_size + PROBE_PACKET_MAX_BUF);
3743
3744    ffformatcontext(s)->prefer_codec_framerate = 1;
3745
3746    if (ffio_ensure_seekback(pb, seekback) < 0)
3747        av_log(s, AV_LOG_WARNING, "Failed to allocate buffers for seekback\n");
3748
3749    pos = avio_tell(pb);
3750    ts->raw_packet_size = get_packet_size(s);
3751    if (ts->raw_packet_size <= 0) {
3752        av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
3753        ts->raw_packet_size = TS_PACKET_SIZE;
3754    }
3755    ts->stream     = s;
3756    ts->auto_guess = 0;
3757
3758    if (s->iformat == &ff_mpegts_demuxer) {
3759        /* normal demux */
3760
3761        /* first do a scan to get all the services */
3762        seek_back(s, pb, pos);
3763
3764        mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
3765        mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
3766        mpegts_open_section_filter(ts, EIT_PID, eit_cb, ts, 1);
3767
3768        handle_packets(ts, probesize / ts->raw_packet_size);
3769        /* if could not find service, enable auto_guess */
3770
3771        ts->auto_guess = 1;
3772
3773        av_log(ts->stream, AV_LOG_TRACE, "tuning done\n");
3774
3775        s->ctx_flags |= AVFMTCTX_NOHEADER;
3776    } else {
3777        AVStream *st;
3778        int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
3779        int64_t pcrs[2], pcr_h;
3780        uint8_t packet[TS_PACKET_SIZE];
3781        const uint8_t *data;
3782
3783        /* only read packets */
3784
3785        st = avformat_new_stream(s, NULL);
3786        if (!st)
3787            return AVERROR(ENOMEM);
3788        avpriv_set_pts_info(st, 60, 1, 27000000);
3789        st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
3790        st->codecpar->codec_id   = AV_CODEC_ID_MPEG2TS;
3791
3792        /* we iterate until we find two PCRs to estimate the bitrate */
3793        pcr_pid    = -1;
3794        nb_pcrs    = 0;
3795        nb_packets = 0;
3796        for (;;) {
3797            ret = read_packet(s, packet, ts->raw_packet_size, &data);
3798            if (ret < 0)
3799                return ret;
3800            pid = AV_RB16(data + 1) & 0x1fff;
3801            if ((pcr_pid == -1 || pcr_pid == pid) &&
3802                parse_pcr(&pcr_h, &pcr_l, data) == 0) {
3803                finished_reading_packet(s, ts->raw_packet_size);
3804                pcr_pid = pid;
3805                pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
3806                nb_pcrs++;
3807                if (nb_pcrs >= 2) {
3808                    if (pcrs[1] - pcrs[0] > 0) {
3809                        /* the difference needs to be positive to make sense for bitrate computation */
3810                        break;
3811                    } else {
3812                        av_log(ts->stream, AV_LOG_WARNING, "invalid pcr pair %"PRId64" >= %"PRId64"\n", pcrs[0], pcrs[1]);
3813                        pcrs[0] = pcrs[1];
3814                        nb_pcrs--;
3815                    }
3816                }
3817            } else {
3818                finished_reading_packet(s, ts->raw_packet_size);
3819            }
3820            nb_packets++;
3821        }
3822
3823        /* NOTE1: the bitrate is computed without the FEC */
3824        /* NOTE2: it is only the bitrate of the start of the stream */
3825        ts->pcr_incr = pcrs[1] - pcrs[0];
3826        ts->cur_pcr  = pcrs[0] - ts->pcr_incr * (nb_packets - 1);
3827        s->bit_rate  = TS_PACKET_SIZE * 8 * 27000000LL / ts->pcr_incr;
3828        st->codecpar->bit_rate = s->bit_rate;
3829        st->start_time      = ts->cur_pcr;
3830        av_log(ts->stream, AV_LOG_TRACE, "start=%0.3f pcr=%0.3f incr=%"PRId64"\n",
3831                st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
3832    }
3833
3834    seek_back(s, pb, pos);
3835    return 0;
3836}
3837
3838#define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
3839
3840static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
3841{
3842    MpegTSContext *ts = s->priv_data;
3843    int ret, i;
3844    int64_t pcr_h, next_pcr_h, pos;
3845    int pcr_l, next_pcr_l;
3846    uint8_t pcr_buf[12];
3847    const uint8_t *data;
3848
3849    if ((ret = av_new_packet(pkt, TS_PACKET_SIZE)) < 0)
3850        return ret;
3851    ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
3852    pkt->pos = avio_tell(s->pb);
3853    if (ret < 0) {
3854        return ret;
3855    }
3856    if (data != pkt->data)
3857        memcpy(pkt->data, data, TS_PACKET_SIZE);
3858    finished_reading_packet(s, ts->raw_packet_size);
3859    if (ts->mpeg2ts_compute_pcr) {
3860        /* compute exact PCR for each packet */
3861        if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
3862            /* we read the next PCR (XXX: optimize it by using a bigger buffer */
3863            pos = avio_tell(s->pb);
3864            for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
3865                avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
3866                avio_read(s->pb, pcr_buf, 12);
3867                if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
3868                    /* XXX: not precise enough */
3869                    ts->pcr_incr =
3870                        ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
3871                        (i + 1);
3872                    break;
3873                }
3874            }
3875            avio_seek(s->pb, pos, SEEK_SET);
3876            /* no next PCR found: we use previous increment */
3877            ts->cur_pcr = pcr_h * 300 + pcr_l;
3878        }
3879        pkt->pts      = ts->cur_pcr;
3880        pkt->duration = ts->pcr_incr;
3881        ts->cur_pcr  += ts->pcr_incr;
3882    }
3883    pkt->stream_index = 0;
3884    return 0;
3885}
3886
3887static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
3888{
3889    MpegTSContext *ts = s->priv_data;
3890    int ret, i;
3891
3892    pkt->size = -1;
3893    ts->pkt = pkt;
3894    ret = handle_packets(ts, 0);
3895    if (ret < 0) {
3896        av_packet_unref(ts->pkt);
3897        /* flush pes data left */
3898        for (i = 0; i < NB_PID_MAX; i++)
3899            if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
3900                PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
3901                if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
3902                    ret = new_pes_packet(pes, pkt);
3903                    if (ret < 0)
3904                        return ret;
3905                    pes->state = MPEGTS_SKIP;
3906                    ret = 0;
3907                    break;
3908                }
3909            }
3910    }
3911
3912#ifdef OHOS_DRM
3913    if (!ret && pkt->size < 0) {
3914        ret = AVERROR_INVALIDDATA;
3915        return ret;
3916    }
3917    mpegts_packet_add_cenc_info(s, pkt);
3918#else
3919    if (!ret && pkt->size < 0)
3920        ret = AVERROR_INVALIDDATA;
3921#endif
3922    return ret;
3923}
3924
3925static void mpegts_free(MpegTSContext *ts)
3926{
3927    int i;
3928
3929    clear_programs(ts);
3930
3931    for (i = 0; i < FF_ARRAY_ELEMS(ts->pools); i++)
3932        av_buffer_pool_uninit(&ts->pools[i]);
3933
3934    for (i = 0; i < NB_PID_MAX; i++)
3935        if (ts->pids[i])
3936            mpegts_close_filter(ts, ts->pids[i]);
3937}
3938
3939static int mpegts_read_close(AVFormatContext *s)
3940{
3941    MpegTSContext *ts = s->priv_data;
3942    mpegts_free(ts);
3943    return 0;
3944}
3945
3946static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
3947                              int64_t *ppos, int64_t pos_limit)
3948{
3949    MpegTSContext *ts = s->priv_data;
3950    int64_t pos, timestamp;
3951    uint8_t buf[TS_PACKET_SIZE];
3952    int pcr_l, pcr_pid =
3953        ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
3954    int pos47 = ts->pos47_full % ts->raw_packet_size;
3955    pos =
3956        ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
3957        ts->raw_packet_size + pos47;
3958    while(pos < pos_limit) {
3959        if (avio_seek(s->pb, pos, SEEK_SET) < 0)
3960            return AV_NOPTS_VALUE;
3961        if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
3962            return AV_NOPTS_VALUE;
3963        if (buf[0] != 0x47) {
3964            if (mpegts_resync(s, TS_PACKET_SIZE, buf) < 0)
3965                return AV_NOPTS_VALUE;
3966            pos = avio_tell(s->pb);
3967            continue;
3968        }
3969        if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
3970            parse_pcr(&timestamp, &pcr_l, buf) == 0) {
3971            *ppos = pos;
3972            return timestamp;
3973        }
3974        pos += ts->raw_packet_size;
3975    }
3976
3977    return AV_NOPTS_VALUE;
3978}
3979
3980static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
3981                              int64_t *ppos, int64_t pos_limit)
3982{
3983    MpegTSContext *ts = s->priv_data;
3984    AVPacket *pkt;
3985    int64_t pos;
3986    int pos47 = ts->pos47_full % ts->raw_packet_size;
3987    pos = ((*ppos  + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
3988    ff_read_frame_flush(s);
3989    if (avio_seek(s->pb, pos, SEEK_SET) < 0)
3990        return AV_NOPTS_VALUE;
3991    pkt = av_packet_alloc();
3992    if (!pkt)
3993        return AV_NOPTS_VALUE;
3994    while(pos < pos_limit) {
3995        int ret = av_read_frame(s, pkt);
3996        if (ret < 0) {
3997            av_packet_free(&pkt);
3998            return AV_NOPTS_VALUE;
3999        }
4000        if (pkt->dts != AV_NOPTS_VALUE && pkt->pos >= 0) {
4001            ff_reduce_index(s, pkt->stream_index);
4002            av_add_index_entry(s->streams[pkt->stream_index], pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
4003            if (pkt->stream_index == stream_index && pkt->pos >= *ppos) {
4004                int64_t dts = pkt->dts;
4005                *ppos = pkt->pos;
4006                av_packet_free(&pkt);
4007                return dts;
4008            }
4009        }
4010        pos = pkt->pos;
4011        av_packet_unref(pkt);
4012    }
4013
4014    av_packet_free(&pkt);
4015    return AV_NOPTS_VALUE;
4016}
4017
4018/**************************************************************/
4019/* parsing functions - called from other demuxers such as RTP */
4020
4021MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s)
4022{
4023    MpegTSContext *ts;
4024
4025    ts = av_mallocz(sizeof(MpegTSContext));
4026    if (!ts)
4027        return NULL;
4028    /* no stream case, currently used by RTP */
4029    ts->raw_packet_size = TS_PACKET_SIZE;
4030    ts->max_packet_size = 2048000;
4031    ts->stream = s;
4032    ts->auto_guess = 1;
4033
4034    mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
4035    mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
4036    mpegts_open_section_filter(ts, EIT_PID, eit_cb, ts, 1);
4037
4038    return ts;
4039}
4040
4041/* return the consumed length if a packet was output, or -1 if no
4042 * packet is output */
4043int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
4044                               const uint8_t *buf, int len)
4045{
4046    int len1;
4047
4048    len1 = len;
4049    ts->pkt = pkt;
4050    for (;;) {
4051        ts->stop_parse = 0;
4052        if (len < TS_PACKET_SIZE)
4053            return AVERROR_INVALIDDATA;
4054        if (buf[0] != 0x47) {
4055            buf++;
4056            len--;
4057        } else {
4058            handle_packet(ts, buf, len1 - len + TS_PACKET_SIZE);
4059            buf += TS_PACKET_SIZE;
4060            len -= TS_PACKET_SIZE;
4061            if (ts->stop_parse == 1)
4062                break;
4063        }
4064    }
4065    return len1 - len;
4066}
4067
4068void avpriv_mpegts_parse_close(MpegTSContext *ts)
4069{
4070    mpegts_free(ts);
4071    av_free(ts);
4072}
4073
4074const AVInputFormat ff_mpegts_demuxer = {
4075    .name           = "mpegts",
4076    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
4077    .priv_data_size = sizeof(MpegTSContext),
4078    .read_probe     = mpegts_probe,
4079    .read_header    = mpegts_read_header,
4080    .read_packet    = mpegts_read_packet,
4081    .read_close     = mpegts_read_close,
4082    .read_timestamp = mpegts_get_dts,
4083    .flags          = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
4084    .priv_class     = &mpegts_class,
4085};
4086
4087const AVInputFormat ff_mpegtsraw_demuxer = {
4088    .name           = "mpegtsraw",
4089    .long_name      = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
4090    .priv_data_size = sizeof(MpegTSContext),
4091    .read_header    = mpegts_read_header,
4092    .read_packet    = mpegts_raw_read_packet,
4093    .read_close     = mpegts_read_close,
4094    .read_timestamp = mpegts_get_dts,
4095    .flags          = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
4096    .priv_class     = &mpegtsraw_class,
4097};
4098