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