mpegts.c 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463
  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. #include "config_components.h"
  22. #include "libavutil/buffer.h"
  23. #include "libavutil/crc.h"
  24. #include "libavutil/internal.h"
  25. #include "libavutil/intreadwrite.h"
  26. #include "libavutil/log.h"
  27. #include "libavutil/dict.h"
  28. #include "libavutil/mem.h"
  29. #include "libavutil/opt.h"
  30. #include "libavutil/avassert.h"
  31. #include "libavutil/dovi_meta.h"
  32. #include "libavcodec/bytestream.h"
  33. #include "libavcodec/defs.h"
  34. #include "libavcodec/get_bits.h"
  35. #include "libavcodec/opus/opus.h"
  36. #include "avformat.h"
  37. #include "mpegts.h"
  38. #include "internal.h"
  39. #include "avio_internal.h"
  40. #include "demux.h"
  41. #include "mpeg.h"
  42. #include "isom.h"
  43. #if CONFIG_ICONV
  44. #include <iconv.h>
  45. #endif
  46. /* maximum size in which we look for synchronization if
  47. * synchronization is lost */
  48. #define MAX_RESYNC_SIZE 65536
  49. #define MAX_MP4_DESCR_COUNT 16
  50. #define MOD_UNLIKELY(modulus, dividend, divisor, prev_dividend) \
  51. do { \
  52. if ((prev_dividend) == 0 || (dividend) - (prev_dividend) != (divisor)) \
  53. (modulus) = (dividend) % (divisor); \
  54. (prev_dividend) = (dividend); \
  55. } while (0)
  56. #define PROBE_PACKET_MAX_BUF 8192
  57. #define PROBE_PACKET_MARGIN 5
  58. enum MpegTSFilterType {
  59. MPEGTS_PES,
  60. MPEGTS_SECTION,
  61. MPEGTS_PCR,
  62. };
  63. typedef struct MpegTSFilter MpegTSFilter;
  64. typedef int PESCallback (MpegTSFilter *f, const uint8_t *buf, int len,
  65. int is_start, int64_t pos);
  66. typedef struct MpegTSPESFilter {
  67. PESCallback *pes_cb;
  68. void *opaque;
  69. } MpegTSPESFilter;
  70. typedef void SectionCallback (MpegTSFilter *f, const uint8_t *buf, int len);
  71. typedef void SetServiceCallback (void *opaque, int ret);
  72. typedef struct MpegTSSectionFilter {
  73. int section_index;
  74. int section_h_size;
  75. int last_ver;
  76. unsigned crc;
  77. unsigned last_crc;
  78. uint8_t *section_buf;
  79. unsigned int check_crc : 1;
  80. unsigned int end_of_section_reached : 1;
  81. SectionCallback *section_cb;
  82. void *opaque;
  83. } MpegTSSectionFilter;
  84. struct MpegTSFilter {
  85. int pid;
  86. int es_id;
  87. int last_cc; /* last cc code (-1 if first packet) */
  88. int64_t last_pcr;
  89. int discard;
  90. enum MpegTSFilterType type;
  91. union {
  92. MpegTSPESFilter pes_filter;
  93. MpegTSSectionFilter section_filter;
  94. } u;
  95. };
  96. struct Stream {
  97. int idx;
  98. int stream_identifier;
  99. };
  100. #define MAX_STREAMS_PER_PROGRAM 128
  101. #define MAX_PIDS_PER_PROGRAM (MAX_STREAMS_PER_PROGRAM + 2)
  102. struct Program {
  103. unsigned int id; // program id/service id
  104. unsigned int nb_pids;
  105. unsigned int pids[MAX_PIDS_PER_PROGRAM];
  106. unsigned int nb_streams;
  107. struct Stream streams[MAX_STREAMS_PER_PROGRAM];
  108. /** have we found pmt for this program */
  109. int pmt_found;
  110. };
  111. struct MpegTSContext {
  112. const AVClass *class;
  113. /* user data */
  114. AVFormatContext *stream;
  115. /** raw packet size, including FEC if present */
  116. int raw_packet_size;
  117. int64_t pos47_full;
  118. /** if true, all pids are analyzed to find streams */
  119. int auto_guess;
  120. /** compute exact PCR for each transport stream packet */
  121. int mpeg2ts_compute_pcr;
  122. /** fix dvb teletext pts */
  123. int fix_teletext_pts;
  124. int64_t cur_pcr; /**< used to estimate the exact PCR */
  125. int64_t pcr_incr; /**< used to estimate the exact PCR */
  126. /* data needed to handle file based ts */
  127. /** stop parsing loop */
  128. int stop_parse;
  129. /** packet containing Audio/Video data */
  130. AVPacket *pkt;
  131. /** to detect seek */
  132. int64_t last_pos;
  133. int skip_changes;
  134. int skip_clear;
  135. int skip_unknown_pmt;
  136. int scan_all_pmts;
  137. int resync_size;
  138. int merge_pmt_versions;
  139. int max_packet_size;
  140. int id;
  141. /******************************************/
  142. /* private mpegts data */
  143. /* scan context */
  144. /** structure to keep track of Program->pids mapping */
  145. unsigned int nb_prg;
  146. struct Program *prg;
  147. int8_t crc_validity[NB_PID_MAX];
  148. /** filters for various streams specified by PMT + for the PAT and PMT */
  149. MpegTSFilter *pids[NB_PID_MAX];
  150. int current_pid;
  151. AVStream *epg_stream;
  152. AVBufferPool* pools[32];
  153. };
  154. #define MPEGTS_OPTIONS \
  155. { "resync_size", "set size limit for looking up a new synchronization", \
  156. offsetof(MpegTSContext, resync_size), AV_OPT_TYPE_INT, \
  157. { .i64 = MAX_RESYNC_SIZE}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM }, \
  158. { "ts_id", "transport stream id", \
  159. offsetof(MpegTSContext, id), AV_OPT_TYPE_INT, \
  160. { .i64 = 0 }, 0, INT_MAX, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY }, \
  161. { "ts_packetsize", "output option carrying the raw packet size", \
  162. offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT, \
  163. { .i64 = 0 }, 0, INT_MAX, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY }
  164. static const AVOption options[] = {
  165. MPEGTS_OPTIONS,
  166. {"fix_teletext_pts", "try to fix pts values of dvb teletext streams", offsetof(MpegTSContext, fix_teletext_pts), AV_OPT_TYPE_BOOL,
  167. {.i64 = 1}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
  168. {"scan_all_pmts", "scan and combine all PMTs", offsetof(MpegTSContext, scan_all_pmts), AV_OPT_TYPE_BOOL,
  169. {.i64 = -1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM },
  170. {"skip_unknown_pmt", "skip PMTs for programs not advertised in the PAT", offsetof(MpegTSContext, skip_unknown_pmt), AV_OPT_TYPE_BOOL,
  171. {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
  172. {"merge_pmt_versions", "re-use streams when PMT's version/pids change", offsetof(MpegTSContext, merge_pmt_versions), AV_OPT_TYPE_BOOL,
  173. {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
  174. {"skip_changes", "skip changing / adding streams / programs", offsetof(MpegTSContext, skip_changes), AV_OPT_TYPE_BOOL,
  175. {.i64 = 0}, 0, 1, 0 },
  176. {"skip_clear", "skip clearing programs", offsetof(MpegTSContext, skip_clear), AV_OPT_TYPE_BOOL,
  177. {.i64 = 0}, 0, 1, 0 },
  178. {"max_packet_size", "maximum size of emitted packet", offsetof(MpegTSContext, max_packet_size), AV_OPT_TYPE_INT,
  179. {.i64 = 204800}, 1, INT_MAX/2, AV_OPT_FLAG_DECODING_PARAM },
  180. { NULL },
  181. };
  182. static const AVClass mpegts_class = {
  183. .class_name = "mpegts demuxer",
  184. .item_name = av_default_item_name,
  185. .option = options,
  186. .version = LIBAVUTIL_VERSION_INT,
  187. };
  188. static const AVOption raw_options[] = {
  189. MPEGTS_OPTIONS,
  190. { "compute_pcr", "compute exact PCR for each transport stream packet",
  191. offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_BOOL,
  192. { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
  193. { NULL },
  194. };
  195. static const AVClass mpegtsraw_class = {
  196. .class_name = "mpegtsraw demuxer",
  197. .item_name = av_default_item_name,
  198. .option = raw_options,
  199. .version = LIBAVUTIL_VERSION_INT,
  200. };
  201. /* TS stream handling */
  202. enum MpegTSState {
  203. MPEGTS_HEADER = 0,
  204. MPEGTS_PESHEADER,
  205. MPEGTS_PESHEADER_FILL,
  206. MPEGTS_PAYLOAD,
  207. MPEGTS_SKIP,
  208. };
  209. /* enough for PES header + length */
  210. #define PES_START_SIZE 6
  211. #define PES_HEADER_SIZE 9
  212. #define MAX_PES_HEADER_SIZE (9 + 255)
  213. typedef struct PESContext {
  214. int pid;
  215. int pcr_pid; /**< if -1 then all packets containing PCR are considered */
  216. int stream_type;
  217. MpegTSContext *ts;
  218. AVFormatContext *stream;
  219. AVStream *st;
  220. AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
  221. enum MpegTSState state;
  222. /* used to get the format */
  223. int data_index;
  224. int flags; /**< copied to the AVPacket flags */
  225. int PES_packet_length;
  226. int pes_header_size;
  227. int extended_stream_id;
  228. uint8_t stream_id;
  229. int64_t pts, dts;
  230. int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
  231. uint8_t header[MAX_PES_HEADER_SIZE];
  232. AVBufferRef *buffer;
  233. SLConfigDescr sl;
  234. int merged_st;
  235. } PESContext;
  236. extern const FFInputFormat ff_mpegts_demuxer;
  237. static struct Program * get_program(MpegTSContext *ts, unsigned int programid)
  238. {
  239. int i;
  240. for (i = 0; i < ts->nb_prg; i++) {
  241. if (ts->prg[i].id == programid) {
  242. return &ts->prg[i];
  243. }
  244. }
  245. return NULL;
  246. }
  247. static void clear_avprogram(MpegTSContext *ts, unsigned int programid)
  248. {
  249. AVProgram *prg = NULL;
  250. int i;
  251. for (i = 0; i < ts->stream->nb_programs; i++)
  252. if (ts->stream->programs[i]->id == programid) {
  253. prg = ts->stream->programs[i];
  254. break;
  255. }
  256. if (!prg)
  257. return;
  258. prg->nb_stream_indexes = 0;
  259. }
  260. static void clear_program(struct Program *p)
  261. {
  262. if (!p)
  263. return;
  264. p->nb_pids = 0;
  265. p->nb_streams = 0;
  266. p->pmt_found = 0;
  267. }
  268. static void clear_programs(MpegTSContext *ts)
  269. {
  270. av_freep(&ts->prg);
  271. ts->nb_prg = 0;
  272. }
  273. static struct Program * add_program(MpegTSContext *ts, unsigned int programid)
  274. {
  275. struct Program *p = get_program(ts, programid);
  276. if (p)
  277. return p;
  278. if (av_reallocp_array(&ts->prg, ts->nb_prg + 1, sizeof(*ts->prg)) < 0) {
  279. ts->nb_prg = 0;
  280. return NULL;
  281. }
  282. p = &ts->prg[ts->nb_prg];
  283. p->id = programid;
  284. clear_program(p);
  285. ts->nb_prg++;
  286. return p;
  287. }
  288. static void add_pid_to_program(struct Program *p, unsigned int pid)
  289. {
  290. int i;
  291. if (!p)
  292. return;
  293. if (p->nb_pids >= MAX_PIDS_PER_PROGRAM)
  294. return;
  295. for (i = 0; i < p->nb_pids; i++)
  296. if (p->pids[i] == pid)
  297. return;
  298. p->pids[p->nb_pids++] = pid;
  299. }
  300. static void update_av_program_info(AVFormatContext *s, unsigned int programid,
  301. unsigned int pid, int version)
  302. {
  303. int i;
  304. for (i = 0; i < s->nb_programs; i++) {
  305. AVProgram *program = s->programs[i];
  306. if (program->id == programid) {
  307. int old_pcr_pid = program->pcr_pid,
  308. old_version = program->pmt_version;
  309. program->pcr_pid = pid;
  310. program->pmt_version = version;
  311. if (old_version != -1 && old_version != version) {
  312. av_log(s, AV_LOG_VERBOSE,
  313. "detected PMT change (program=%d, version=%d/%d, pcr_pid=0x%x/0x%x)\n",
  314. programid, old_version, version, old_pcr_pid, pid);
  315. }
  316. break;
  317. }
  318. }
  319. }
  320. /**
  321. * @brief discard_pid() decides if the pid is to be discarded according
  322. * to caller's programs selection
  323. * @param ts : - TS context
  324. * @param pid : - pid
  325. * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
  326. * 0 otherwise
  327. */
  328. static int discard_pid(MpegTSContext *ts, unsigned int pid)
  329. {
  330. int i, j, k;
  331. int used = 0, discarded = 0;
  332. struct Program *p;
  333. if (pid == PAT_PID)
  334. return 0;
  335. /* If none of the programs have .discard=AVDISCARD_ALL then there's
  336. * no way we have to discard this packet */
  337. for (k = 0; k < ts->stream->nb_programs; k++)
  338. if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
  339. break;
  340. if (k == ts->stream->nb_programs)
  341. return 0;
  342. for (i = 0; i < ts->nb_prg; i++) {
  343. p = &ts->prg[i];
  344. for (j = 0; j < p->nb_pids; j++) {
  345. if (p->pids[j] != pid)
  346. continue;
  347. // is program with id p->id set to be discarded?
  348. for (k = 0; k < ts->stream->nb_programs; k++) {
  349. if (ts->stream->programs[k]->id == p->id) {
  350. if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
  351. discarded++;
  352. else
  353. used++;
  354. }
  355. }
  356. }
  357. }
  358. return !used && discarded;
  359. }
  360. /**
  361. * Assemble PES packets out of TS packets, and then call the "section_cb"
  362. * function when they are complete.
  363. */
  364. static void write_section_data(MpegTSContext *ts, MpegTSFilter *tss1,
  365. const uint8_t *buf, int buf_size, int is_start)
  366. {
  367. MpegTSSectionFilter *tss = &tss1->u.section_filter;
  368. uint8_t *cur_section_buf = NULL;
  369. int len, offset;
  370. if (is_start) {
  371. memcpy(tss->section_buf, buf, buf_size);
  372. tss->section_index = buf_size;
  373. tss->section_h_size = -1;
  374. tss->end_of_section_reached = 0;
  375. } else {
  376. if (tss->end_of_section_reached)
  377. return;
  378. len = MAX_SECTION_SIZE - tss->section_index;
  379. if (buf_size < len)
  380. len = buf_size;
  381. memcpy(tss->section_buf + tss->section_index, buf, len);
  382. tss->section_index += len;
  383. }
  384. offset = 0;
  385. cur_section_buf = tss->section_buf;
  386. while (cur_section_buf - tss->section_buf < MAX_SECTION_SIZE && cur_section_buf[0] != 0xff) {
  387. /* compute section length if possible */
  388. if (tss->section_h_size == -1 && tss->section_index - offset >= 3) {
  389. len = (AV_RB16(cur_section_buf + 1) & 0xfff) + 3;
  390. if (len > MAX_SECTION_SIZE)
  391. return;
  392. tss->section_h_size = len;
  393. }
  394. if (tss->section_h_size != -1 &&
  395. tss->section_index >= offset + tss->section_h_size) {
  396. int crc_valid = 1;
  397. tss->end_of_section_reached = 1;
  398. if (tss->check_crc) {
  399. crc_valid = !av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, cur_section_buf, tss->section_h_size);
  400. if (tss->section_h_size >= 4)
  401. tss->crc = AV_RB32(cur_section_buf + tss->section_h_size - 4);
  402. if (crc_valid) {
  403. ts->crc_validity[ tss1->pid ] = 100;
  404. }else if (ts->crc_validity[ tss1->pid ] > -10) {
  405. ts->crc_validity[ tss1->pid ]--;
  406. }else
  407. crc_valid = 2;
  408. }
  409. if (crc_valid) {
  410. tss->section_cb(tss1, cur_section_buf, tss->section_h_size);
  411. if (crc_valid != 1)
  412. tss->last_ver = -1;
  413. }
  414. cur_section_buf += tss->section_h_size;
  415. offset += tss->section_h_size;
  416. tss->section_h_size = -1;
  417. } else {
  418. tss->section_h_size = -1;
  419. tss->end_of_section_reached = 0;
  420. break;
  421. }
  422. }
  423. }
  424. static MpegTSFilter *mpegts_open_filter(MpegTSContext *ts, unsigned int pid,
  425. enum MpegTSFilterType type)
  426. {
  427. MpegTSFilter *filter;
  428. av_log(ts->stream, AV_LOG_TRACE, "Filter: pid=0x%x type=%d\n", pid, type);
  429. if (pid >= NB_PID_MAX || ts->pids[pid])
  430. return NULL;
  431. filter = av_mallocz(sizeof(MpegTSFilter));
  432. if (!filter)
  433. return NULL;
  434. ts->pids[pid] = filter;
  435. filter->type = type;
  436. filter->pid = pid;
  437. filter->es_id = -1;
  438. filter->last_cc = -1;
  439. filter->last_pcr= -1;
  440. return filter;
  441. }
  442. static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts,
  443. unsigned int pid,
  444. SectionCallback *section_cb,
  445. void *opaque,
  446. int check_crc)
  447. {
  448. MpegTSFilter *filter;
  449. MpegTSSectionFilter *sec;
  450. uint8_t *section_buf = av_mallocz(MAX_SECTION_SIZE);
  451. if (!section_buf)
  452. return NULL;
  453. if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_SECTION))) {
  454. av_free(section_buf);
  455. return NULL;
  456. }
  457. sec = &filter->u.section_filter;
  458. sec->section_cb = section_cb;
  459. sec->opaque = opaque;
  460. sec->section_buf = section_buf;
  461. sec->check_crc = check_crc;
  462. sec->last_ver = -1;
  463. return filter;
  464. }
  465. static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
  466. PESCallback *pes_cb,
  467. void *opaque)
  468. {
  469. MpegTSFilter *filter;
  470. MpegTSPESFilter *pes;
  471. if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_PES)))
  472. return NULL;
  473. pes = &filter->u.pes_filter;
  474. pes->pes_cb = pes_cb;
  475. pes->opaque = opaque;
  476. return filter;
  477. }
  478. static MpegTSFilter *mpegts_open_pcr_filter(MpegTSContext *ts, unsigned int pid)
  479. {
  480. return mpegts_open_filter(ts, pid, MPEGTS_PCR);
  481. }
  482. static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
  483. {
  484. int pid;
  485. pid = filter->pid;
  486. if (filter->type == MPEGTS_SECTION)
  487. av_freep(&filter->u.section_filter.section_buf);
  488. else if (filter->type == MPEGTS_PES) {
  489. PESContext *pes = filter->u.pes_filter.opaque;
  490. av_buffer_unref(&pes->buffer);
  491. /* referenced private data will be freed later in
  492. * avformat_close_input (pes->st->priv_data == pes) */
  493. if (!pes->st || pes->merged_st) {
  494. av_freep(&filter->u.pes_filter.opaque);
  495. }
  496. }
  497. av_free(filter);
  498. ts->pids[pid] = NULL;
  499. }
  500. static int analyze(const uint8_t *buf, int size, int packet_size,
  501. int probe)
  502. {
  503. int stat[TS_MAX_PACKET_SIZE];
  504. int stat_all = 0;
  505. int i;
  506. int best_score = 0;
  507. memset(stat, 0, packet_size * sizeof(*stat));
  508. for (i = 0; i < size - 3; i++) {
  509. if (buf[i] == 0x47) {
  510. int pid = AV_RB16(buf+1) & 0x1FFF;
  511. int asc = buf[i + 3] & 0x30;
  512. if (!probe || pid == 0x1FFF || asc) {
  513. int x = i % packet_size;
  514. stat[x]++;
  515. stat_all++;
  516. if (stat[x] > best_score) {
  517. best_score = stat[x];
  518. }
  519. }
  520. }
  521. }
  522. return best_score - FFMAX(stat_all - 10*best_score, 0)/10;
  523. }
  524. /* autodetect fec presence */
  525. static int get_packet_size(AVFormatContext* s)
  526. {
  527. int score, fec_score, dvhs_score;
  528. int margin;
  529. int ret;
  530. /*init buffer to store stream for probing */
  531. uint8_t buf[PROBE_PACKET_MAX_BUF] = {0};
  532. int buf_size = 0;
  533. int max_iterations = 16;
  534. while (buf_size < PROBE_PACKET_MAX_BUF && max_iterations--) {
  535. ret = avio_read_partial(s->pb, buf + buf_size, PROBE_PACKET_MAX_BUF - buf_size);
  536. if (ret < 0)
  537. return AVERROR_INVALIDDATA;
  538. buf_size += ret;
  539. score = analyze(buf, buf_size, TS_PACKET_SIZE, 0);
  540. dvhs_score = analyze(buf, buf_size, TS_DVHS_PACKET_SIZE, 0);
  541. fec_score = analyze(buf, buf_size, TS_FEC_PACKET_SIZE, 0);
  542. av_log(s, AV_LOG_TRACE, "Probe: %d, score: %d, dvhs_score: %d, fec_score: %d \n",
  543. buf_size, score, dvhs_score, fec_score);
  544. margin = mid_pred(score, fec_score, dvhs_score);
  545. if (buf_size < PROBE_PACKET_MAX_BUF)
  546. margin += PROBE_PACKET_MARGIN; /*if buffer not filled */
  547. if (score > margin)
  548. return TS_PACKET_SIZE;
  549. else if (dvhs_score > margin)
  550. return TS_DVHS_PACKET_SIZE;
  551. else if (fec_score > margin)
  552. return TS_FEC_PACKET_SIZE;
  553. }
  554. return AVERROR_INVALIDDATA;
  555. }
  556. typedef struct SectionHeader {
  557. uint8_t tid;
  558. uint16_t id;
  559. uint8_t version;
  560. uint8_t current_next;
  561. uint8_t sec_num;
  562. uint8_t last_sec_num;
  563. } SectionHeader;
  564. static int skip_identical(const SectionHeader *h, MpegTSSectionFilter *tssf)
  565. {
  566. if (h->version == tssf->last_ver && tssf->last_crc == tssf->crc)
  567. return 1;
  568. tssf->last_ver = h->version;
  569. tssf->last_crc = tssf->crc;
  570. return 0;
  571. }
  572. static inline int get8(const uint8_t **pp, const uint8_t *p_end)
  573. {
  574. const uint8_t *p;
  575. int c;
  576. p = *pp;
  577. if (p >= p_end)
  578. return AVERROR_INVALIDDATA;
  579. c = *p++;
  580. *pp = p;
  581. return c;
  582. }
  583. static inline int get16(const uint8_t **pp, const uint8_t *p_end)
  584. {
  585. const uint8_t *p;
  586. int c;
  587. p = *pp;
  588. if (1 >= p_end - p)
  589. return AVERROR_INVALIDDATA;
  590. c = AV_RB16(p);
  591. p += 2;
  592. *pp = p;
  593. return c;
  594. }
  595. /* read and allocate a DVB string preceded by its length */
  596. static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
  597. {
  598. int len;
  599. const uint8_t *p;
  600. char *str;
  601. p = *pp;
  602. len = get8(&p, p_end);
  603. if (len < 0)
  604. return NULL;
  605. if (len > p_end - p)
  606. return NULL;
  607. #if CONFIG_ICONV
  608. if (len) {
  609. const char *encodings[] = {
  610. "ISO6937", "ISO-8859-5", "ISO-8859-6", "ISO-8859-7",
  611. "ISO-8859-8", "ISO-8859-9", "ISO-8859-10", "ISO-8859-11",
  612. "", "ISO-8859-13", "ISO-8859-14", "ISO-8859-15", "", "", "", "",
  613. "", "UCS-2BE", "KSC_5601", "GB2312", "UCS-2BE", "UTF-8", "", "",
  614. "", "", "", "", "", "", "", ""
  615. };
  616. iconv_t cd;
  617. char *in, *out;
  618. size_t inlen = len, outlen = inlen * 6 + 1;
  619. if (len >= 3 && p[0] == 0x10 && !p[1] && p[2] && p[2] <= 0xf && p[2] != 0xc) {
  620. char iso8859[12];
  621. snprintf(iso8859, sizeof(iso8859), "ISO-8859-%d", p[2]);
  622. inlen -= 3;
  623. in = (char *)p + 3;
  624. cd = iconv_open("UTF-8", iso8859);
  625. } else if (p[0] < 0x20) {
  626. inlen -= 1;
  627. in = (char *)p + 1;
  628. cd = iconv_open("UTF-8", encodings[*p]);
  629. } else {
  630. in = (char *)p;
  631. cd = iconv_open("UTF-8", encodings[0]);
  632. }
  633. if (cd == (iconv_t)-1)
  634. goto no_iconv;
  635. str = out = av_malloc(outlen);
  636. if (!str) {
  637. iconv_close(cd);
  638. return NULL;
  639. }
  640. if (iconv(cd, &in, &inlen, &out, &outlen) == -1) {
  641. iconv_close(cd);
  642. av_freep(&str);
  643. goto no_iconv;
  644. }
  645. iconv_close(cd);
  646. *out = 0;
  647. *pp = p + len;
  648. return str;
  649. }
  650. no_iconv:
  651. #endif
  652. str = av_malloc(len + 1);
  653. if (!str)
  654. return NULL;
  655. memcpy(str, p, len);
  656. str[len] = '\0';
  657. p += len;
  658. *pp = p;
  659. return str;
  660. }
  661. static int parse_section_header(SectionHeader *h,
  662. const uint8_t **pp, const uint8_t *p_end)
  663. {
  664. int val;
  665. val = get8(pp, p_end);
  666. if (val < 0)
  667. return val;
  668. h->tid = val;
  669. *pp += 2;
  670. val = get16(pp, p_end);
  671. if (val < 0)
  672. return val;
  673. h->id = val;
  674. val = get8(pp, p_end);
  675. if (val < 0)
  676. return val;
  677. h->version = (val >> 1) & 0x1f;
  678. h->current_next = val & 0x01;
  679. val = get8(pp, p_end);
  680. if (val < 0)
  681. return val;
  682. h->sec_num = val;
  683. val = get8(pp, p_end);
  684. if (val < 0)
  685. return val;
  686. h->last_sec_num = val;
  687. return 0;
  688. }
  689. typedef struct StreamType {
  690. uint32_t stream_type;
  691. enum AVMediaType codec_type;
  692. enum AVCodecID codec_id;
  693. } StreamType;
  694. static const StreamType ISO_types[] = {
  695. { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
  696. { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
  697. { 0x03, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
  698. { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
  699. { 0x0f, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
  700. { 0x10, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4 },
  701. /* Makito encoder sets stream type 0x11 for AAC,
  702. * so auto-detect LOAS/LATM instead of hardcoding it. */
  703. #if !CONFIG_LOAS_DEMUXER
  704. { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
  705. #endif
  706. { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
  707. { 0x1c, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
  708. { 0x20, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
  709. { 0x21, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_JPEG2000 },
  710. { 0x24, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
  711. { 0x33, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VVC },
  712. { 0x42, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_CAVS },
  713. { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
  714. { 0xd2, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_AVS2 },
  715. { 0xd4, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_AVS3 },
  716. { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
  717. { 0 },
  718. };
  719. static const StreamType HDMV_types[] = {
  720. { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
  721. { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
  722. { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  723. { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
  724. { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
  725. { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
  726. { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
  727. { 0xa1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC3 Secondary Audio */
  728. { 0xa2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS Express Secondary Audio */
  729. { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
  730. { 0x92, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_TEXT_SUBTITLE },
  731. { 0 },
  732. };
  733. /* SCTE types */
  734. static const StreamType SCTE_types[] = {
  735. { 0x86, AVMEDIA_TYPE_DATA, AV_CODEC_ID_SCTE_35 },
  736. { 0 },
  737. };
  738. /* ATSC ? */
  739. static const StreamType MISC_types[] = {
  740. { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
  741. { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  742. { 0 },
  743. };
  744. /* HLS Sample Encryption Types */
  745. static const StreamType HLS_SAMPLE_ENC_types[] = {
  746. { 0xdb, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264},
  747. { 0xcf, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
  748. { 0xc1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
  749. { 0xc2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3},
  750. { 0 },
  751. };
  752. static const StreamType REGD_types[] = {
  753. { MKTAG('d', 'r', 'a', 'c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
  754. { MKTAG('A', 'C', '-', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
  755. { MKTAG('A', 'C', '-', '4'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC4 },
  756. { MKTAG('B', 'S', 'S', 'D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
  757. { MKTAG('D', 'T', 'S', '1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  758. { MKTAG('D', 'T', 'S', '2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  759. { MKTAG('D', 'T', 'S', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  760. { MKTAG('E', 'A', 'C', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
  761. { MKTAG('H', 'E', 'V', 'C'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
  762. { MKTAG('V', 'V', 'C', ' '), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VVC },
  763. { MKTAG('K', 'L', 'V', 'A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
  764. { MKTAG('V', 'A', 'N', 'C'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_2038 },
  765. { MKTAG('I', 'D', '3', ' '), AVMEDIA_TYPE_DATA, AV_CODEC_ID_TIMED_ID3 },
  766. { MKTAG('V', 'C', '-', '1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
  767. { MKTAG('O', 'p', 'u', 's'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_OPUS },
  768. { 0 },
  769. };
  770. static const StreamType METADATA_types[] = {
  771. { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
  772. { MKTAG('I','D','3',' '), AVMEDIA_TYPE_DATA, AV_CODEC_ID_TIMED_ID3 },
  773. { 0 },
  774. };
  775. /* descriptor present */
  776. static const StreamType DESC_types[] = {
  777. { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
  778. { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
  779. { 0x7b, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  780. { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
  781. { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
  782. { 0 },
  783. };
  784. static void mpegts_find_stream_type(AVStream *st,
  785. uint32_t stream_type,
  786. const StreamType *types)
  787. {
  788. FFStream *const sti = ffstream(st);
  789. for (; types->stream_type; types++)
  790. if (stream_type == types->stream_type) {
  791. if (st->codecpar->codec_type != types->codec_type ||
  792. st->codecpar->codec_id != types->codec_id) {
  793. st->codecpar->codec_type = types->codec_type;
  794. st->codecpar->codec_id = types->codec_id;
  795. sti->need_context_update = 1;
  796. }
  797. sti->request_probe = 0;
  798. return;
  799. }
  800. }
  801. static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
  802. uint32_t stream_type, uint32_t prog_reg_desc)
  803. {
  804. FFStream *const sti = ffstream(st);
  805. int old_codec_type = st->codecpar->codec_type;
  806. int old_codec_id = st->codecpar->codec_id;
  807. int old_codec_tag = st->codecpar->codec_tag;
  808. avpriv_set_pts_info(st, 33, 1, 90000);
  809. st->priv_data = pes;
  810. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  811. st->codecpar->codec_id = AV_CODEC_ID_NONE;
  812. sti->need_parsing = AVSTREAM_PARSE_FULL;
  813. pes->st = st;
  814. pes->stream_type = stream_type;
  815. av_log(pes->stream, AV_LOG_DEBUG,
  816. "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
  817. st->index, pes->stream_type, pes->pid, (char *)&prog_reg_desc);
  818. st->codecpar->codec_tag = pes->stream_type;
  819. mpegts_find_stream_type(st, pes->stream_type, ISO_types);
  820. if (pes->stream_type == 4 || pes->stream_type == 0x0f)
  821. sti->request_probe = 50;
  822. if ((prog_reg_desc == AV_RL32("HDMV") ||
  823. prog_reg_desc == AV_RL32("HDPR")) &&
  824. st->codecpar->codec_id == AV_CODEC_ID_NONE) {
  825. mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
  826. if (pes->stream_type == 0x83) {
  827. // HDMV TrueHD streams also contain an AC3 coded version of the
  828. // audio track - add a second stream for this
  829. AVStream *sub_st;
  830. // priv_data cannot be shared between streams
  831. PESContext *sub_pes = av_memdup(pes, sizeof(*sub_pes));
  832. if (!sub_pes)
  833. return AVERROR(ENOMEM);
  834. sub_st = avformat_new_stream(pes->stream, NULL);
  835. if (!sub_st) {
  836. av_free(sub_pes);
  837. return AVERROR(ENOMEM);
  838. }
  839. sub_st->id = pes->pid;
  840. avpriv_set_pts_info(sub_st, 33, 1, 90000);
  841. sub_st->priv_data = sub_pes;
  842. sub_st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  843. sub_st->codecpar->codec_id = AV_CODEC_ID_AC3;
  844. ffstream(sub_st)->need_parsing = AVSTREAM_PARSE_FULL;
  845. sub_pes->sub_st = pes->sub_st = sub_st;
  846. }
  847. }
  848. if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
  849. mpegts_find_stream_type(st, pes->stream_type, MISC_types);
  850. if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
  851. mpegts_find_stream_type(st, pes->stream_type, HLS_SAMPLE_ENC_types);
  852. if (st->codecpar->codec_id == AV_CODEC_ID_NONE) {
  853. st->codecpar->codec_id = old_codec_id;
  854. st->codecpar->codec_type = old_codec_type;
  855. }
  856. if ((st->codecpar->codec_id == AV_CODEC_ID_NONE ||
  857. (sti->request_probe > 0 && sti->request_probe < AVPROBE_SCORE_STREAM_RETRY / 5)) &&
  858. sti->probe_packets > 0 &&
  859. stream_type == STREAM_TYPE_PRIVATE_DATA) {
  860. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  861. st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
  862. sti->request_probe = AVPROBE_SCORE_STREAM_RETRY / 5;
  863. }
  864. /* queue a context update if properties changed */
  865. if (old_codec_type != st->codecpar->codec_type ||
  866. old_codec_id != st->codecpar->codec_id ||
  867. old_codec_tag != st->codecpar->codec_tag)
  868. sti->need_context_update = 1;
  869. return 0;
  870. }
  871. static void reset_pes_packet_state(PESContext *pes)
  872. {
  873. pes->pts = AV_NOPTS_VALUE;
  874. pes->dts = AV_NOPTS_VALUE;
  875. pes->data_index = 0;
  876. pes->flags = 0;
  877. av_buffer_unref(&pes->buffer);
  878. }
  879. static void new_data_packet(const uint8_t *buffer, int len, AVPacket *pkt)
  880. {
  881. av_packet_unref(pkt);
  882. pkt->data = (uint8_t *)buffer;
  883. pkt->size = len;
  884. }
  885. static int new_pes_packet(PESContext *pes, AVPacket *pkt)
  886. {
  887. uint8_t *sd;
  888. av_packet_unref(pkt);
  889. pkt->buf = pes->buffer;
  890. pkt->data = pes->buffer->data;
  891. pkt->size = pes->data_index;
  892. if (pes->PES_packet_length &&
  893. pes->pes_header_size + pes->data_index != pes->PES_packet_length +
  894. PES_START_SIZE) {
  895. av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
  896. pes->flags |= AV_PKT_FLAG_CORRUPT;
  897. }
  898. memset(pkt->data + pkt->size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  899. // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
  900. if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
  901. pkt->stream_index = pes->sub_st->index;
  902. else
  903. pkt->stream_index = pes->st->index;
  904. pkt->pts = pes->pts;
  905. pkt->dts = pes->dts;
  906. /* store position of first TS packet of this PES packet */
  907. pkt->pos = pes->ts_packet_pos;
  908. pkt->flags = pes->flags;
  909. pes->buffer = NULL;
  910. reset_pes_packet_state(pes);
  911. sd = av_packet_new_side_data(pkt, AV_PKT_DATA_MPEGTS_STREAM_ID, 1);
  912. if (!sd)
  913. return AVERROR(ENOMEM);
  914. *sd = pes->stream_id;
  915. return 0;
  916. }
  917. static uint64_t get_ts64(GetBitContext *gb, int bits)
  918. {
  919. if (get_bits_left(gb) < bits)
  920. return AV_NOPTS_VALUE;
  921. return get_bits64(gb, bits);
  922. }
  923. static int read_sl_header(PESContext *pes, SLConfigDescr *sl,
  924. const uint8_t *buf, int buf_size)
  925. {
  926. GetBitContext gb;
  927. int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
  928. int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
  929. int dts_flag = -1, cts_flag = -1;
  930. int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
  931. uint8_t buf_padded[128 + AV_INPUT_BUFFER_PADDING_SIZE];
  932. int buf_padded_size = FFMIN(buf_size, sizeof(buf_padded) - AV_INPUT_BUFFER_PADDING_SIZE);
  933. memcpy(buf_padded, buf, buf_padded_size);
  934. init_get_bits(&gb, buf_padded, buf_padded_size * 8);
  935. if (sl->use_au_start)
  936. au_start_flag = get_bits1(&gb);
  937. if (sl->use_au_end)
  938. au_end_flag = get_bits1(&gb);
  939. if (!sl->use_au_start && !sl->use_au_end)
  940. au_start_flag = au_end_flag = 1;
  941. if (sl->ocr_len > 0)
  942. ocr_flag = get_bits1(&gb);
  943. if (sl->use_idle)
  944. idle_flag = get_bits1(&gb);
  945. if (sl->use_padding)
  946. padding_flag = get_bits1(&gb);
  947. if (padding_flag)
  948. padding_bits = get_bits(&gb, 3);
  949. if (!idle_flag && (!padding_flag || padding_bits != 0)) {
  950. if (sl->packet_seq_num_len)
  951. skip_bits_long(&gb, sl->packet_seq_num_len);
  952. if (sl->degr_prior_len)
  953. if (get_bits1(&gb))
  954. skip_bits(&gb, sl->degr_prior_len);
  955. if (ocr_flag)
  956. skip_bits_long(&gb, sl->ocr_len);
  957. if (au_start_flag) {
  958. if (sl->use_rand_acc_pt)
  959. get_bits1(&gb);
  960. if (sl->au_seq_num_len > 0)
  961. skip_bits_long(&gb, sl->au_seq_num_len);
  962. if (sl->use_timestamps) {
  963. dts_flag = get_bits1(&gb);
  964. cts_flag = get_bits1(&gb);
  965. }
  966. }
  967. if (sl->inst_bitrate_len)
  968. inst_bitrate_flag = get_bits1(&gb);
  969. if (dts_flag == 1)
  970. dts = get_ts64(&gb, sl->timestamp_len);
  971. if (cts_flag == 1)
  972. cts = get_ts64(&gb, sl->timestamp_len);
  973. if (sl->au_len > 0)
  974. skip_bits_long(&gb, sl->au_len);
  975. if (inst_bitrate_flag)
  976. skip_bits_long(&gb, sl->inst_bitrate_len);
  977. }
  978. if (dts != AV_NOPTS_VALUE)
  979. pes->dts = dts;
  980. if (cts != AV_NOPTS_VALUE)
  981. pes->pts = cts;
  982. if (sl->timestamp_len && sl->timestamp_res)
  983. avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
  984. return (get_bits_count(&gb) + 7) >> 3;
  985. }
  986. static AVBufferRef *buffer_pool_get(MpegTSContext *ts, int size)
  987. {
  988. int index = av_log2(size + AV_INPUT_BUFFER_PADDING_SIZE);
  989. if (!ts->pools[index]) {
  990. int pool_size = FFMIN(ts->max_packet_size + AV_INPUT_BUFFER_PADDING_SIZE, 2 << index);
  991. ts->pools[index] = av_buffer_pool_init(pool_size, NULL);
  992. if (!ts->pools[index])
  993. return NULL;
  994. }
  995. return av_buffer_pool_get(ts->pools[index]);
  996. }
  997. /* return non zero if a packet could be constructed */
  998. static int mpegts_push_data(MpegTSFilter *filter,
  999. const uint8_t *buf, int buf_size, int is_start,
  1000. int64_t pos)
  1001. {
  1002. PESContext *pes = filter->u.pes_filter.opaque;
  1003. MpegTSContext *ts = pes->ts;
  1004. const uint8_t *p;
  1005. int ret, len;
  1006. if (!ts->pkt)
  1007. return 0;
  1008. if (is_start) {
  1009. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  1010. ret = new_pes_packet(pes, ts->pkt);
  1011. if (ret < 0)
  1012. return ret;
  1013. ts->stop_parse = 1;
  1014. } else {
  1015. reset_pes_packet_state(pes);
  1016. }
  1017. pes->state = MPEGTS_HEADER;
  1018. pes->ts_packet_pos = pos;
  1019. }
  1020. p = buf;
  1021. while (buf_size > 0) {
  1022. switch (pes->state) {
  1023. case MPEGTS_HEADER:
  1024. len = PES_START_SIZE - pes->data_index;
  1025. if (len > buf_size)
  1026. len = buf_size;
  1027. memcpy(pes->header + pes->data_index, p, len);
  1028. pes->data_index += len;
  1029. p += len;
  1030. buf_size -= len;
  1031. if (pes->data_index == PES_START_SIZE) {
  1032. /* we got all the PES or section header. We can now
  1033. * decide */
  1034. if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
  1035. pes->header[2] == 0x01) {
  1036. /* it must be an MPEG-2 PES stream */
  1037. pes->stream_id = pes->header[3];
  1038. av_log(pes->stream, AV_LOG_TRACE, "pid=%x stream_id=%#x\n", pes->pid, pes->stream_id);
  1039. if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
  1040. (!pes->sub_st ||
  1041. pes->sub_st->discard == AVDISCARD_ALL)) ||
  1042. pes->stream_id == STREAM_ID_PADDING_STREAM)
  1043. goto skip;
  1044. /* stream not present in PMT */
  1045. if (!pes->st) {
  1046. if (ts->skip_changes)
  1047. goto skip;
  1048. if (ts->merge_pmt_versions)
  1049. goto skip; /* wait for PMT to merge new stream */
  1050. pes->st = avformat_new_stream(ts->stream, NULL);
  1051. if (!pes->st)
  1052. return AVERROR(ENOMEM);
  1053. pes->st->id = pes->pid;
  1054. mpegts_set_stream_info(pes->st, pes, 0, 0);
  1055. }
  1056. pes->PES_packet_length = AV_RB16(pes->header + 4);
  1057. /* NOTE: zero length means the PES size is unbounded */
  1058. if (pes->stream_id != STREAM_ID_PROGRAM_STREAM_MAP &&
  1059. pes->stream_id != STREAM_ID_PRIVATE_STREAM_2 &&
  1060. pes->stream_id != STREAM_ID_ECM_STREAM &&
  1061. pes->stream_id != STREAM_ID_EMM_STREAM &&
  1062. pes->stream_id != STREAM_ID_PROGRAM_STREAM_DIRECTORY &&
  1063. pes->stream_id != STREAM_ID_DSMCC_STREAM &&
  1064. pes->stream_id != STREAM_ID_TYPE_E_STREAM) {
  1065. FFStream *const pes_sti = ffstream(pes->st);
  1066. pes->state = MPEGTS_PESHEADER;
  1067. if (pes->st->codecpar->codec_id == AV_CODEC_ID_NONE && !pes_sti->request_probe) {
  1068. av_log(pes->stream, AV_LOG_TRACE,
  1069. "pid=%x stream_type=%x probing\n",
  1070. pes->pid,
  1071. pes->stream_type);
  1072. pes_sti->request_probe = 1;
  1073. }
  1074. } else {
  1075. pes->pes_header_size = 6;
  1076. pes->state = MPEGTS_PAYLOAD;
  1077. pes->data_index = 0;
  1078. }
  1079. } else {
  1080. /* otherwise, it should be a table */
  1081. /* skip packet */
  1082. skip:
  1083. pes->state = MPEGTS_SKIP;
  1084. continue;
  1085. }
  1086. }
  1087. break;
  1088. /**********************************************/
  1089. /* PES packing parsing */
  1090. case MPEGTS_PESHEADER:
  1091. len = PES_HEADER_SIZE - pes->data_index;
  1092. if (len < 0)
  1093. return AVERROR_INVALIDDATA;
  1094. if (len > buf_size)
  1095. len = buf_size;
  1096. memcpy(pes->header + pes->data_index, p, len);
  1097. pes->data_index += len;
  1098. p += len;
  1099. buf_size -= len;
  1100. if (pes->data_index == PES_HEADER_SIZE) {
  1101. pes->pes_header_size = pes->header[8] + 9;
  1102. pes->state = MPEGTS_PESHEADER_FILL;
  1103. }
  1104. break;
  1105. case MPEGTS_PESHEADER_FILL:
  1106. len = pes->pes_header_size - pes->data_index;
  1107. if (len < 0)
  1108. return AVERROR_INVALIDDATA;
  1109. if (len > buf_size)
  1110. len = buf_size;
  1111. memcpy(pes->header + pes->data_index, p, len);
  1112. pes->data_index += len;
  1113. p += len;
  1114. buf_size -= len;
  1115. if (pes->data_index == pes->pes_header_size) {
  1116. const uint8_t *r;
  1117. unsigned int flags, pes_ext, skip;
  1118. flags = pes->header[7];
  1119. r = pes->header + 9;
  1120. pes->pts = AV_NOPTS_VALUE;
  1121. pes->dts = AV_NOPTS_VALUE;
  1122. if ((flags & 0xc0) == 0x80) {
  1123. pes->dts = pes->pts = ff_parse_pes_pts(r);
  1124. r += 5;
  1125. } else if ((flags & 0xc0) == 0xc0) {
  1126. pes->pts = ff_parse_pes_pts(r);
  1127. r += 5;
  1128. pes->dts = ff_parse_pes_pts(r);
  1129. r += 5;
  1130. }
  1131. pes->extended_stream_id = -1;
  1132. if (flags & 0x01) { /* PES extension */
  1133. pes_ext = *r++;
  1134. /* Skip PES private data, program packet sequence counter and P-STD buffer */
  1135. skip = (pes_ext >> 4) & 0xb;
  1136. skip += skip & 0x9;
  1137. r += skip;
  1138. if ((pes_ext & 0x41) == 0x01 &&
  1139. (r + 2) <= (pes->header + pes->pes_header_size)) {
  1140. /* PES extension 2 */
  1141. if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
  1142. pes->extended_stream_id = r[1];
  1143. }
  1144. }
  1145. /* we got the full header. We parse it and get the payload */
  1146. pes->state = MPEGTS_PAYLOAD;
  1147. pes->data_index = 0;
  1148. if (pes->stream_type == 0x12 && buf_size > 0) {
  1149. int sl_header_bytes = read_sl_header(pes, &pes->sl, p,
  1150. buf_size);
  1151. pes->pes_header_size += sl_header_bytes;
  1152. p += sl_header_bytes;
  1153. buf_size -= sl_header_bytes;
  1154. }
  1155. if (pes->stream_type == STREAM_TYPE_METADATA &&
  1156. pes->stream_id == STREAM_ID_METADATA_STREAM &&
  1157. pes->st->codecpar->codec_id == AV_CODEC_ID_SMPTE_KLV &&
  1158. buf_size >= 5) {
  1159. /* skip metadata access unit header - see MISB ST 1402 */
  1160. pes->pes_header_size += 5;
  1161. p += 5;
  1162. buf_size -= 5;
  1163. }
  1164. if ( pes->ts->fix_teletext_pts
  1165. && ( pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT
  1166. || pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
  1167. ) {
  1168. AVProgram *p = NULL;
  1169. int pcr_found = 0;
  1170. while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
  1171. if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
  1172. MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
  1173. if (f) {
  1174. AVStream *st = NULL;
  1175. if (f->type == MPEGTS_PES) {
  1176. PESContext *pcrpes = f->u.pes_filter.opaque;
  1177. if (pcrpes)
  1178. st = pcrpes->st;
  1179. } else if (f->type == MPEGTS_PCR) {
  1180. int i;
  1181. for (i = 0; i < p->nb_stream_indexes; i++) {
  1182. AVStream *pst = pes->stream->streams[p->stream_index[i]];
  1183. if (pst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  1184. st = pst;
  1185. }
  1186. }
  1187. if (f->last_pcr != -1 && !f->discard) {
  1188. // teletext packets do not always have correct timestamps,
  1189. // the standard says they should be handled after 40.6 ms at most,
  1190. // and the pcr error to this packet should be no more than 100 ms.
  1191. // TODO: we should interpolate the PCR, not just use the last one
  1192. int64_t pcr = f->last_pcr / 300;
  1193. pcr_found = 1;
  1194. if (st) {
  1195. const FFStream *const sti = ffstream(st);
  1196. FFStream *const pes_sti = ffstream(pes->st);
  1197. pes_sti->pts_wrap_reference = sti->pts_wrap_reference;
  1198. pes_sti->pts_wrap_behavior = sti->pts_wrap_behavior;
  1199. }
  1200. if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
  1201. pes->pts = pes->dts = pcr;
  1202. } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT &&
  1203. pes->dts > pcr + 3654 + 9000) {
  1204. pes->pts = pes->dts = pcr + 3654 + 9000;
  1205. } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
  1206. pes->dts > pcr + 10*90000) { //10sec
  1207. pes->pts = pes->dts = pcr + 3654 + 9000;
  1208. }
  1209. break;
  1210. }
  1211. }
  1212. }
  1213. }
  1214. if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT &&
  1215. !pcr_found) {
  1216. av_log(pes->stream, AV_LOG_VERBOSE,
  1217. "Forcing DTS/PTS to be unset for a "
  1218. "non-trustworthy PES packet for PID %d as "
  1219. "PCR hasn't been received yet.\n",
  1220. pes->pid);
  1221. pes->dts = pes->pts = AV_NOPTS_VALUE;
  1222. }
  1223. }
  1224. }
  1225. break;
  1226. case MPEGTS_PAYLOAD:
  1227. do {
  1228. int max_packet_size = ts->max_packet_size;
  1229. if (pes->PES_packet_length && pes->PES_packet_length + PES_START_SIZE > pes->pes_header_size)
  1230. max_packet_size = pes->PES_packet_length + PES_START_SIZE - pes->pes_header_size;
  1231. if (pes->data_index > 0 &&
  1232. pes->data_index + buf_size > max_packet_size) {
  1233. ret = new_pes_packet(pes, ts->pkt);
  1234. if (ret < 0)
  1235. return ret;
  1236. pes->PES_packet_length = 0;
  1237. max_packet_size = ts->max_packet_size;
  1238. ts->stop_parse = 1;
  1239. } else if (pes->data_index == 0 &&
  1240. buf_size > max_packet_size) {
  1241. // pes packet size is < ts size packet and pes data is padded with 0xff
  1242. // not sure if this is legal in ts but see issue #2392
  1243. buf_size = max_packet_size;
  1244. }
  1245. if (!pes->buffer) {
  1246. pes->buffer = buffer_pool_get(ts, max_packet_size);
  1247. if (!pes->buffer)
  1248. return AVERROR(ENOMEM);
  1249. }
  1250. memcpy(pes->buffer->data + pes->data_index, p, buf_size);
  1251. pes->data_index += buf_size;
  1252. /* emit complete packets with known packet size
  1253. * decreases demuxer delay for infrequent packets like subtitles from
  1254. * a couple of seconds to milliseconds for properly muxed files. */
  1255. if (!ts->stop_parse && pes->PES_packet_length &&
  1256. pes->pes_header_size + pes->data_index == pes->PES_packet_length + PES_START_SIZE) {
  1257. ts->stop_parse = 1;
  1258. ret = new_pes_packet(pes, ts->pkt);
  1259. pes->state = MPEGTS_SKIP;
  1260. if (ret < 0)
  1261. return ret;
  1262. }
  1263. } while (0);
  1264. buf_size = 0;
  1265. break;
  1266. case MPEGTS_SKIP:
  1267. buf_size = 0;
  1268. break;
  1269. }
  1270. }
  1271. return 0;
  1272. }
  1273. static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
  1274. {
  1275. MpegTSFilter *tss;
  1276. PESContext *pes;
  1277. /* if no pid found, then add a pid context */
  1278. pes = av_mallocz(sizeof(PESContext));
  1279. if (!pes)
  1280. return 0;
  1281. pes->ts = ts;
  1282. pes->stream = ts->stream;
  1283. pes->pid = pid;
  1284. pes->pcr_pid = pcr_pid;
  1285. pes->state = MPEGTS_SKIP;
  1286. pes->pts = AV_NOPTS_VALUE;
  1287. pes->dts = AV_NOPTS_VALUE;
  1288. tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
  1289. if (!tss) {
  1290. av_free(pes);
  1291. return 0;
  1292. }
  1293. return pes;
  1294. }
  1295. #define MAX_LEVEL 4
  1296. typedef struct MP4DescrParseContext {
  1297. AVFormatContext *s;
  1298. FFIOContext pb;
  1299. Mp4Descr *descr;
  1300. Mp4Descr *active_descr;
  1301. int descr_count;
  1302. int max_descr_count;
  1303. int level;
  1304. int predefined_SLConfigDescriptor_seen;
  1305. } MP4DescrParseContext;
  1306. static int init_MP4DescrParseContext(MP4DescrParseContext *d, AVFormatContext *s,
  1307. const uint8_t *buf, unsigned size,
  1308. Mp4Descr *descr, int max_descr_count)
  1309. {
  1310. if (size > (1 << 30))
  1311. return AVERROR_INVALIDDATA;
  1312. ffio_init_read_context(&d->pb, buf, size);
  1313. d->s = s;
  1314. d->level = 0;
  1315. d->descr_count = 0;
  1316. d->descr = descr;
  1317. d->active_descr = NULL;
  1318. d->max_descr_count = max_descr_count;
  1319. return 0;
  1320. }
  1321. static void update_offsets(AVIOContext *pb, int64_t *off, int *len)
  1322. {
  1323. int64_t new_off = avio_tell(pb);
  1324. (*len) -= new_off - *off;
  1325. *off = new_off;
  1326. }
  1327. static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
  1328. int target_tag);
  1329. static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
  1330. {
  1331. while (len > 0) {
  1332. int ret = parse_mp4_descr(d, off, len, 0);
  1333. if (ret < 0)
  1334. return ret;
  1335. update_offsets(&d->pb.pub, &off, &len);
  1336. }
  1337. return 0;
  1338. }
  1339. static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1340. {
  1341. AVIOContext *const pb = &d->pb.pub;
  1342. avio_rb16(pb); // ID
  1343. avio_r8(pb);
  1344. avio_r8(pb);
  1345. avio_r8(pb);
  1346. avio_r8(pb);
  1347. avio_r8(pb);
  1348. update_offsets(pb, &off, &len);
  1349. return parse_mp4_descr_arr(d, off, len);
  1350. }
  1351. static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1352. {
  1353. int id_flags;
  1354. if (len < 2)
  1355. return 0;
  1356. id_flags = avio_rb16(&d->pb.pub);
  1357. if (!(id_flags & 0x0020)) { // URL_Flag
  1358. update_offsets(&d->pb.pub, &off, &len);
  1359. return parse_mp4_descr_arr(d, off, len); // ES_Descriptor[]
  1360. } else {
  1361. return 0;
  1362. }
  1363. }
  1364. static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1365. {
  1366. AVIOContext *const pb = &d->pb.pub;
  1367. int es_id = 0;
  1368. int ret = 0;
  1369. if (d->descr_count >= d->max_descr_count)
  1370. return AVERROR_INVALIDDATA;
  1371. ff_mp4_parse_es_descr(pb, &es_id);
  1372. d->active_descr = d->descr + (d->descr_count++);
  1373. d->active_descr->es_id = es_id;
  1374. update_offsets(pb, &off, &len);
  1375. if ((ret = parse_mp4_descr(d, off, len, MP4DecConfigDescrTag)) < 0)
  1376. return ret;
  1377. update_offsets(pb, &off, &len);
  1378. if (len > 0)
  1379. ret = parse_mp4_descr(d, off, len, MP4SLDescrTag);
  1380. d->active_descr = NULL;
  1381. return ret;
  1382. }
  1383. static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off,
  1384. int len)
  1385. {
  1386. Mp4Descr *descr = d->active_descr;
  1387. if (!descr)
  1388. return AVERROR_INVALIDDATA;
  1389. d->active_descr->dec_config_descr = av_malloc(len);
  1390. if (!descr->dec_config_descr)
  1391. return AVERROR(ENOMEM);
  1392. descr->dec_config_descr_len = len;
  1393. avio_read(&d->pb.pub, descr->dec_config_descr, len);
  1394. return 0;
  1395. }
  1396. static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1397. {
  1398. Mp4Descr *descr = d->active_descr;
  1399. AVIOContext *const pb = &d->pb.pub;
  1400. int predefined;
  1401. if (!descr)
  1402. return AVERROR_INVALIDDATA;
  1403. #define R8_CHECK_CLIP_MAX(dst, maxv) do { \
  1404. descr->sl.dst = avio_r8(pb); \
  1405. if (descr->sl.dst > maxv) { \
  1406. descr->sl.dst = maxv; \
  1407. return AVERROR_INVALIDDATA; \
  1408. } \
  1409. } while (0)
  1410. predefined = avio_r8(pb);
  1411. if (!predefined) {
  1412. int lengths;
  1413. int flags = avio_r8(pb);
  1414. descr->sl.use_au_start = !!(flags & 0x80);
  1415. descr->sl.use_au_end = !!(flags & 0x40);
  1416. descr->sl.use_rand_acc_pt = !!(flags & 0x20);
  1417. descr->sl.use_padding = !!(flags & 0x08);
  1418. descr->sl.use_timestamps = !!(flags & 0x04);
  1419. descr->sl.use_idle = !!(flags & 0x02);
  1420. descr->sl.timestamp_res = avio_rb32(pb);
  1421. avio_rb32(pb);
  1422. R8_CHECK_CLIP_MAX(timestamp_len, 63);
  1423. R8_CHECK_CLIP_MAX(ocr_len, 63);
  1424. R8_CHECK_CLIP_MAX(au_len, 31);
  1425. descr->sl.inst_bitrate_len = avio_r8(pb);
  1426. lengths = avio_rb16(pb);
  1427. descr->sl.degr_prior_len = lengths >> 12;
  1428. descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
  1429. descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
  1430. } else if (!d->predefined_SLConfigDescriptor_seen){
  1431. avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
  1432. d->predefined_SLConfigDescriptor_seen = 1;
  1433. }
  1434. return 0;
  1435. }
  1436. static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
  1437. int target_tag)
  1438. {
  1439. int tag;
  1440. AVIOContext *const pb = &d->pb.pub;
  1441. int len1 = ff_mp4_read_descr(d->s, pb, &tag);
  1442. int ret = 0;
  1443. update_offsets(pb, &off, &len);
  1444. if (len < 0 || len1 > len || len1 <= 0) {
  1445. av_log(d->s, AV_LOG_ERROR,
  1446. "Tag %x length violation new length %d bytes remaining %d\n",
  1447. tag, len1, len);
  1448. return AVERROR_INVALIDDATA;
  1449. }
  1450. if (d->level++ >= MAX_LEVEL) {
  1451. av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
  1452. ret = AVERROR_INVALIDDATA;
  1453. goto done;
  1454. }
  1455. if (target_tag && tag != target_tag) {
  1456. av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag,
  1457. target_tag);
  1458. ret = AVERROR_INVALIDDATA;
  1459. goto done;
  1460. }
  1461. switch (tag) {
  1462. case MP4IODescrTag:
  1463. ret = parse_MP4IODescrTag(d, off, len1);
  1464. break;
  1465. case MP4ODescrTag:
  1466. ret = parse_MP4ODescrTag(d, off, len1);
  1467. break;
  1468. case MP4ESDescrTag:
  1469. ret = parse_MP4ESDescrTag(d, off, len1);
  1470. break;
  1471. case MP4DecConfigDescrTag:
  1472. ret = parse_MP4DecConfigDescrTag(d, off, len1);
  1473. break;
  1474. case MP4SLDescrTag:
  1475. ret = parse_MP4SLDescrTag(d, off, len1);
  1476. break;
  1477. }
  1478. done:
  1479. d->level--;
  1480. avio_seek(pb, off + len1, SEEK_SET);
  1481. return ret;
  1482. }
  1483. static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
  1484. Mp4Descr *descr, int *descr_count, int max_descr_count)
  1485. {
  1486. MP4DescrParseContext d;
  1487. int ret;
  1488. d.predefined_SLConfigDescriptor_seen = 0;
  1489. ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
  1490. if (ret < 0)
  1491. return ret;
  1492. ret = parse_mp4_descr(&d, avio_tell(&d.pb.pub), size, MP4IODescrTag);
  1493. *descr_count = d.descr_count;
  1494. return ret;
  1495. }
  1496. static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
  1497. Mp4Descr *descr, int *descr_count, int max_descr_count)
  1498. {
  1499. MP4DescrParseContext d;
  1500. int ret;
  1501. ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
  1502. if (ret < 0)
  1503. return ret;
  1504. ret = parse_mp4_descr_arr(&d, avio_tell(&d.pb.pub), size);
  1505. *descr_count = d.descr_count;
  1506. return ret;
  1507. }
  1508. static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section,
  1509. int section_len)
  1510. {
  1511. MpegTSContext *ts = filter->u.section_filter.opaque;
  1512. MpegTSSectionFilter *tssf = &filter->u.section_filter;
  1513. SectionHeader h;
  1514. const uint8_t *p, *p_end;
  1515. int mp4_descr_count = 0;
  1516. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
  1517. int i, pid;
  1518. AVFormatContext *s = ts->stream;
  1519. p_end = section + section_len - 4;
  1520. p = section;
  1521. if (parse_section_header(&h, &p, p_end) < 0)
  1522. return;
  1523. if (h.tid != M4OD_TID)
  1524. return;
  1525. if (skip_identical(&h, tssf))
  1526. return;
  1527. mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count,
  1528. MAX_MP4_DESCR_COUNT);
  1529. for (pid = 0; pid < NB_PID_MAX; pid++) {
  1530. if (!ts->pids[pid])
  1531. continue;
  1532. for (i = 0; i < mp4_descr_count; i++) {
  1533. PESContext *pes;
  1534. AVStream *st;
  1535. FFStream *sti;
  1536. FFIOContext pb;
  1537. if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
  1538. continue;
  1539. if (ts->pids[pid]->type != MPEGTS_PES) {
  1540. av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
  1541. continue;
  1542. }
  1543. pes = ts->pids[pid]->u.pes_filter.opaque;
  1544. st = pes->st;
  1545. if (!st)
  1546. continue;
  1547. sti = ffstream(st);
  1548. pes->sl = mp4_descr[i].sl;
  1549. ffio_init_read_context(&pb, mp4_descr[i].dec_config_descr,
  1550. mp4_descr[i].dec_config_descr_len);
  1551. ff_mp4_read_dec_config_descr(s, st, &pb.pub);
  1552. if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
  1553. st->codecpar->extradata_size > 0)
  1554. sti->need_parsing = 0;
  1555. if (st->codecpar->codec_id == AV_CODEC_ID_H264 &&
  1556. st->codecpar->extradata_size > 0)
  1557. sti->need_parsing = 0;
  1558. st->codecpar->codec_type = avcodec_get_type(st->codecpar->codec_id);
  1559. sti->need_context_update = 1;
  1560. }
  1561. }
  1562. for (i = 0; i < mp4_descr_count; i++)
  1563. av_free(mp4_descr[i].dec_config_descr);
  1564. }
  1565. static void scte_data_cb(MpegTSFilter *filter, const uint8_t *section,
  1566. int section_len)
  1567. {
  1568. AVProgram *prg = NULL;
  1569. MpegTSContext *ts = filter->u.section_filter.opaque;
  1570. int idx = ff_find_stream_index(ts->stream, filter->pid);
  1571. if (idx < 0)
  1572. return;
  1573. /**
  1574. * In case we receive an SCTE-35 packet before mpegts context is fully
  1575. * initialized.
  1576. */
  1577. if (!ts->pkt)
  1578. return;
  1579. new_data_packet(section, section_len, ts->pkt);
  1580. ts->pkt->stream_index = idx;
  1581. prg = av_find_program_from_stream(ts->stream, NULL, idx);
  1582. if (prg && prg->pcr_pid != -1 && prg->discard != AVDISCARD_ALL) {
  1583. MpegTSFilter *f = ts->pids[prg->pcr_pid];
  1584. if (f && f->last_pcr != -1)
  1585. ts->pkt->pts = ts->pkt->dts = f->last_pcr/300;
  1586. }
  1587. ts->stop_parse = 1;
  1588. }
  1589. static const uint8_t opus_coupled_stream_cnt[9] = {
  1590. 1, 0, 1, 1, 2, 2, 2, 3, 3
  1591. };
  1592. static const uint8_t opus_stream_cnt[9] = {
  1593. 1, 1, 1, 2, 2, 3, 4, 4, 5,
  1594. };
  1595. static const uint8_t opus_channel_map[8][8] = {
  1596. { 0 },
  1597. { 0,1 },
  1598. { 0,2,1 },
  1599. { 0,1,2,3 },
  1600. { 0,4,1,2,3 },
  1601. { 0,4,1,2,3,5 },
  1602. { 0,4,1,2,3,5,6 },
  1603. { 0,6,1,2,3,4,5,7 },
  1604. };
  1605. int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
  1606. const uint8_t **pp, const uint8_t *desc_list_end,
  1607. Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
  1608. MpegTSContext *ts)
  1609. {
  1610. FFStream *const sti = ffstream(st);
  1611. const uint8_t *desc_end;
  1612. int desc_len, desc_tag, desc_es_id, ext_desc_tag, channels, channel_config_code;
  1613. char language[252];
  1614. int i;
  1615. desc_tag = get8(pp, desc_list_end);
  1616. if (desc_tag < 0)
  1617. return AVERROR_INVALIDDATA;
  1618. desc_len = get8(pp, desc_list_end);
  1619. if (desc_len < 0)
  1620. return AVERROR_INVALIDDATA;
  1621. desc_end = *pp + desc_len;
  1622. if (desc_end > desc_list_end)
  1623. return AVERROR_INVALIDDATA;
  1624. av_log(fc, AV_LOG_TRACE, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
  1625. if ((st->codecpar->codec_id == AV_CODEC_ID_NONE || sti->request_probe > 0) &&
  1626. stream_type == STREAM_TYPE_PRIVATE_DATA)
  1627. mpegts_find_stream_type(st, desc_tag, DESC_types);
  1628. switch (desc_tag) {
  1629. case VIDEO_STREAM_DESCRIPTOR:
  1630. if (get8(pp, desc_end) & 0x1) {
  1631. st->disposition |= AV_DISPOSITION_STILL_IMAGE;
  1632. }
  1633. break;
  1634. case SL_DESCRIPTOR:
  1635. desc_es_id = get16(pp, desc_end);
  1636. if (desc_es_id < 0)
  1637. break;
  1638. if (ts && ts->pids[pid])
  1639. ts->pids[pid]->es_id = desc_es_id;
  1640. for (i = 0; i < mp4_descr_count; i++)
  1641. if (mp4_descr[i].dec_config_descr_len &&
  1642. mp4_descr[i].es_id == desc_es_id) {
  1643. FFIOContext pb;
  1644. ffio_init_read_context(&pb, mp4_descr[i].dec_config_descr,
  1645. mp4_descr[i].dec_config_descr_len);
  1646. ff_mp4_read_dec_config_descr(fc, st, &pb.pub);
  1647. if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
  1648. st->codecpar->extradata_size > 0) {
  1649. sti->need_parsing = 0;
  1650. sti->need_context_update = 1;
  1651. }
  1652. if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
  1653. mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
  1654. }
  1655. break;
  1656. case FMC_DESCRIPTOR:
  1657. if (get16(pp, desc_end) < 0)
  1658. break;
  1659. if (mp4_descr_count > 0 &&
  1660. (st->codecpar->codec_id == AV_CODEC_ID_AAC_LATM ||
  1661. (sti->request_probe == 0 && st->codecpar->codec_id == AV_CODEC_ID_NONE) ||
  1662. sti->request_probe > 0) &&
  1663. mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
  1664. FFIOContext pb;
  1665. ffio_init_read_context(&pb, mp4_descr->dec_config_descr,
  1666. mp4_descr->dec_config_descr_len);
  1667. ff_mp4_read_dec_config_descr(fc, st, &pb.pub);
  1668. if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
  1669. st->codecpar->extradata_size > 0) {
  1670. sti->request_probe = sti->need_parsing = 0;
  1671. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  1672. sti->need_context_update = 1;
  1673. }
  1674. }
  1675. break;
  1676. case 0x56: /* DVB teletext descriptor */
  1677. {
  1678. uint8_t *extradata = NULL;
  1679. int language_count = desc_len / 5, ret;
  1680. if (desc_len > 0 && desc_len % 5 != 0)
  1681. return AVERROR_INVALIDDATA;
  1682. if (language_count > 0) {
  1683. /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
  1684. av_assert0(language_count <= sizeof(language) / 4);
  1685. if (st->codecpar->extradata == NULL) {
  1686. ret = ff_alloc_extradata(st->codecpar, language_count * 2);
  1687. if (ret < 0)
  1688. return ret;
  1689. }
  1690. if (st->codecpar->extradata_size < language_count * 2)
  1691. return AVERROR_INVALIDDATA;
  1692. extradata = st->codecpar->extradata;
  1693. for (i = 0; i < language_count; i++) {
  1694. language[i * 4 + 0] = get8(pp, desc_end);
  1695. language[i * 4 + 1] = get8(pp, desc_end);
  1696. language[i * 4 + 2] = get8(pp, desc_end);
  1697. language[i * 4 + 3] = ',';
  1698. memcpy(extradata, *pp, 2);
  1699. extradata += 2;
  1700. *pp += 2;
  1701. }
  1702. language[i * 4 - 1] = 0;
  1703. av_dict_set(&st->metadata, "language", language, 0);
  1704. sti->need_context_update = 1;
  1705. }
  1706. }
  1707. break;
  1708. case 0x59: /* subtitling descriptor */
  1709. {
  1710. /* 8 bytes per DVB subtitle substream data:
  1711. * ISO_639_language_code (3 bytes),
  1712. * subtitling_type (1 byte),
  1713. * composition_page_id (2 bytes),
  1714. * ancillary_page_id (2 bytes) */
  1715. int language_count = desc_len / 8, ret;
  1716. if (desc_len > 0 && desc_len % 8 != 0)
  1717. return AVERROR_INVALIDDATA;
  1718. if (language_count > 1) {
  1719. avpriv_request_sample(fc, "DVB subtitles with multiple languages");
  1720. }
  1721. if (language_count > 0) {
  1722. uint8_t *extradata;
  1723. /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
  1724. av_assert0(language_count <= sizeof(language) / 4);
  1725. if (st->codecpar->extradata == NULL) {
  1726. ret = ff_alloc_extradata(st->codecpar, language_count * 5);
  1727. if (ret < 0)
  1728. return ret;
  1729. }
  1730. if (st->codecpar->extradata_size < language_count * 5)
  1731. return AVERROR_INVALIDDATA;
  1732. extradata = st->codecpar->extradata;
  1733. for (i = 0; i < language_count; i++) {
  1734. language[i * 4 + 0] = get8(pp, desc_end);
  1735. language[i * 4 + 1] = get8(pp, desc_end);
  1736. language[i * 4 + 2] = get8(pp, desc_end);
  1737. language[i * 4 + 3] = ',';
  1738. /* hearing impaired subtitles detection using subtitling_type */
  1739. switch (*pp[0]) {
  1740. case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
  1741. case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
  1742. case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
  1743. case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
  1744. case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
  1745. case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
  1746. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1747. break;
  1748. }
  1749. extradata[4] = get8(pp, desc_end); /* subtitling_type */
  1750. memcpy(extradata, *pp, 4); /* composition_page_id and ancillary_page_id */
  1751. extradata += 5;
  1752. *pp += 4;
  1753. }
  1754. language[i * 4 - 1] = 0;
  1755. av_dict_set(&st->metadata, "language", language, 0);
  1756. sti->need_context_update = 1;
  1757. }
  1758. }
  1759. break;
  1760. case ISO_639_LANGUAGE_DESCRIPTOR:
  1761. for (i = 0; i + 4 <= desc_len; i += 4) {
  1762. language[i + 0] = get8(pp, desc_end);
  1763. language[i + 1] = get8(pp, desc_end);
  1764. language[i + 2] = get8(pp, desc_end);
  1765. language[i + 3] = ',';
  1766. switch (get8(pp, desc_end)) {
  1767. case 0x01:
  1768. st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;
  1769. break;
  1770. case 0x02:
  1771. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1772. break;
  1773. case 0x03:
  1774. st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
  1775. st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
  1776. break;
  1777. }
  1778. }
  1779. if (i && language[0]) {
  1780. language[i - 1] = 0;
  1781. /* don't overwrite language, as it may already have been set by
  1782. * another, more specific descriptor (e.g. supplementary audio) */
  1783. av_dict_set(&st->metadata, "language", language, AV_DICT_DONT_OVERWRITE);
  1784. }
  1785. break;
  1786. case REGISTRATION_DESCRIPTOR:
  1787. st->codecpar->codec_tag = bytestream_get_le32(pp);
  1788. av_log(fc, AV_LOG_TRACE, "reg_desc=%.4s\n", (char *)&st->codecpar->codec_tag);
  1789. if (st->codecpar->codec_id == AV_CODEC_ID_NONE || sti->request_probe > 0) {
  1790. mpegts_find_stream_type(st, st->codecpar->codec_tag, REGD_types);
  1791. if (st->codecpar->codec_tag == MKTAG('B', 'S', 'S', 'D'))
  1792. sti->request_probe = 50;
  1793. }
  1794. break;
  1795. case 0x52: /* stream identifier descriptor */
  1796. sti->stream_identifier = 1 + get8(pp, desc_end);
  1797. break;
  1798. case METADATA_DESCRIPTOR:
  1799. if (get16(pp, desc_end) == 0xFFFF)
  1800. *pp += 4;
  1801. if (get8(pp, desc_end) == 0xFF) {
  1802. st->codecpar->codec_tag = bytestream_get_le32(pp);
  1803. if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
  1804. mpegts_find_stream_type(st, st->codecpar->codec_tag, METADATA_types);
  1805. }
  1806. break;
  1807. case 0x7f: /* DVB extension descriptor */
  1808. ext_desc_tag = get8(pp, desc_end);
  1809. if (ext_desc_tag < 0)
  1810. return AVERROR_INVALIDDATA;
  1811. if (st->codecpar->codec_id == AV_CODEC_ID_OPUS &&
  1812. ext_desc_tag == 0x80) { /* User defined (provisional Opus) */
  1813. if (!st->codecpar->extradata) {
  1814. st->codecpar->extradata = av_mallocz(sizeof(opus_default_extradata) +
  1815. AV_INPUT_BUFFER_PADDING_SIZE);
  1816. if (!st->codecpar->extradata)
  1817. return AVERROR(ENOMEM);
  1818. st->codecpar->extradata_size = sizeof(opus_default_extradata);
  1819. memcpy(st->codecpar->extradata, opus_default_extradata, sizeof(opus_default_extradata));
  1820. channel_config_code = get8(pp, desc_end);
  1821. if (channel_config_code < 0)
  1822. return AVERROR_INVALIDDATA;
  1823. if (channel_config_code <= 0x8) {
  1824. st->codecpar->extradata[9] = channels = channel_config_code ? channel_config_code : 2;
  1825. AV_WL32(&st->codecpar->extradata[12], 48000);
  1826. st->codecpar->extradata[18] = channel_config_code ? (channels > 2) : /* Dual Mono */ 255;
  1827. st->codecpar->extradata[19] = opus_stream_cnt[channel_config_code];
  1828. st->codecpar->extradata[20] = opus_coupled_stream_cnt[channel_config_code];
  1829. memcpy(&st->codecpar->extradata[21], opus_channel_map[channels - 1], channels);
  1830. st->codecpar->extradata_size = st->codecpar->extradata[18] ? 21 + channels : 19;
  1831. } else {
  1832. avpriv_request_sample(fc, "Opus in MPEG-TS - channel_config_code > 0x8");
  1833. }
  1834. sti->need_parsing = AVSTREAM_PARSE_FULL;
  1835. sti->need_context_update = 1;
  1836. }
  1837. }
  1838. if (ext_desc_tag == 0x06) { /* supplementary audio descriptor */
  1839. int flags;
  1840. if (desc_len < 1)
  1841. return AVERROR_INVALIDDATA;
  1842. flags = get8(pp, desc_end);
  1843. if ((flags & 0x80) == 0) /* mix_type */
  1844. st->disposition |= AV_DISPOSITION_DEPENDENT;
  1845. switch ((flags >> 2) & 0x1F) { /* editorial_classification */
  1846. case 0x01:
  1847. st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
  1848. st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
  1849. break;
  1850. case 0x02:
  1851. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1852. break;
  1853. case 0x03:
  1854. st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
  1855. break;
  1856. }
  1857. if (flags & 0x01) { /* language_code_present */
  1858. if (desc_len < 4)
  1859. return AVERROR_INVALIDDATA;
  1860. language[0] = get8(pp, desc_end);
  1861. language[1] = get8(pp, desc_end);
  1862. language[2] = get8(pp, desc_end);
  1863. language[3] = 0;
  1864. /* This language always has to override a possible
  1865. * ISO 639 language descriptor language */
  1866. if (language[0])
  1867. av_dict_set(&st->metadata, "language", language, 0);
  1868. }
  1869. }
  1870. break;
  1871. case 0x6a: /* ac-3_descriptor */
  1872. {
  1873. int component_type_flag = get8(pp, desc_end) & (1 << 7);
  1874. if (component_type_flag) {
  1875. int component_type = get8(pp, desc_end);
  1876. int service_type_mask = 0x38; // 0b00111000
  1877. int service_type = ((component_type & service_type_mask) >> 3);
  1878. if (service_type == 0x02 /* 0b010 */) {
  1879. st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
  1880. av_log(ts ? ts->stream : fc, AV_LOG_DEBUG, "New track disposition for id %u: %u\n", st->id, st->disposition);
  1881. }
  1882. }
  1883. }
  1884. break;
  1885. case 0x7a: /* enhanced_ac-3_descriptor */
  1886. {
  1887. int component_type_flag = get8(pp, desc_end) & (1 << 7);
  1888. if (component_type_flag) {
  1889. int component_type = get8(pp, desc_end);
  1890. int service_type_mask = 0x38; // 0b00111000
  1891. int service_type = ((component_type & service_type_mask) >> 3);
  1892. if (service_type == 0x02 /* 0b010 */) {
  1893. st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
  1894. av_log(ts ? ts->stream : fc, AV_LOG_DEBUG, "New track disposition for id %u: %u\n", st->id, st->disposition);
  1895. }
  1896. }
  1897. }
  1898. break;
  1899. case 0xfd: /* ARIB data coding type descriptor */
  1900. // STD-B24, fascicle 3, chapter 4 defines private_stream_1
  1901. // for captions
  1902. if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
  1903. // This structure is defined in STD-B10, part 1, listing 5.4 and
  1904. // part 2, 6.2.20).
  1905. // Listing of data_component_ids is in STD-B10, part 2, Annex J.
  1906. // Component tag limits are documented in TR-B14, fascicle 2,
  1907. // Vol. 3, Section 2, 4.2.8.1
  1908. int actual_component_tag = sti->stream_identifier - 1;
  1909. int picked_profile = AV_PROFILE_UNKNOWN;
  1910. int data_component_id = get16(pp, desc_end);
  1911. if (data_component_id < 0)
  1912. return AVERROR_INVALIDDATA;
  1913. switch (data_component_id) {
  1914. case 0x0008:
  1915. // [0x30..0x37] are component tags utilized for
  1916. // non-mobile captioning service ("profile A").
  1917. if (actual_component_tag >= 0x30 &&
  1918. actual_component_tag <= 0x37) {
  1919. picked_profile = AV_PROFILE_ARIB_PROFILE_A;
  1920. }
  1921. break;
  1922. case 0x0012:
  1923. // component tag 0x87 signifies a mobile/partial reception
  1924. // (1seg) captioning service ("profile C").
  1925. if (actual_component_tag == 0x87) {
  1926. picked_profile = AV_PROFILE_ARIB_PROFILE_C;
  1927. }
  1928. break;
  1929. default:
  1930. break;
  1931. }
  1932. if (picked_profile == AV_PROFILE_UNKNOWN)
  1933. break;
  1934. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1935. st->codecpar->codec_id = AV_CODEC_ID_ARIB_CAPTION;
  1936. if (st->codecpar->profile != picked_profile) {
  1937. st->codecpar->profile = picked_profile;
  1938. sti->need_context_update = 1;
  1939. }
  1940. sti->request_probe = 0;
  1941. sti->need_parsing = 0;
  1942. }
  1943. break;
  1944. case 0xb0: /* DOVI video stream descriptor */
  1945. {
  1946. uint32_t buf;
  1947. AVDOVIDecoderConfigurationRecord *dovi;
  1948. size_t dovi_size;
  1949. int dependency_pid = -1; // Unset
  1950. if (desc_end - *pp < 4) // (8 + 8 + 7 + 6 + 1 + 1 + 1) / 8
  1951. return AVERROR_INVALIDDATA;
  1952. dovi = av_dovi_alloc(&dovi_size);
  1953. if (!dovi)
  1954. return AVERROR(ENOMEM);
  1955. dovi->dv_version_major = get8(pp, desc_end);
  1956. dovi->dv_version_minor = get8(pp, desc_end);
  1957. buf = get16(pp, desc_end);
  1958. dovi->dv_profile = (buf >> 9) & 0x7f; // 7 bits
  1959. dovi->dv_level = (buf >> 3) & 0x3f; // 6 bits
  1960. dovi->rpu_present_flag = (buf >> 2) & 0x01; // 1 bit
  1961. dovi->el_present_flag = (buf >> 1) & 0x01; // 1 bit
  1962. dovi->bl_present_flag = buf & 0x01; // 1 bit
  1963. if (!dovi->bl_present_flag && desc_end - *pp >= 2) {
  1964. buf = get16(pp, desc_end);
  1965. dependency_pid = buf >> 3; // 13 bits
  1966. }
  1967. if (desc_end - *pp >= 1) { // 8 bits
  1968. buf = get8(pp, desc_end);
  1969. dovi->dv_bl_signal_compatibility_id = (buf >> 4) & 0x0f; // 4 bits
  1970. dovi->dv_md_compression = (buf >> 2) & 0x03; // 2 bits
  1971. } else {
  1972. // 0 stands for None
  1973. // Dolby Vision V1.2.93 profiles and levels
  1974. dovi->dv_bl_signal_compatibility_id = 0;
  1975. dovi->dv_md_compression = AV_DOVI_COMPRESSION_NONE;
  1976. }
  1977. if (!av_packet_side_data_add(&st->codecpar->coded_side_data,
  1978. &st->codecpar->nb_coded_side_data,
  1979. AV_PKT_DATA_DOVI_CONF,
  1980. (uint8_t *)dovi, dovi_size, 0)) {
  1981. av_free(dovi);
  1982. return AVERROR(ENOMEM);
  1983. }
  1984. av_log(fc, AV_LOG_TRACE, "DOVI, version: %d.%d, profile: %d, level: %d, "
  1985. "rpu flag: %d, el flag: %d, bl flag: %d, dependency_pid: %d, "
  1986. "compatibility id: %d, compression: %d\n",
  1987. dovi->dv_version_major, dovi->dv_version_minor,
  1988. dovi->dv_profile, dovi->dv_level,
  1989. dovi->rpu_present_flag,
  1990. dovi->el_present_flag,
  1991. dovi->bl_present_flag,
  1992. dependency_pid,
  1993. dovi->dv_bl_signal_compatibility_id,
  1994. dovi->dv_md_compression);
  1995. }
  1996. break;
  1997. default:
  1998. break;
  1999. }
  2000. *pp = desc_end;
  2001. return 0;
  2002. }
  2003. static AVStream *find_matching_stream(MpegTSContext *ts, int pid, unsigned int programid,
  2004. int stream_identifier, int pmt_stream_idx, struct Program *p)
  2005. {
  2006. AVFormatContext *s = ts->stream;
  2007. AVStream *found = NULL;
  2008. if (stream_identifier) { /* match based on "stream identifier descriptor" if present */
  2009. for (int i = 0; i < p->nb_streams; i++) {
  2010. if (p->streams[i].stream_identifier == stream_identifier)
  2011. if (!found || pmt_stream_idx == i) /* fallback to idx based guess if multiple streams have the same identifier */
  2012. found = s->streams[p->streams[i].idx];
  2013. }
  2014. } else if (pmt_stream_idx < p->nb_streams) { /* match based on position within the PMT */
  2015. found = s->streams[p->streams[pmt_stream_idx].idx];
  2016. }
  2017. if (found) {
  2018. av_log(ts->stream, AV_LOG_VERBOSE,
  2019. "re-using existing %s stream %d (pid=0x%x) for new pid=0x%x\n",
  2020. av_get_media_type_string(found->codecpar->codec_type),
  2021. found->index, found->id, pid);
  2022. }
  2023. return found;
  2024. }
  2025. static int parse_stream_identifier_desc(const uint8_t *p, const uint8_t *p_end)
  2026. {
  2027. const uint8_t **pp = &p;
  2028. const uint8_t *desc_list_end;
  2029. const uint8_t *desc_end;
  2030. int desc_list_len;
  2031. int desc_len, desc_tag;
  2032. desc_list_len = get16(pp, p_end);
  2033. if (desc_list_len < 0)
  2034. return -1;
  2035. desc_list_len &= 0xfff;
  2036. desc_list_end = p + desc_list_len;
  2037. if (desc_list_end > p_end)
  2038. return -1;
  2039. while (1) {
  2040. desc_tag = get8(pp, desc_list_end);
  2041. if (desc_tag < 0)
  2042. return -1;
  2043. desc_len = get8(pp, desc_list_end);
  2044. if (desc_len < 0)
  2045. return -1;
  2046. desc_end = *pp + desc_len;
  2047. if (desc_end > desc_list_end)
  2048. return -1;
  2049. if (desc_tag == 0x52) {
  2050. return get8(pp, desc_end);
  2051. }
  2052. *pp = desc_end;
  2053. }
  2054. return -1;
  2055. }
  2056. static int is_pes_stream(int stream_type, uint32_t prog_reg_desc)
  2057. {
  2058. return !(stream_type == 0x13 ||
  2059. (stream_type == 0x86 && prog_reg_desc == AV_RL32("CUEI")) );
  2060. }
  2061. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  2062. {
  2063. MpegTSContext *ts = filter->u.section_filter.opaque;
  2064. MpegTSSectionFilter *tssf = &filter->u.section_filter;
  2065. struct Program old_program;
  2066. SectionHeader h1, *h = &h1;
  2067. PESContext *pes;
  2068. AVStream *st;
  2069. const uint8_t *p, *p_end, *desc_list_end;
  2070. int program_info_length, pcr_pid, pid, stream_type;
  2071. int desc_list_len;
  2072. uint32_t prog_reg_desc = 0; /* registration descriptor */
  2073. int stream_identifier = -1;
  2074. struct Program *prg;
  2075. int mp4_descr_count = 0;
  2076. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
  2077. int i;
  2078. av_log(ts->stream, AV_LOG_TRACE, "PMT: len %i\n", section_len);
  2079. hex_dump_debug(ts->stream, section, section_len);
  2080. p_end = section + section_len - 4;
  2081. p = section;
  2082. if (parse_section_header(h, &p, p_end) < 0)
  2083. return;
  2084. if (h->tid != PMT_TID)
  2085. return;
  2086. if (!h->current_next)
  2087. return;
  2088. if (skip_identical(h, tssf))
  2089. return;
  2090. av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x sec_num=%d/%d version=%d tid=%d\n",
  2091. h->id, h->sec_num, h->last_sec_num, h->version, h->tid);
  2092. if (!ts->scan_all_pmts && ts->skip_changes)
  2093. return;
  2094. prg = get_program(ts, h->id);
  2095. if (prg)
  2096. old_program = *prg;
  2097. else
  2098. clear_program(&old_program);
  2099. if (ts->skip_unknown_pmt && !prg)
  2100. return;
  2101. if (prg && prg->nb_pids && prg->pids[0] != ts->current_pid)
  2102. return;
  2103. if (!ts->skip_clear)
  2104. clear_avprogram(ts, h->id);
  2105. clear_program(prg);
  2106. add_pid_to_program(prg, ts->current_pid);
  2107. pcr_pid = get16(&p, p_end);
  2108. if (pcr_pid < 0)
  2109. return;
  2110. pcr_pid &= 0x1fff;
  2111. add_pid_to_program(prg, pcr_pid);
  2112. update_av_program_info(ts->stream, h->id, pcr_pid, h->version);
  2113. av_log(ts->stream, AV_LOG_TRACE, "pcr_pid=0x%x\n", pcr_pid);
  2114. program_info_length = get16(&p, p_end);
  2115. if (program_info_length < 0)
  2116. return;
  2117. program_info_length &= 0xfff;
  2118. while (program_info_length >= 2) {
  2119. uint8_t tag, len;
  2120. tag = get8(&p, p_end);
  2121. len = get8(&p, p_end);
  2122. av_log(ts->stream, AV_LOG_TRACE, "program tag: 0x%02x len=%d\n", tag, len);
  2123. program_info_length -= 2;
  2124. if (len > program_info_length)
  2125. // something else is broken, exit the program_descriptors_loop
  2126. break;
  2127. program_info_length -= len;
  2128. if (tag == IOD_DESCRIPTOR) {
  2129. get8(&p, p_end); // scope
  2130. get8(&p, p_end); // label
  2131. len -= 2;
  2132. mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
  2133. &mp4_descr_count, MAX_MP4_DESCR_COUNT);
  2134. } else if (tag == REGISTRATION_DESCRIPTOR && len >= 4) {
  2135. prog_reg_desc = bytestream_get_le32(&p);
  2136. len -= 4;
  2137. }
  2138. p += len;
  2139. }
  2140. p += program_info_length;
  2141. if (p >= p_end)
  2142. goto out;
  2143. // stop parsing after pmt, we found header
  2144. if (!ts->pkt)
  2145. ts->stop_parse = 2;
  2146. if (prg)
  2147. prg->pmt_found = 1;
  2148. for (i = 0; i < MAX_STREAMS_PER_PROGRAM; i++) {
  2149. st = 0;
  2150. pes = NULL;
  2151. stream_type = get8(&p, p_end);
  2152. if (stream_type < 0)
  2153. break;
  2154. pid = get16(&p, p_end);
  2155. if (pid < 0)
  2156. goto out;
  2157. pid &= 0x1fff;
  2158. if (pid == ts->current_pid)
  2159. goto out;
  2160. stream_identifier = parse_stream_identifier_desc(p, p_end) + 1;
  2161. /* now create stream */
  2162. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  2163. pes = ts->pids[pid]->u.pes_filter.opaque;
  2164. if (ts->merge_pmt_versions && !pes->st) {
  2165. st = find_matching_stream(ts, pid, h->id, stream_identifier, i, &old_program);
  2166. if (st) {
  2167. pes->st = st;
  2168. pes->stream_type = stream_type;
  2169. pes->merged_st = 1;
  2170. }
  2171. }
  2172. if (!pes->st) {
  2173. pes->st = avformat_new_stream(pes->stream, NULL);
  2174. if (!pes->st)
  2175. goto out;
  2176. pes->st->id = pes->pid;
  2177. }
  2178. st = pes->st;
  2179. } else if (is_pes_stream(stream_type, prog_reg_desc)) {
  2180. if (ts->pids[pid])
  2181. mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
  2182. pes = add_pes_stream(ts, pid, pcr_pid);
  2183. if (ts->merge_pmt_versions && pes && !pes->st) {
  2184. st = find_matching_stream(ts, pid, h->id, stream_identifier, i, &old_program);
  2185. if (st) {
  2186. pes->st = st;
  2187. pes->stream_type = stream_type;
  2188. pes->merged_st = 1;
  2189. }
  2190. }
  2191. if (pes && !pes->st) {
  2192. st = avformat_new_stream(pes->stream, NULL);
  2193. if (!st)
  2194. goto out;
  2195. st->id = pes->pid;
  2196. }
  2197. } else {
  2198. int idx = ff_find_stream_index(ts->stream, pid);
  2199. if (idx >= 0) {
  2200. st = ts->stream->streams[idx];
  2201. }
  2202. if (ts->merge_pmt_versions && !st) {
  2203. st = find_matching_stream(ts, pid, h->id, stream_identifier, i, &old_program);
  2204. }
  2205. if (!st) {
  2206. st = avformat_new_stream(ts->stream, NULL);
  2207. if (!st)
  2208. goto out;
  2209. st->id = pid;
  2210. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  2211. if (stream_type == 0x86 && prog_reg_desc == AV_RL32("CUEI")) {
  2212. mpegts_find_stream_type(st, stream_type, SCTE_types);
  2213. mpegts_open_section_filter(ts, pid, scte_data_cb, ts, 1);
  2214. }
  2215. }
  2216. }
  2217. if (!st)
  2218. goto out;
  2219. if (pes && !pes->stream_type)
  2220. mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
  2221. add_pid_to_program(prg, pid);
  2222. if (prg) {
  2223. prg->streams[i].idx = st->index;
  2224. prg->streams[i].stream_identifier = stream_identifier;
  2225. prg->nb_streams++;
  2226. }
  2227. av_program_add_stream_index(ts->stream, h->id, st->index);
  2228. desc_list_len = get16(&p, p_end);
  2229. if (desc_list_len < 0)
  2230. goto out;
  2231. desc_list_len &= 0xfff;
  2232. desc_list_end = p + desc_list_len;
  2233. if (desc_list_end > p_end)
  2234. goto out;
  2235. for (;;) {
  2236. if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
  2237. desc_list_end, mp4_descr,
  2238. mp4_descr_count, pid, ts) < 0)
  2239. break;
  2240. if (pes && prog_reg_desc == AV_RL32("HDMV") &&
  2241. stream_type == 0x83 && pes->sub_st) {
  2242. av_program_add_stream_index(ts->stream, h->id,
  2243. pes->sub_st->index);
  2244. pes->sub_st->codecpar->codec_tag = st->codecpar->codec_tag;
  2245. }
  2246. }
  2247. p = desc_list_end;
  2248. }
  2249. if (!ts->pids[pcr_pid])
  2250. mpegts_open_pcr_filter(ts, pcr_pid);
  2251. out:
  2252. for (i = 0; i < mp4_descr_count; i++)
  2253. av_free(mp4_descr[i].dec_config_descr);
  2254. }
  2255. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  2256. {
  2257. MpegTSContext *ts = filter->u.section_filter.opaque;
  2258. MpegTSSectionFilter *tssf = &filter->u.section_filter;
  2259. SectionHeader h1, *h = &h1;
  2260. const uint8_t *p, *p_end;
  2261. int sid, pmt_pid;
  2262. int nb_prg = 0;
  2263. AVProgram *program;
  2264. av_log(ts->stream, AV_LOG_TRACE, "PAT:\n");
  2265. hex_dump_debug(ts->stream, section, section_len);
  2266. p_end = section + section_len - 4;
  2267. p = section;
  2268. if (parse_section_header(h, &p, p_end) < 0)
  2269. return;
  2270. if (h->tid != PAT_TID)
  2271. return;
  2272. if (!h->current_next)
  2273. return;
  2274. if (ts->skip_changes)
  2275. return;
  2276. if (skip_identical(h, tssf))
  2277. return;
  2278. ts->id = h->id;
  2279. for (;;) {
  2280. sid = get16(&p, p_end);
  2281. if (sid < 0)
  2282. break;
  2283. pmt_pid = get16(&p, p_end);
  2284. if (pmt_pid < 0)
  2285. break;
  2286. pmt_pid &= 0x1fff;
  2287. if (pmt_pid == ts->current_pid)
  2288. break;
  2289. av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  2290. if (sid == 0x0000) {
  2291. /* NIT info */
  2292. } else {
  2293. MpegTSFilter *fil = ts->pids[pmt_pid];
  2294. struct Program *prg;
  2295. program = av_new_program(ts->stream, sid);
  2296. if (program) {
  2297. program->program_num = sid;
  2298. program->pmt_pid = pmt_pid;
  2299. }
  2300. if (fil)
  2301. if ( fil->type != MPEGTS_SECTION
  2302. || fil->pid != pmt_pid
  2303. || fil->u.section_filter.section_cb != pmt_cb)
  2304. mpegts_close_filter(ts, ts->pids[pmt_pid]);
  2305. if (!ts->pids[pmt_pid])
  2306. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  2307. prg = add_program(ts, sid);
  2308. if (prg) {
  2309. unsigned prg_idx = prg - ts->prg;
  2310. if (prg->nb_pids && prg->pids[0] != pmt_pid)
  2311. clear_program(prg);
  2312. add_pid_to_program(prg, pmt_pid);
  2313. if (prg_idx > nb_prg)
  2314. FFSWAP(struct Program, ts->prg[nb_prg], ts->prg[prg_idx]);
  2315. if (prg_idx >= nb_prg)
  2316. nb_prg++;
  2317. } else
  2318. nb_prg = 0;
  2319. }
  2320. }
  2321. ts->nb_prg = nb_prg;
  2322. if (sid < 0) {
  2323. int i,j;
  2324. for (j=0; j<ts->stream->nb_programs; j++) {
  2325. for (i = 0; i < ts->nb_prg; i++)
  2326. if (ts->prg[i].id == ts->stream->programs[j]->id)
  2327. break;
  2328. if (i==ts->nb_prg && !ts->skip_clear)
  2329. clear_avprogram(ts, ts->stream->programs[j]->id);
  2330. }
  2331. }
  2332. }
  2333. static void eit_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  2334. {
  2335. MpegTSContext *ts = filter->u.section_filter.opaque;
  2336. const uint8_t *p, *p_end;
  2337. SectionHeader h1, *h = &h1;
  2338. /*
  2339. * Sometimes we receive EPG packets but SDT table do not have
  2340. * eit_pres_following or eit_sched turned on, so we open EPG
  2341. * stream directly here.
  2342. */
  2343. if (!ts->epg_stream) {
  2344. ts->epg_stream = avformat_new_stream(ts->stream, NULL);
  2345. if (!ts->epg_stream)
  2346. return;
  2347. ts->epg_stream->id = EIT_PID;
  2348. ts->epg_stream->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  2349. ts->epg_stream->codecpar->codec_id = AV_CODEC_ID_EPG;
  2350. }
  2351. if (ts->epg_stream->discard == AVDISCARD_ALL)
  2352. return;
  2353. p_end = section + section_len - 4;
  2354. p = section;
  2355. if (parse_section_header(h, &p, p_end) < 0)
  2356. return;
  2357. if (h->tid < EIT_TID || h->tid > OEITS_END_TID)
  2358. return;
  2359. av_log(ts->stream, AV_LOG_TRACE, "EIT: tid received = %.02x\n", h->tid);
  2360. /**
  2361. * Service_id 0xFFFF is reserved, it indicates that the current EIT table
  2362. * is scrambled.
  2363. */
  2364. if (h->id == 0xFFFF) {
  2365. av_log(ts->stream, AV_LOG_TRACE, "Scrambled EIT table received.\n");
  2366. return;
  2367. }
  2368. /**
  2369. * In case we receive an EPG packet before mpegts context is fully
  2370. * initialized.
  2371. */
  2372. if (!ts->pkt)
  2373. return;
  2374. new_data_packet(section, section_len, ts->pkt);
  2375. ts->pkt->stream_index = ts->epg_stream->index;
  2376. ts->stop_parse = 1;
  2377. }
  2378. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  2379. {
  2380. MpegTSContext *ts = filter->u.section_filter.opaque;
  2381. MpegTSSectionFilter *tssf = &filter->u.section_filter;
  2382. SectionHeader h1, *h = &h1;
  2383. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  2384. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  2385. char *name, *provider_name;
  2386. av_log(ts->stream, AV_LOG_TRACE, "SDT:\n");
  2387. hex_dump_debug(ts->stream, section, section_len);
  2388. p_end = section + section_len - 4;
  2389. p = section;
  2390. if (parse_section_header(h, &p, p_end) < 0)
  2391. return;
  2392. if (h->tid != SDT_TID)
  2393. return;
  2394. if (!h->current_next)
  2395. return;
  2396. if (ts->skip_changes)
  2397. return;
  2398. if (skip_identical(h, tssf))
  2399. return;
  2400. onid = get16(&p, p_end);
  2401. if (onid < 0)
  2402. return;
  2403. val = get8(&p, p_end);
  2404. if (val < 0)
  2405. return;
  2406. for (;;) {
  2407. sid = get16(&p, p_end);
  2408. if (sid < 0)
  2409. break;
  2410. val = get8(&p, p_end);
  2411. if (val < 0)
  2412. break;
  2413. desc_list_len = get16(&p, p_end);
  2414. if (desc_list_len < 0)
  2415. break;
  2416. desc_list_len &= 0xfff;
  2417. desc_list_end = p + desc_list_len;
  2418. if (desc_list_end > p_end)
  2419. break;
  2420. for (;;) {
  2421. desc_tag = get8(&p, desc_list_end);
  2422. if (desc_tag < 0)
  2423. break;
  2424. desc_len = get8(&p, desc_list_end);
  2425. desc_end = p + desc_len;
  2426. if (desc_len < 0 || desc_end > desc_list_end)
  2427. break;
  2428. av_log(ts->stream, AV_LOG_TRACE, "tag: 0x%02x len=%d\n",
  2429. desc_tag, desc_len);
  2430. switch (desc_tag) {
  2431. case 0x48:
  2432. service_type = get8(&p, desc_end);
  2433. if (service_type < 0)
  2434. break;
  2435. provider_name = getstr8(&p, desc_end);
  2436. if (!provider_name)
  2437. break;
  2438. name = getstr8(&p, desc_end);
  2439. if (name) {
  2440. AVProgram *program = av_new_program(ts->stream, sid);
  2441. if (program) {
  2442. av_dict_set(&program->metadata, "service_name", name, 0);
  2443. av_dict_set(&program->metadata, "service_provider",
  2444. provider_name, 0);
  2445. }
  2446. }
  2447. av_free(name);
  2448. av_free(provider_name);
  2449. break;
  2450. default:
  2451. break;
  2452. }
  2453. p = desc_end;
  2454. }
  2455. p = desc_list_end;
  2456. }
  2457. }
  2458. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  2459. const uint8_t *packet);
  2460. /* handle one TS packet */
  2461. static int handle_packet(MpegTSContext *ts, const uint8_t *packet, int64_t pos)
  2462. {
  2463. MpegTSFilter *tss;
  2464. int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
  2465. has_adaptation, has_payload;
  2466. const uint8_t *p, *p_end;
  2467. pid = AV_RB16(packet + 1) & 0x1fff;
  2468. is_start = packet[1] & 0x40;
  2469. tss = ts->pids[pid];
  2470. if (ts->auto_guess && !tss && is_start) {
  2471. add_pes_stream(ts, pid, -1);
  2472. tss = ts->pids[pid];
  2473. }
  2474. if (!tss)
  2475. return 0;
  2476. if (is_start)
  2477. tss->discard = discard_pid(ts, pid);
  2478. if (tss->discard)
  2479. return 0;
  2480. ts->current_pid = pid;
  2481. afc = (packet[3] >> 4) & 3;
  2482. if (afc == 0) /* reserved value */
  2483. return 0;
  2484. has_adaptation = afc & 2;
  2485. has_payload = afc & 1;
  2486. is_discontinuity = has_adaptation &&
  2487. packet[4] != 0 && /* with length > 0 */
  2488. (packet[5] & 0x80); /* and discontinuity indicated */
  2489. /* continuity check (currently not used) */
  2490. cc = (packet[3] & 0xf);
  2491. expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
  2492. cc_ok = pid == 0x1FFF || // null packet PID
  2493. is_discontinuity ||
  2494. tss->last_cc < 0 ||
  2495. expected_cc == cc;
  2496. tss->last_cc = cc;
  2497. if (!cc_ok) {
  2498. av_log(ts->stream, AV_LOG_DEBUG,
  2499. "Continuity check failed for pid %d expected %d got %d\n",
  2500. pid, expected_cc, cc);
  2501. if (tss->type == MPEGTS_PES) {
  2502. PESContext *pc = tss->u.pes_filter.opaque;
  2503. pc->flags |= AV_PKT_FLAG_CORRUPT;
  2504. }
  2505. }
  2506. if (packet[1] & 0x80) {
  2507. av_log(ts->stream, AV_LOG_DEBUG, "Packet had TEI flag set; marking as corrupt\n");
  2508. if (tss->type == MPEGTS_PES) {
  2509. PESContext *pc = tss->u.pes_filter.opaque;
  2510. pc->flags |= AV_PKT_FLAG_CORRUPT;
  2511. }
  2512. }
  2513. p = packet + 4;
  2514. if (has_adaptation) {
  2515. int64_t pcr_h;
  2516. int pcr_l;
  2517. if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
  2518. tss->last_pcr = pcr_h * 300 + pcr_l;
  2519. /* skip adaptation field */
  2520. p += p[0] + 1;
  2521. }
  2522. /* if past the end of packet, ignore */
  2523. p_end = packet + TS_PACKET_SIZE;
  2524. if (p >= p_end || !has_payload)
  2525. return 0;
  2526. if (pos >= 0) {
  2527. av_assert0(pos >= TS_PACKET_SIZE);
  2528. ts->pos47_full = pos - TS_PACKET_SIZE;
  2529. }
  2530. if (tss->type == MPEGTS_SECTION) {
  2531. if (is_start) {
  2532. /* pointer field present */
  2533. len = *p++;
  2534. if (len > p_end - p)
  2535. return 0;
  2536. if (len && cc_ok) {
  2537. /* write remaining section bytes */
  2538. write_section_data(ts, tss,
  2539. p, len, 0);
  2540. /* check whether filter has been closed */
  2541. if (!ts->pids[pid])
  2542. return 0;
  2543. }
  2544. p += len;
  2545. if (p < p_end) {
  2546. write_section_data(ts, tss,
  2547. p, p_end - p, 1);
  2548. }
  2549. } else {
  2550. if (cc_ok) {
  2551. write_section_data(ts, tss,
  2552. p, p_end - p, 0);
  2553. }
  2554. }
  2555. // stop find_stream_info from waiting for more streams
  2556. // when all programs have received a PMT
  2557. if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER && ts->scan_all_pmts <= 0) {
  2558. int i;
  2559. for (i = 0; i < ts->nb_prg; i++) {
  2560. if (!ts->prg[i].pmt_found)
  2561. break;
  2562. }
  2563. if (i == ts->nb_prg && ts->nb_prg > 0) {
  2564. av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
  2565. ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
  2566. }
  2567. }
  2568. } else {
  2569. int ret;
  2570. // Note: The position here points actually behind the current packet.
  2571. if (tss->type == MPEGTS_PES) {
  2572. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  2573. pos - ts->raw_packet_size)) < 0)
  2574. return ret;
  2575. }
  2576. }
  2577. return 0;
  2578. }
  2579. static int mpegts_resync(AVFormatContext *s, int seekback, const uint8_t *current_packet)
  2580. {
  2581. MpegTSContext *ts = s->priv_data;
  2582. AVIOContext *pb = s->pb;
  2583. int c, i;
  2584. uint64_t pos = avio_tell(pb);
  2585. int64_t back = FFMIN(seekback, pos);
  2586. //Special case for files like 01c56b0dc1.ts
  2587. if (current_packet[0] == 0x80 && current_packet[12] == 0x47 && pos >= TS_PACKET_SIZE) {
  2588. avio_seek(pb, 12 - TS_PACKET_SIZE, SEEK_CUR);
  2589. return 0;
  2590. }
  2591. avio_seek(pb, -back, SEEK_CUR);
  2592. for (i = 0; i < ts->resync_size; i++) {
  2593. c = avio_r8(pb);
  2594. if (avio_feof(pb))
  2595. return AVERROR_EOF;
  2596. if (c == 0x47) {
  2597. int new_packet_size, ret;
  2598. avio_seek(pb, -1, SEEK_CUR);
  2599. pos = avio_tell(pb);
  2600. ret = ffio_ensure_seekback(pb, PROBE_PACKET_MAX_BUF);
  2601. if (ret < 0)
  2602. return ret;
  2603. new_packet_size = get_packet_size(s);
  2604. if (new_packet_size > 0 && new_packet_size != ts->raw_packet_size) {
  2605. av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", new_packet_size);
  2606. ts->raw_packet_size = new_packet_size;
  2607. }
  2608. avio_seek(pb, pos, SEEK_SET);
  2609. return 0;
  2610. }
  2611. }
  2612. av_log(s, AV_LOG_ERROR,
  2613. "max resync size reached, could not find sync byte\n");
  2614. /* no sync found */
  2615. return AVERROR_INVALIDDATA;
  2616. }
  2617. /* return AVERROR_something if error or EOF. Return 0 if OK. */
  2618. static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
  2619. const uint8_t **data)
  2620. {
  2621. AVIOContext *pb = s->pb;
  2622. int len;
  2623. for (;;) {
  2624. len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
  2625. if (len != TS_PACKET_SIZE)
  2626. return len < 0 ? len : AVERROR_EOF;
  2627. /* check packet sync byte */
  2628. if ((*data)[0] != 0x47) {
  2629. /* find a new packet start */
  2630. if (mpegts_resync(s, raw_packet_size, *data) < 0)
  2631. return AVERROR(EAGAIN);
  2632. else
  2633. continue;
  2634. } else {
  2635. break;
  2636. }
  2637. }
  2638. return 0;
  2639. }
  2640. static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
  2641. {
  2642. AVIOContext *pb = s->pb;
  2643. int skip = raw_packet_size - TS_PACKET_SIZE;
  2644. if (skip > 0)
  2645. avio_skip(pb, skip);
  2646. }
  2647. static int handle_packets(MpegTSContext *ts, int64_t nb_packets)
  2648. {
  2649. AVFormatContext *s = ts->stream;
  2650. uint8_t packet[TS_PACKET_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
  2651. const uint8_t *data;
  2652. int64_t packet_num;
  2653. int ret = 0;
  2654. if (avio_tell(s->pb) != ts->last_pos) {
  2655. int i;
  2656. av_log(ts->stream, AV_LOG_TRACE, "Skipping after seek\n");
  2657. /* seek detected, flush pes buffer */
  2658. for (i = 0; i < NB_PID_MAX; i++) {
  2659. if (ts->pids[i]) {
  2660. if (ts->pids[i]->type == MPEGTS_PES) {
  2661. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  2662. av_buffer_unref(&pes->buffer);
  2663. pes->data_index = 0;
  2664. pes->state = MPEGTS_SKIP; /* skip until pes header */
  2665. } else if (ts->pids[i]->type == MPEGTS_SECTION) {
  2666. ts->pids[i]->u.section_filter.last_ver = -1;
  2667. }
  2668. ts->pids[i]->last_cc = -1;
  2669. ts->pids[i]->last_pcr = -1;
  2670. }
  2671. }
  2672. }
  2673. ts->stop_parse = 0;
  2674. packet_num = 0;
  2675. memset(packet + TS_PACKET_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  2676. for (;;) {
  2677. packet_num++;
  2678. if (nb_packets != 0 && packet_num >= nb_packets ||
  2679. ts->stop_parse > 1) {
  2680. ret = AVERROR(EAGAIN);
  2681. break;
  2682. }
  2683. if (ts->stop_parse > 0)
  2684. break;
  2685. ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2686. if (ret != 0)
  2687. break;
  2688. ret = handle_packet(ts, data, avio_tell(s->pb));
  2689. finished_reading_packet(s, ts->raw_packet_size);
  2690. if (ret != 0)
  2691. break;
  2692. }
  2693. ts->last_pos = avio_tell(s->pb);
  2694. return ret;
  2695. }
  2696. static int mpegts_probe(const AVProbeData *p)
  2697. {
  2698. const int size = p->buf_size;
  2699. int maxscore = 0;
  2700. int sumscore = 0;
  2701. int i;
  2702. int check_count = size / TS_FEC_PACKET_SIZE;
  2703. #define CHECK_COUNT 10
  2704. #define CHECK_BLOCK 100
  2705. if (!check_count)
  2706. return 0;
  2707. for (i = 0; i<check_count; i+=CHECK_BLOCK) {
  2708. int left = FFMIN(check_count - i, CHECK_BLOCK);
  2709. int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , 1);
  2710. int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, 1);
  2711. int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , 1);
  2712. score = FFMAX3(score, dvhs_score, fec_score);
  2713. sumscore += score;
  2714. maxscore = FFMAX(maxscore, score);
  2715. }
  2716. sumscore = sumscore * CHECK_COUNT / check_count;
  2717. maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;
  2718. ff_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
  2719. if (check_count > CHECK_COUNT && sumscore > 6) {
  2720. return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
  2721. } else if (check_count >= CHECK_COUNT && sumscore > 6) {
  2722. return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
  2723. } else if (check_count >= CHECK_COUNT && maxscore > 6) {
  2724. return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
  2725. } else if (sumscore > 6) {
  2726. return 2;
  2727. } else {
  2728. return 0;
  2729. }
  2730. }
  2731. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  2732. * (-1) if not available */
  2733. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
  2734. {
  2735. int afc, len, flags;
  2736. const uint8_t *p;
  2737. unsigned int v;
  2738. afc = (packet[3] >> 4) & 3;
  2739. if (afc <= 1)
  2740. return AVERROR_INVALIDDATA;
  2741. p = packet + 4;
  2742. len = p[0];
  2743. p++;
  2744. if (len == 0)
  2745. return AVERROR_INVALIDDATA;
  2746. flags = *p++;
  2747. len--;
  2748. if (!(flags & 0x10))
  2749. return AVERROR_INVALIDDATA;
  2750. if (len < 6)
  2751. return AVERROR_INVALIDDATA;
  2752. v = AV_RB32(p);
  2753. *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
  2754. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  2755. return 0;
  2756. }
  2757. static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
  2758. /* NOTE: We attempt to seek on non-seekable files as well, as the
  2759. * probe buffer usually is big enough. Only warn if the seek failed
  2760. * on files where the seek should work. */
  2761. if (avio_seek(pb, pos, SEEK_SET) < 0)
  2762. av_log(s, (pb->seekable & AVIO_SEEKABLE_NORMAL) ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
  2763. }
  2764. static int mpegts_read_header(AVFormatContext *s)
  2765. {
  2766. MpegTSContext *ts = s->priv_data;
  2767. AVIOContext *pb = s->pb;
  2768. int64_t pos, probesize = s->probesize;
  2769. int64_t seekback = FFMAX(s->probesize, (int64_t)ts->resync_size + PROBE_PACKET_MAX_BUF);
  2770. ffformatcontext(s)->prefer_codec_framerate = 1;
  2771. if (ffio_ensure_seekback(pb, seekback) < 0)
  2772. av_log(s, AV_LOG_WARNING, "Failed to allocate buffers for seekback\n");
  2773. pos = avio_tell(pb);
  2774. ts->raw_packet_size = get_packet_size(s);
  2775. if (ts->raw_packet_size <= 0) {
  2776. av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
  2777. ts->raw_packet_size = TS_PACKET_SIZE;
  2778. }
  2779. ts->stream = s;
  2780. ts->auto_guess = 0;
  2781. if (s->iformat == &ff_mpegts_demuxer.p) {
  2782. /* normal demux */
  2783. /* first do a scan to get all the services */
  2784. seek_back(s, pb, pos);
  2785. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  2786. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2787. mpegts_open_section_filter(ts, EIT_PID, eit_cb, ts, 1);
  2788. handle_packets(ts, probesize / ts->raw_packet_size);
  2789. /* if could not find service, enable auto_guess */
  2790. ts->auto_guess = 1;
  2791. av_log(ts->stream, AV_LOG_TRACE, "tuning done\n");
  2792. s->ctx_flags |= AVFMTCTX_NOHEADER;
  2793. } else {
  2794. AVStream *st;
  2795. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  2796. int64_t pcrs[2], pcr_h;
  2797. uint8_t packet[TS_PACKET_SIZE];
  2798. const uint8_t *data;
  2799. /* only read packets */
  2800. st = avformat_new_stream(s, NULL);
  2801. if (!st)
  2802. return AVERROR(ENOMEM);
  2803. avpriv_set_pts_info(st, 60, 1, 27000000);
  2804. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  2805. st->codecpar->codec_id = AV_CODEC_ID_MPEG2TS;
  2806. /* we iterate until we find two PCRs to estimate the bitrate */
  2807. pcr_pid = -1;
  2808. nb_pcrs = 0;
  2809. nb_packets = 0;
  2810. for (;;) {
  2811. ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2812. if (ret < 0)
  2813. return ret;
  2814. pid = AV_RB16(data + 1) & 0x1fff;
  2815. if ((pcr_pid == -1 || pcr_pid == pid) &&
  2816. parse_pcr(&pcr_h, &pcr_l, data) == 0) {
  2817. finished_reading_packet(s, ts->raw_packet_size);
  2818. pcr_pid = pid;
  2819. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  2820. nb_pcrs++;
  2821. if (nb_pcrs >= 2) {
  2822. if (pcrs[1] - pcrs[0] > 0) {
  2823. /* the difference needs to be positive to make sense for bitrate computation */
  2824. break;
  2825. } else {
  2826. av_log(ts->stream, AV_LOG_WARNING, "invalid pcr pair %"PRId64" >= %"PRId64"\n", pcrs[0], pcrs[1]);
  2827. pcrs[0] = pcrs[1];
  2828. nb_pcrs--;
  2829. }
  2830. }
  2831. } else {
  2832. finished_reading_packet(s, ts->raw_packet_size);
  2833. }
  2834. nb_packets++;
  2835. }
  2836. /* NOTE1: the bitrate is computed without the FEC */
  2837. /* NOTE2: it is only the bitrate of the start of the stream */
  2838. ts->pcr_incr = pcrs[1] - pcrs[0];
  2839. ts->cur_pcr = pcrs[0] - ts->pcr_incr * (nb_packets - 1);
  2840. s->bit_rate = TS_PACKET_SIZE * 8 * 27000000LL / ts->pcr_incr;
  2841. st->codecpar->bit_rate = s->bit_rate;
  2842. st->start_time = ts->cur_pcr;
  2843. av_log(ts->stream, AV_LOG_TRACE, "start=%0.3f pcr=%0.3f incr=%"PRId64"\n",
  2844. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  2845. }
  2846. seek_back(s, pb, pos);
  2847. return 0;
  2848. }
  2849. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  2850. static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
  2851. {
  2852. MpegTSContext *ts = s->priv_data;
  2853. int ret, i;
  2854. int64_t pcr_h, next_pcr_h, pos;
  2855. int pcr_l, next_pcr_l;
  2856. uint8_t pcr_buf[12];
  2857. const uint8_t *data;
  2858. if ((ret = av_new_packet(pkt, TS_PACKET_SIZE)) < 0)
  2859. return ret;
  2860. ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
  2861. pkt->pos = avio_tell(s->pb);
  2862. if (ret < 0) {
  2863. return ret;
  2864. }
  2865. if (data != pkt->data)
  2866. memcpy(pkt->data, data, TS_PACKET_SIZE);
  2867. finished_reading_packet(s, ts->raw_packet_size);
  2868. if (ts->mpeg2ts_compute_pcr) {
  2869. /* compute exact PCR for each packet */
  2870. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  2871. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  2872. pos = avio_tell(s->pb);
  2873. for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
  2874. avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  2875. avio_read(s->pb, pcr_buf, 12);
  2876. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  2877. /* XXX: not precise enough */
  2878. ts->pcr_incr =
  2879. ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  2880. (i + 1);
  2881. break;
  2882. }
  2883. }
  2884. avio_seek(s->pb, pos, SEEK_SET);
  2885. /* no next PCR found: we use previous increment */
  2886. ts->cur_pcr = pcr_h * 300 + pcr_l;
  2887. }
  2888. pkt->pts = ts->cur_pcr;
  2889. pkt->duration = ts->pcr_incr;
  2890. ts->cur_pcr += ts->pcr_incr;
  2891. }
  2892. pkt->stream_index = 0;
  2893. return 0;
  2894. }
  2895. static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
  2896. {
  2897. MpegTSContext *ts = s->priv_data;
  2898. int ret, i;
  2899. pkt->size = -1;
  2900. ts->pkt = pkt;
  2901. ret = handle_packets(ts, 0);
  2902. if (ret < 0) {
  2903. av_packet_unref(ts->pkt);
  2904. /* flush pes data left */
  2905. for (i = 0; i < NB_PID_MAX; i++)
  2906. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  2907. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  2908. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  2909. ret = new_pes_packet(pes, pkt);
  2910. if (ret < 0)
  2911. return ret;
  2912. pes->state = MPEGTS_SKIP;
  2913. ret = 0;
  2914. break;
  2915. }
  2916. }
  2917. }
  2918. if (!ret && pkt->size < 0)
  2919. ret = AVERROR_INVALIDDATA;
  2920. return ret;
  2921. }
  2922. static void mpegts_free(MpegTSContext *ts)
  2923. {
  2924. int i;
  2925. clear_programs(ts);
  2926. for (i = 0; i < FF_ARRAY_ELEMS(ts->pools); i++)
  2927. av_buffer_pool_uninit(&ts->pools[i]);
  2928. for (i = 0; i < NB_PID_MAX; i++)
  2929. if (ts->pids[i])
  2930. mpegts_close_filter(ts, ts->pids[i]);
  2931. }
  2932. static int mpegts_read_close(AVFormatContext *s)
  2933. {
  2934. MpegTSContext *ts = s->priv_data;
  2935. mpegts_free(ts);
  2936. return 0;
  2937. }
  2938. static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  2939. int64_t *ppos, int64_t pos_limit)
  2940. {
  2941. MpegTSContext *ts = s->priv_data;
  2942. int64_t pos, timestamp;
  2943. uint8_t buf[TS_PACKET_SIZE];
  2944. int pcr_l, pcr_pid =
  2945. ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
  2946. int pos47 = ts->pos47_full % ts->raw_packet_size;
  2947. pos =
  2948. ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
  2949. ts->raw_packet_size + pos47;
  2950. while(pos < pos_limit) {
  2951. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2952. return AV_NOPTS_VALUE;
  2953. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  2954. return AV_NOPTS_VALUE;
  2955. if (buf[0] != 0x47) {
  2956. if (mpegts_resync(s, TS_PACKET_SIZE, buf) < 0)
  2957. return AV_NOPTS_VALUE;
  2958. pos = avio_tell(s->pb);
  2959. continue;
  2960. }
  2961. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  2962. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  2963. *ppos = pos;
  2964. return timestamp;
  2965. }
  2966. pos += ts->raw_packet_size;
  2967. }
  2968. return AV_NOPTS_VALUE;
  2969. }
  2970. static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
  2971. int64_t *ppos, int64_t pos_limit)
  2972. {
  2973. MpegTSContext *ts = s->priv_data;
  2974. AVPacket *pkt;
  2975. int64_t pos;
  2976. int pos47 = ts->pos47_full % ts->raw_packet_size;
  2977. pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
  2978. ff_read_frame_flush(s);
  2979. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2980. return AV_NOPTS_VALUE;
  2981. pkt = av_packet_alloc();
  2982. if (!pkt)
  2983. return AV_NOPTS_VALUE;
  2984. while(pos < pos_limit) {
  2985. int ret = av_read_frame(s, pkt);
  2986. if (ret < 0) {
  2987. av_packet_free(&pkt);
  2988. return AV_NOPTS_VALUE;
  2989. }
  2990. if (pkt->dts != AV_NOPTS_VALUE && pkt->pos >= 0) {
  2991. ff_reduce_index(s, pkt->stream_index);
  2992. av_add_index_entry(s->streams[pkt->stream_index], pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
  2993. if (pkt->stream_index == stream_index && pkt->pos >= *ppos) {
  2994. int64_t dts = pkt->dts;
  2995. *ppos = pkt->pos;
  2996. av_packet_free(&pkt);
  2997. return dts;
  2998. }
  2999. }
  3000. pos = pkt->pos;
  3001. av_packet_unref(pkt);
  3002. }
  3003. av_packet_free(&pkt);
  3004. return AV_NOPTS_VALUE;
  3005. }
  3006. /**************************************************************/
  3007. /* parsing functions - called from other demuxers such as RTP */
  3008. MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s)
  3009. {
  3010. MpegTSContext *ts;
  3011. ts = av_mallocz(sizeof(MpegTSContext));
  3012. if (!ts)
  3013. return NULL;
  3014. /* no stream case, currently used by RTP */
  3015. ts->raw_packet_size = TS_PACKET_SIZE;
  3016. ts->max_packet_size = 2048000;
  3017. ts->stream = s;
  3018. ts->auto_guess = 1;
  3019. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  3020. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  3021. mpegts_open_section_filter(ts, EIT_PID, eit_cb, ts, 1);
  3022. return ts;
  3023. }
  3024. /* return the consumed length if a packet was output, or -1 if no
  3025. * packet is output */
  3026. int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  3027. const uint8_t *buf, int len)
  3028. {
  3029. int len1;
  3030. len1 = len;
  3031. ts->pkt = pkt;
  3032. for (;;) {
  3033. ts->stop_parse = 0;
  3034. if (len < TS_PACKET_SIZE)
  3035. return AVERROR_INVALIDDATA;
  3036. if (buf[0] != 0x47) {
  3037. buf++;
  3038. len--;
  3039. } else {
  3040. handle_packet(ts, buf, len1 - len + TS_PACKET_SIZE);
  3041. buf += TS_PACKET_SIZE;
  3042. len -= TS_PACKET_SIZE;
  3043. if (ts->stop_parse == 1)
  3044. break;
  3045. }
  3046. }
  3047. return len1 - len;
  3048. }
  3049. void avpriv_mpegts_parse_close(MpegTSContext *ts)
  3050. {
  3051. mpegts_free(ts);
  3052. av_free(ts);
  3053. }
  3054. const FFInputFormat ff_mpegts_demuxer = {
  3055. .p.name = "mpegts",
  3056. .p.long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
  3057. .p.flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  3058. .p.priv_class = &mpegts_class,
  3059. .priv_data_size = sizeof(MpegTSContext),
  3060. .read_probe = mpegts_probe,
  3061. .read_header = mpegts_read_header,
  3062. .read_packet = mpegts_read_packet,
  3063. .read_close = mpegts_read_close,
  3064. .read_timestamp = mpegts_get_dts,
  3065. };
  3066. const FFInputFormat ff_mpegtsraw_demuxer = {
  3067. .p.name = "mpegtsraw",
  3068. .p.long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
  3069. .p.flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  3070. .p.priv_class = &mpegtsraw_class,
  3071. .priv_data_size = sizeof(MpegTSContext),
  3072. .read_header = mpegts_read_header,
  3073. .read_packet = mpegts_raw_read_packet,
  3074. .read_close = mpegts_read_close,
  3075. .read_timestamp = mpegts_get_dts,
  3076. };