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