mpegts.c 119 KB

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