dashdec.c 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380
  1. /*
  2. * Dynamic Adaptive Streaming over HTTP demux
  3. * Copyright (c) 2017 samsamsam@o2.pl based on HLS demux
  4. * Copyright (c) 2017 Steven Liu
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include <libxml/parser.h>
  23. #include <time.h>
  24. #include "libavutil/bprint.h"
  25. #include "libavutil/mem.h"
  26. #include "libavutil/opt.h"
  27. #include "libavutil/time.h"
  28. #include "libavutil/parseutils.h"
  29. #include "internal.h"
  30. #include "avio_internal.h"
  31. #include "dash.h"
  32. #include "demux.h"
  33. #include "url.h"
  34. #define INITIAL_BUFFER_SIZE 32768
  35. struct fragment {
  36. int64_t url_offset;
  37. int64_t size;
  38. char *url;
  39. };
  40. /*
  41. * reference to : ISO_IEC_23009-1-DASH-2012
  42. * Section: 5.3.9.6.2
  43. * Table: Table 17 — Semantics of SegmentTimeline element
  44. * */
  45. struct timeline {
  46. /* starttime: Element or Attribute Name
  47. * specifies the MPD start time, in @timescale units,
  48. * the first Segment in the series starts relative to the beginning of the Period.
  49. * The value of this attribute must be equal to or greater than the sum of the previous S
  50. * element earliest presentation time and the sum of the contiguous Segment durations.
  51. * If the value of the attribute is greater than what is expressed by the previous S element,
  52. * it expresses discontinuities in the timeline.
  53. * If not present then the value shall be assumed to be zero for the first S element
  54. * and for the subsequent S elements, the value shall be assumed to be the sum of
  55. * the previous S element's earliest presentation time and contiguous duration
  56. * (i.e. previous S@starttime + @duration * (@repeat + 1)).
  57. * */
  58. int64_t starttime;
  59. /* repeat: Element or Attribute Name
  60. * specifies the repeat count of the number of following contiguous Segments with
  61. * the same duration expressed by the value of @duration. This value is zero-based
  62. * (e.g. a value of three means four Segments in the contiguous series).
  63. * */
  64. int64_t repeat;
  65. /* duration: Element or Attribute Name
  66. * specifies the Segment duration, in units of the value of the @timescale.
  67. * */
  68. int64_t duration;
  69. };
  70. /*
  71. * Each playlist has its own demuxer. If it is currently active,
  72. * it has an opened AVIOContext too, and potentially an AVPacket
  73. * containing the next packet from this stream.
  74. */
  75. struct representation {
  76. char *url_template;
  77. FFIOContext pb;
  78. AVIOContext *input;
  79. AVFormatContext *parent;
  80. AVFormatContext *ctx;
  81. int stream_index;
  82. char *id;
  83. char *lang;
  84. int bandwidth;
  85. AVRational framerate;
  86. AVStream *assoc_stream; /* demuxer stream associated with this representation */
  87. int n_fragments;
  88. struct fragment **fragments; /* VOD list of fragment for profile */
  89. int n_timelines;
  90. struct timeline **timelines;
  91. int64_t first_seq_no;
  92. int64_t last_seq_no;
  93. int64_t start_number; /* used in case when we have dynamic list of segment to know which segments are new one*/
  94. int64_t fragment_duration;
  95. int64_t fragment_timescale;
  96. int64_t presentation_timeoffset;
  97. int64_t cur_seq_no;
  98. int64_t cur_seg_offset;
  99. int64_t cur_seg_size;
  100. struct fragment *cur_seg;
  101. /* Currently active Media Initialization Section */
  102. struct fragment *init_section;
  103. uint8_t *init_sec_buf;
  104. uint32_t init_sec_buf_size;
  105. uint32_t init_sec_data_len;
  106. uint32_t init_sec_buf_read_offset;
  107. int64_t cur_timestamp;
  108. int is_restart_needed;
  109. };
  110. typedef struct DASHContext {
  111. const AVClass *class;
  112. char *base_url;
  113. int n_videos;
  114. struct representation **videos;
  115. int n_audios;
  116. struct representation **audios;
  117. int n_subtitles;
  118. struct representation **subtitles;
  119. /* MediaPresentationDescription Attribute */
  120. uint64_t media_presentation_duration;
  121. uint64_t suggested_presentation_delay;
  122. uint64_t availability_start_time;
  123. uint64_t availability_end_time;
  124. uint64_t publish_time;
  125. uint64_t minimum_update_period;
  126. uint64_t time_shift_buffer_depth;
  127. uint64_t min_buffer_time;
  128. /* Period Attribute */
  129. uint64_t period_duration;
  130. uint64_t period_start;
  131. /* AdaptationSet Attribute */
  132. char *adaptionset_lang;
  133. int is_live;
  134. AVIOInterruptCB *interrupt_callback;
  135. char *allowed_extensions;
  136. AVDictionary *avio_opts;
  137. int max_url_size;
  138. char *cenc_decryption_key;
  139. /* Flags for init section*/
  140. int is_init_section_common_video;
  141. int is_init_section_common_audio;
  142. int is_init_section_common_subtitle;
  143. } DASHContext;
  144. static int ishttp(char *url)
  145. {
  146. const char *proto_name = avio_find_protocol_name(url);
  147. return proto_name && av_strstart(proto_name, "http", NULL);
  148. }
  149. static int aligned(int val)
  150. {
  151. return ((val + 0x3F) >> 6) << 6;
  152. }
  153. static uint64_t get_current_time_in_sec(void)
  154. {
  155. return av_gettime() / 1000000;
  156. }
  157. static uint64_t get_utc_date_time_insec(AVFormatContext *s, const char *datetime)
  158. {
  159. struct tm timeinfo;
  160. int year = 0;
  161. int month = 0;
  162. int day = 0;
  163. int hour = 0;
  164. int minute = 0;
  165. int ret = 0;
  166. float second = 0.0;
  167. /* ISO-8601 date parser */
  168. if (!datetime)
  169. return 0;
  170. ret = sscanf(datetime, "%d-%d-%dT%d:%d:%fZ", &year, &month, &day, &hour, &minute, &second);
  171. /* year, month, day, hour, minute, second 6 arguments */
  172. if (ret != 6) {
  173. av_log(s, AV_LOG_WARNING, "get_utc_date_time_insec get a wrong time format\n");
  174. }
  175. timeinfo.tm_year = year - 1900;
  176. timeinfo.tm_mon = month - 1;
  177. timeinfo.tm_mday = day;
  178. timeinfo.tm_hour = hour;
  179. timeinfo.tm_min = minute;
  180. timeinfo.tm_sec = (int)second;
  181. return av_timegm(&timeinfo);
  182. }
  183. static uint32_t get_duration_insec(AVFormatContext *s, const char *duration)
  184. {
  185. /* ISO-8601 duration parser */
  186. uint32_t days = 0;
  187. uint32_t hours = 0;
  188. uint32_t mins = 0;
  189. uint32_t secs = 0;
  190. int size = 0;
  191. float value = 0;
  192. char type = '\0';
  193. const char *ptr = duration;
  194. while (*ptr) {
  195. if (*ptr == 'P' || *ptr == 'T') {
  196. ptr++;
  197. continue;
  198. }
  199. if (sscanf(ptr, "%f%c%n", &value, &type, &size) != 2) {
  200. av_log(s, AV_LOG_WARNING, "get_duration_insec get a wrong time format\n");
  201. return 0; /* parser error */
  202. }
  203. switch (type) {
  204. case 'D':
  205. days = (uint32_t)value;
  206. break;
  207. case 'H':
  208. hours = (uint32_t)value;
  209. break;
  210. case 'M':
  211. mins = (uint32_t)value;
  212. break;
  213. case 'S':
  214. secs = (uint32_t)value;
  215. break;
  216. default:
  217. // handle invalid type
  218. break;
  219. }
  220. ptr += size;
  221. }
  222. return ((days * 24 + hours) * 60 + mins) * 60 + secs;
  223. }
  224. static int64_t get_segment_start_time_based_on_timeline(struct representation *pls, int64_t cur_seq_no)
  225. {
  226. int64_t start_time = 0;
  227. int64_t i = 0;
  228. int64_t j = 0;
  229. int64_t num = 0;
  230. if (pls->n_timelines) {
  231. for (i = 0; i < pls->n_timelines; i++) {
  232. if (pls->timelines[i]->starttime > 0) {
  233. start_time = pls->timelines[i]->starttime;
  234. }
  235. if (num == cur_seq_no)
  236. goto finish;
  237. start_time += pls->timelines[i]->duration;
  238. if (pls->timelines[i]->repeat == -1) {
  239. start_time = pls->timelines[i]->duration * cur_seq_no;
  240. goto finish;
  241. }
  242. for (j = 0; j < pls->timelines[i]->repeat; j++) {
  243. num++;
  244. if (num == cur_seq_no)
  245. goto finish;
  246. start_time += pls->timelines[i]->duration;
  247. }
  248. num++;
  249. }
  250. }
  251. finish:
  252. return start_time;
  253. }
  254. static int64_t calc_next_seg_no_from_timelines(struct representation *pls, int64_t cur_time)
  255. {
  256. int64_t i = 0;
  257. int64_t j = 0;
  258. int64_t num = 0;
  259. int64_t start_time = 0;
  260. for (i = 0; i < pls->n_timelines; i++) {
  261. if (pls->timelines[i]->starttime > 0) {
  262. start_time = pls->timelines[i]->starttime;
  263. }
  264. if (start_time > cur_time)
  265. goto finish;
  266. start_time += pls->timelines[i]->duration;
  267. for (j = 0; j < pls->timelines[i]->repeat; j++) {
  268. num++;
  269. if (start_time > cur_time)
  270. goto finish;
  271. start_time += pls->timelines[i]->duration;
  272. }
  273. num++;
  274. }
  275. return -1;
  276. finish:
  277. return num;
  278. }
  279. static void free_fragment(struct fragment **seg)
  280. {
  281. if (!(*seg)) {
  282. return;
  283. }
  284. av_freep(&(*seg)->url);
  285. av_freep(seg);
  286. }
  287. static void free_fragment_list(struct representation *pls)
  288. {
  289. int i;
  290. for (i = 0; i < pls->n_fragments; i++) {
  291. free_fragment(&pls->fragments[i]);
  292. }
  293. av_freep(&pls->fragments);
  294. pls->n_fragments = 0;
  295. }
  296. static void free_timelines_list(struct representation *pls)
  297. {
  298. int i;
  299. for (i = 0; i < pls->n_timelines; i++) {
  300. av_freep(&pls->timelines[i]);
  301. }
  302. av_freep(&pls->timelines);
  303. pls->n_timelines = 0;
  304. }
  305. static void free_representation(struct representation *pls)
  306. {
  307. free_fragment_list(pls);
  308. free_timelines_list(pls);
  309. free_fragment(&pls->cur_seg);
  310. free_fragment(&pls->init_section);
  311. av_freep(&pls->init_sec_buf);
  312. av_freep(&pls->pb.pub.buffer);
  313. ff_format_io_close(pls->parent, &pls->input);
  314. if (pls->ctx) {
  315. pls->ctx->pb = NULL;
  316. avformat_close_input(&pls->ctx);
  317. }
  318. av_freep(&pls->url_template);
  319. av_freep(&pls->lang);
  320. av_freep(&pls->id);
  321. av_freep(&pls);
  322. }
  323. static void free_video_list(DASHContext *c)
  324. {
  325. int i;
  326. for (i = 0; i < c->n_videos; i++) {
  327. struct representation *pls = c->videos[i];
  328. free_representation(pls);
  329. }
  330. av_freep(&c->videos);
  331. c->n_videos = 0;
  332. }
  333. static void free_audio_list(DASHContext *c)
  334. {
  335. int i;
  336. for (i = 0; i < c->n_audios; i++) {
  337. struct representation *pls = c->audios[i];
  338. free_representation(pls);
  339. }
  340. av_freep(&c->audios);
  341. c->n_audios = 0;
  342. }
  343. static void free_subtitle_list(DASHContext *c)
  344. {
  345. int i;
  346. for (i = 0; i < c->n_subtitles; i++) {
  347. struct representation *pls = c->subtitles[i];
  348. free_representation(pls);
  349. }
  350. av_freep(&c->subtitles);
  351. c->n_subtitles = 0;
  352. }
  353. static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
  354. AVDictionary **opts, AVDictionary *opts2, int *is_http)
  355. {
  356. DASHContext *c = s->priv_data;
  357. AVDictionary *tmp = NULL;
  358. const char *proto_name = NULL;
  359. int proto_name_len;
  360. int ret;
  361. if (av_strstart(url, "crypto", NULL)) {
  362. if (url[6] == '+' || url[6] == ':')
  363. proto_name = avio_find_protocol_name(url + 7);
  364. }
  365. if (!proto_name)
  366. proto_name = avio_find_protocol_name(url);
  367. if (!proto_name)
  368. return AVERROR_INVALIDDATA;
  369. proto_name_len = strlen(proto_name);
  370. // only http(s) & file are allowed
  371. if (av_strstart(proto_name, "file", NULL)) {
  372. if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
  373. av_log(s, AV_LOG_ERROR,
  374. "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
  375. "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
  376. url);
  377. return AVERROR_INVALIDDATA;
  378. }
  379. } else if (av_strstart(proto_name, "http", NULL)) {
  380. ;
  381. } else
  382. return AVERROR_INVALIDDATA;
  383. if (!strncmp(proto_name, url, proto_name_len) && url[proto_name_len] == ':')
  384. ;
  385. else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, proto_name_len) && url[7 + proto_name_len] == ':')
  386. ;
  387. else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
  388. return AVERROR_INVALIDDATA;
  389. av_freep(pb);
  390. av_dict_copy(&tmp, *opts, 0);
  391. av_dict_copy(&tmp, opts2, 0);
  392. ret = ffio_open_whitelist(pb, url, AVIO_FLAG_READ, c->interrupt_callback, &tmp, s->protocol_whitelist, s->protocol_blacklist);
  393. if (ret >= 0) {
  394. // update cookies on http response with setcookies.
  395. char *new_cookies = NULL;
  396. if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
  397. av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
  398. if (new_cookies) {
  399. av_dict_set(opts, "cookies", new_cookies, AV_DICT_DONT_STRDUP_VAL);
  400. }
  401. }
  402. av_dict_free(&tmp);
  403. if (is_http)
  404. *is_http = av_strstart(proto_name, "http", NULL);
  405. return ret;
  406. }
  407. static char *get_content_url(xmlNodePtr *baseurl_nodes,
  408. int n_baseurl_nodes,
  409. int max_url_size,
  410. char *rep_id_val,
  411. char *rep_bandwidth_val,
  412. char *val)
  413. {
  414. int i;
  415. char *text;
  416. char *url = NULL;
  417. char *tmp_str = av_mallocz(max_url_size);
  418. if (!tmp_str)
  419. return NULL;
  420. for (i = 0; i < n_baseurl_nodes; ++i) {
  421. if (baseurl_nodes[i] &&
  422. baseurl_nodes[i]->children &&
  423. baseurl_nodes[i]->children->type == XML_TEXT_NODE) {
  424. text = xmlNodeGetContent(baseurl_nodes[i]->children);
  425. if (text) {
  426. memset(tmp_str, 0, max_url_size);
  427. ff_make_absolute_url(tmp_str, max_url_size, "", text);
  428. xmlFree(text);
  429. }
  430. }
  431. }
  432. if (val)
  433. ff_make_absolute_url(tmp_str, max_url_size, tmp_str, val);
  434. if (rep_id_val) {
  435. url = av_strireplace(tmp_str, "$RepresentationID$", rep_id_val);
  436. if (!url) {
  437. goto end;
  438. }
  439. av_strlcpy(tmp_str, url, max_url_size);
  440. }
  441. if (rep_bandwidth_val && tmp_str[0] != '\0') {
  442. // free any previously assigned url before reassigning
  443. av_free(url);
  444. url = av_strireplace(tmp_str, "$Bandwidth$", rep_bandwidth_val);
  445. if (!url) {
  446. goto end;
  447. }
  448. }
  449. end:
  450. av_free(tmp_str);
  451. return url;
  452. }
  453. static char *get_val_from_nodes_tab(xmlNodePtr *nodes, const int n_nodes, const char *attrname)
  454. {
  455. int i;
  456. char *val;
  457. for (i = 0; i < n_nodes; ++i) {
  458. if (nodes[i]) {
  459. val = xmlGetProp(nodes[i], attrname);
  460. if (val)
  461. return val;
  462. }
  463. }
  464. return NULL;
  465. }
  466. static xmlNodePtr find_child_node_by_name(xmlNodePtr rootnode, const char *nodename)
  467. {
  468. xmlNodePtr node = rootnode;
  469. if (!node) {
  470. return NULL;
  471. }
  472. node = xmlFirstElementChild(node);
  473. while (node) {
  474. if (!av_strcasecmp(node->name, nodename)) {
  475. return node;
  476. }
  477. node = xmlNextElementSibling(node);
  478. }
  479. return NULL;
  480. }
  481. static enum AVMediaType get_content_type(xmlNodePtr node)
  482. {
  483. enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
  484. int i = 0;
  485. const char *attr;
  486. char *val = NULL;
  487. if (node) {
  488. for (i = 0; i < 2; i++) {
  489. attr = i ? "mimeType" : "contentType";
  490. val = xmlGetProp(node, attr);
  491. if (val) {
  492. if (av_stristr(val, "video")) {
  493. type = AVMEDIA_TYPE_VIDEO;
  494. } else if (av_stristr(val, "audio")) {
  495. type = AVMEDIA_TYPE_AUDIO;
  496. } else if (av_stristr(val, "text")) {
  497. type = AVMEDIA_TYPE_SUBTITLE;
  498. }
  499. xmlFree(val);
  500. }
  501. }
  502. }
  503. return type;
  504. }
  505. static struct fragment *get_fragment(char *range)
  506. {
  507. struct fragment *seg = av_mallocz(sizeof(struct fragment));
  508. if (!seg)
  509. return NULL;
  510. seg->size = -1;
  511. if (range) {
  512. char *str_end_offset;
  513. char *str_offset = av_strtok(range, "-", &str_end_offset);
  514. seg->url_offset = strtoll(str_offset, NULL, 10);
  515. seg->size = strtoll(str_end_offset, NULL, 10) - seg->url_offset + 1;
  516. }
  517. return seg;
  518. }
  519. static int parse_manifest_segmenturlnode(AVFormatContext *s, struct representation *rep,
  520. xmlNodePtr fragmenturl_node,
  521. xmlNodePtr *baseurl_nodes,
  522. char *rep_id_val,
  523. char *rep_bandwidth_val)
  524. {
  525. DASHContext *c = s->priv_data;
  526. char *initialization_val = NULL;
  527. char *media_val = NULL;
  528. char *range_val = NULL;
  529. int max_url_size = c ? c->max_url_size: MAX_URL_SIZE;
  530. int err;
  531. if (!av_strcasecmp(fragmenturl_node->name, "Initialization")) {
  532. initialization_val = xmlGetProp(fragmenturl_node, "sourceURL");
  533. range_val = xmlGetProp(fragmenturl_node, "range");
  534. if (initialization_val || range_val) {
  535. free_fragment(&rep->init_section);
  536. rep->init_section = get_fragment(range_val);
  537. xmlFree(range_val);
  538. if (!rep->init_section) {
  539. xmlFree(initialization_val);
  540. return AVERROR(ENOMEM);
  541. }
  542. rep->init_section->url = get_content_url(baseurl_nodes, 4,
  543. max_url_size,
  544. rep_id_val,
  545. rep_bandwidth_val,
  546. initialization_val);
  547. xmlFree(initialization_val);
  548. if (!rep->init_section->url) {
  549. av_freep(&rep->init_section);
  550. return AVERROR(ENOMEM);
  551. }
  552. }
  553. } else if (!av_strcasecmp(fragmenturl_node->name, "SegmentURL")) {
  554. media_val = xmlGetProp(fragmenturl_node, "media");
  555. range_val = xmlGetProp(fragmenturl_node, "mediaRange");
  556. if (media_val || range_val) {
  557. struct fragment *seg = get_fragment(range_val);
  558. xmlFree(range_val);
  559. if (!seg) {
  560. xmlFree(media_val);
  561. return AVERROR(ENOMEM);
  562. }
  563. seg->url = get_content_url(baseurl_nodes, 4,
  564. max_url_size,
  565. rep_id_val,
  566. rep_bandwidth_val,
  567. media_val);
  568. xmlFree(media_val);
  569. if (!seg->url) {
  570. av_free(seg);
  571. return AVERROR(ENOMEM);
  572. }
  573. err = av_dynarray_add_nofree(&rep->fragments, &rep->n_fragments, seg);
  574. if (err < 0) {
  575. free_fragment(&seg);
  576. return err;
  577. }
  578. }
  579. }
  580. return 0;
  581. }
  582. static int parse_manifest_segmenttimeline(AVFormatContext *s, struct representation *rep,
  583. xmlNodePtr fragment_timeline_node)
  584. {
  585. xmlAttrPtr attr = NULL;
  586. char *val = NULL;
  587. int err;
  588. if (!av_strcasecmp(fragment_timeline_node->name, "S")) {
  589. struct timeline *tml = av_mallocz(sizeof(struct timeline));
  590. if (!tml) {
  591. return AVERROR(ENOMEM);
  592. }
  593. attr = fragment_timeline_node->properties;
  594. while (attr) {
  595. val = xmlGetProp(fragment_timeline_node, attr->name);
  596. if (!val) {
  597. av_log(s, AV_LOG_WARNING, "parse_manifest_segmenttimeline attr->name = %s val is NULL\n", attr->name);
  598. continue;
  599. }
  600. if (!av_strcasecmp(attr->name, "t")) {
  601. tml->starttime = (int64_t)strtoll(val, NULL, 10);
  602. } else if (!av_strcasecmp(attr->name, "r")) {
  603. tml->repeat =(int64_t) strtoll(val, NULL, 10);
  604. } else if (!av_strcasecmp(attr->name, "d")) {
  605. tml->duration = (int64_t)strtoll(val, NULL, 10);
  606. }
  607. attr = attr->next;
  608. xmlFree(val);
  609. }
  610. err = av_dynarray_add_nofree(&rep->timelines, &rep->n_timelines, tml);
  611. if (err < 0) {
  612. av_free(tml);
  613. return err;
  614. }
  615. }
  616. return 0;
  617. }
  618. static int resolve_content_path(AVFormatContext *s, const char *url, int *max_url_size, xmlNodePtr *baseurl_nodes, int n_baseurl_nodes)
  619. {
  620. char *tmp_str = NULL;
  621. char *path = NULL;
  622. char *mpdName = NULL;
  623. xmlNodePtr node = NULL;
  624. char *baseurl = NULL;
  625. char *root_url = NULL;
  626. char *text = NULL;
  627. char *tmp = NULL;
  628. int isRootHttp = 0;
  629. char token ='/';
  630. int start = 0;
  631. int rootId = 0;
  632. int updated = 0;
  633. int size = 0;
  634. int i;
  635. int tmp_max_url_size = strlen(url);
  636. for (i = n_baseurl_nodes-1; i >= 0 ; i--) {
  637. text = xmlNodeGetContent(baseurl_nodes[i]);
  638. if (!text)
  639. continue;
  640. tmp_max_url_size += strlen(text);
  641. if (ishttp(text)) {
  642. xmlFree(text);
  643. break;
  644. }
  645. xmlFree(text);
  646. }
  647. tmp_max_url_size = aligned(tmp_max_url_size);
  648. text = av_mallocz(tmp_max_url_size + 1);
  649. if (!text) {
  650. updated = AVERROR(ENOMEM);
  651. goto end;
  652. }
  653. av_strlcpy(text, url, strlen(url)+1);
  654. tmp = text;
  655. while (mpdName = av_strtok(tmp, "/", &tmp)) {
  656. size = strlen(mpdName);
  657. }
  658. av_free(text);
  659. path = av_mallocz(tmp_max_url_size + 2);
  660. tmp_str = av_mallocz(tmp_max_url_size);
  661. if (!tmp_str || !path) {
  662. updated = AVERROR(ENOMEM);
  663. goto end;
  664. }
  665. av_strlcpy (path, url, strlen(url) - size + 1);
  666. for (rootId = n_baseurl_nodes - 1; rootId > 0; rootId --) {
  667. if (!(node = baseurl_nodes[rootId])) {
  668. continue;
  669. }
  670. text = xmlNodeGetContent(node);
  671. if (ishttp(text)) {
  672. xmlFree(text);
  673. break;
  674. }
  675. xmlFree(text);
  676. }
  677. node = baseurl_nodes[rootId];
  678. baseurl = xmlNodeGetContent(node);
  679. if (baseurl) {
  680. size_t len = xmlStrlen(baseurl)+2;
  681. char *tmp = xmlRealloc(baseurl, len);
  682. if (!tmp) {
  683. updated = AVERROR(ENOMEM);
  684. goto end;
  685. }
  686. baseurl = tmp;
  687. }
  688. root_url = (av_strcasecmp(baseurl, "")) ? baseurl : path;
  689. if (node) {
  690. xmlNodeSetContent(node, root_url);
  691. updated = 1;
  692. }
  693. size = strlen(root_url);
  694. isRootHttp = ishttp(root_url);
  695. if (size > 0 && root_url[size - 1] != token) {
  696. av_strlcat(root_url, "/", size + 2);
  697. size += 2;
  698. }
  699. for (i = 0; i < n_baseurl_nodes; ++i) {
  700. if (i == rootId) {
  701. continue;
  702. }
  703. text = xmlNodeGetContent(baseurl_nodes[i]);
  704. if (text && !av_strstart(text, "/", NULL)) {
  705. memset(tmp_str, 0, strlen(tmp_str));
  706. if (!ishttp(text) && isRootHttp) {
  707. av_strlcpy(tmp_str, root_url, size + 1);
  708. }
  709. start = (text[0] == token);
  710. if (start && av_stristr(tmp_str, text)) {
  711. char *p = tmp_str;
  712. if (!av_strncasecmp(tmp_str, "http://", 7)) {
  713. p += 7;
  714. } else if (!av_strncasecmp(tmp_str, "https://", 8)) {
  715. p += 8;
  716. }
  717. p = strchr(p, '/');
  718. memset(p + 1, 0, strlen(p));
  719. }
  720. av_strlcat(tmp_str, text + start, tmp_max_url_size);
  721. xmlNodeSetContent(baseurl_nodes[i], tmp_str);
  722. updated = 1;
  723. xmlFree(text);
  724. }
  725. }
  726. end:
  727. if (tmp_max_url_size > *max_url_size) {
  728. *max_url_size = tmp_max_url_size;
  729. }
  730. av_free(path);
  731. av_free(tmp_str);
  732. xmlFree(baseurl);
  733. return updated;
  734. }
  735. static int parse_manifest_representation(AVFormatContext *s, const char *url,
  736. xmlNodePtr node,
  737. xmlNodePtr adaptionset_node,
  738. xmlNodePtr mpd_baseurl_node,
  739. xmlNodePtr period_baseurl_node,
  740. xmlNodePtr period_segmenttemplate_node,
  741. xmlNodePtr period_segmentlist_node,
  742. xmlNodePtr fragment_template_node,
  743. xmlNodePtr content_component_node,
  744. xmlNodePtr adaptionset_baseurl_node,
  745. xmlNodePtr adaptionset_segmentlist_node,
  746. xmlNodePtr adaptionset_supplementalproperty_node)
  747. {
  748. int32_t ret = 0;
  749. DASHContext *c = s->priv_data;
  750. struct representation *rep = NULL;
  751. struct fragment *seg = NULL;
  752. xmlNodePtr representation_segmenttemplate_node = NULL;
  753. xmlNodePtr representation_baseurl_node = NULL;
  754. xmlNodePtr representation_segmentlist_node = NULL;
  755. xmlNodePtr segmentlists_tab[3];
  756. xmlNodePtr fragment_timeline_node = NULL;
  757. xmlNodePtr fragment_templates_tab[5];
  758. char *val = NULL;
  759. xmlNodePtr baseurl_nodes[4];
  760. xmlNodePtr representation_node = node;
  761. char *rep_bandwidth_val;
  762. enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
  763. // try get information from representation
  764. if (type == AVMEDIA_TYPE_UNKNOWN)
  765. type = get_content_type(representation_node);
  766. // try get information from contentComponen
  767. if (type == AVMEDIA_TYPE_UNKNOWN)
  768. type = get_content_type(content_component_node);
  769. // try get information from adaption set
  770. if (type == AVMEDIA_TYPE_UNKNOWN)
  771. type = get_content_type(adaptionset_node);
  772. if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO &&
  773. type != AVMEDIA_TYPE_SUBTITLE) {
  774. av_log(s, AV_LOG_VERBOSE, "Parsing '%s' - skipp not supported representation type\n", url);
  775. return 0;
  776. }
  777. // convert selected representation to our internal struct
  778. rep = av_mallocz(sizeof(struct representation));
  779. if (!rep)
  780. return AVERROR(ENOMEM);
  781. if (c->adaptionset_lang) {
  782. rep->lang = av_strdup(c->adaptionset_lang);
  783. if (!rep->lang) {
  784. av_log(s, AV_LOG_ERROR, "alloc language memory failure\n");
  785. av_freep(&rep);
  786. return AVERROR(ENOMEM);
  787. }
  788. }
  789. rep->parent = s;
  790. representation_segmenttemplate_node = find_child_node_by_name(representation_node, "SegmentTemplate");
  791. representation_baseurl_node = find_child_node_by_name(representation_node, "BaseURL");
  792. representation_segmentlist_node = find_child_node_by_name(representation_node, "SegmentList");
  793. rep_bandwidth_val = xmlGetProp(representation_node, "bandwidth");
  794. val = xmlGetProp(representation_node, "id");
  795. if (val) {
  796. rep->id = av_strdup(val);
  797. xmlFree(val);
  798. if (!rep->id)
  799. goto enomem;
  800. }
  801. baseurl_nodes[0] = mpd_baseurl_node;
  802. baseurl_nodes[1] = period_baseurl_node;
  803. baseurl_nodes[2] = adaptionset_baseurl_node;
  804. baseurl_nodes[3] = representation_baseurl_node;
  805. ret = resolve_content_path(s, url, &c->max_url_size, baseurl_nodes, 4);
  806. c->max_url_size = aligned(c->max_url_size
  807. + (rep->id ? strlen(rep->id) : 0)
  808. + (rep_bandwidth_val ? strlen(rep_bandwidth_val) : 0));
  809. if (ret == AVERROR(ENOMEM) || ret == 0)
  810. goto free;
  811. if (representation_segmenttemplate_node || fragment_template_node || period_segmenttemplate_node) {
  812. fragment_timeline_node = NULL;
  813. fragment_templates_tab[0] = representation_segmenttemplate_node;
  814. fragment_templates_tab[1] = adaptionset_segmentlist_node;
  815. fragment_templates_tab[2] = fragment_template_node;
  816. fragment_templates_tab[3] = period_segmenttemplate_node;
  817. fragment_templates_tab[4] = period_segmentlist_node;
  818. val = get_val_from_nodes_tab(fragment_templates_tab, 4, "initialization");
  819. if (val) {
  820. rep->init_section = av_mallocz(sizeof(struct fragment));
  821. if (!rep->init_section) {
  822. xmlFree(val);
  823. goto enomem;
  824. }
  825. c->max_url_size = aligned(c->max_url_size + strlen(val));
  826. rep->init_section->url = get_content_url(baseurl_nodes, 4,
  827. c->max_url_size, rep->id,
  828. rep_bandwidth_val, val);
  829. xmlFree(val);
  830. if (!rep->init_section->url)
  831. goto enomem;
  832. rep->init_section->size = -1;
  833. }
  834. val = get_val_from_nodes_tab(fragment_templates_tab, 4, "media");
  835. if (val) {
  836. c->max_url_size = aligned(c->max_url_size + strlen(val));
  837. rep->url_template = get_content_url(baseurl_nodes, 4,
  838. c->max_url_size, rep->id,
  839. rep_bandwidth_val, val);
  840. xmlFree(val);
  841. }
  842. val = get_val_from_nodes_tab(fragment_templates_tab, 4, "presentationTimeOffset");
  843. if (val) {
  844. rep->presentation_timeoffset = (int64_t) strtoll(val, NULL, 10);
  845. av_log(s, AV_LOG_TRACE, "rep->presentation_timeoffset = [%"PRId64"]\n", rep->presentation_timeoffset);
  846. xmlFree(val);
  847. }
  848. val = get_val_from_nodes_tab(fragment_templates_tab, 4, "duration");
  849. if (val) {
  850. rep->fragment_duration = (int64_t) strtoll(val, NULL, 10);
  851. av_log(s, AV_LOG_TRACE, "rep->fragment_duration = [%"PRId64"]\n", rep->fragment_duration);
  852. xmlFree(val);
  853. }
  854. val = get_val_from_nodes_tab(fragment_templates_tab, 4, "timescale");
  855. if (val) {
  856. rep->fragment_timescale = (int64_t) strtoll(val, NULL, 10);
  857. av_log(s, AV_LOG_TRACE, "rep->fragment_timescale = [%"PRId64"]\n", rep->fragment_timescale);
  858. xmlFree(val);
  859. }
  860. val = get_val_from_nodes_tab(fragment_templates_tab, 4, "startNumber");
  861. if (val) {
  862. rep->start_number = rep->first_seq_no = (int64_t) strtoll(val, NULL, 10);
  863. av_log(s, AV_LOG_TRACE, "rep->first_seq_no = [%"PRId64"]\n", rep->first_seq_no);
  864. xmlFree(val);
  865. }
  866. if (adaptionset_supplementalproperty_node) {
  867. char *scheme_id_uri = xmlGetProp(adaptionset_supplementalproperty_node, "schemeIdUri");
  868. if (scheme_id_uri) {
  869. int is_last_segment_number = !av_strcasecmp(scheme_id_uri, "http://dashif.org/guidelines/last-segment-number");
  870. xmlFree(scheme_id_uri);
  871. if (is_last_segment_number) {
  872. val = xmlGetProp(adaptionset_supplementalproperty_node, "value");
  873. if (!val) {
  874. av_log(s, AV_LOG_ERROR, "Missing value attribute in adaptionset_supplementalproperty_node\n");
  875. } else {
  876. rep->last_seq_no = (int64_t)strtoll(val, NULL, 10) - 1;
  877. xmlFree(val);
  878. }
  879. }
  880. }
  881. }
  882. fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
  883. if (!fragment_timeline_node)
  884. fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
  885. if (!fragment_timeline_node)
  886. fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
  887. if (!fragment_timeline_node)
  888. fragment_timeline_node = find_child_node_by_name(period_segmentlist_node, "SegmentTimeline");
  889. if (fragment_timeline_node) {
  890. fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
  891. while (fragment_timeline_node) {
  892. ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
  893. if (ret < 0)
  894. goto free;
  895. fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
  896. }
  897. }
  898. } else if (representation_baseurl_node && !representation_segmentlist_node) {
  899. seg = av_mallocz(sizeof(struct fragment));
  900. if (!seg)
  901. goto enomem;
  902. ret = av_dynarray_add_nofree(&rep->fragments, &rep->n_fragments, seg);
  903. if (ret < 0) {
  904. av_free(seg);
  905. goto free;
  906. }
  907. seg->url = get_content_url(baseurl_nodes, 4, c->max_url_size,
  908. rep->id, rep_bandwidth_val, NULL);
  909. if (!seg->url)
  910. goto enomem;
  911. seg->size = -1;
  912. } else if (representation_segmentlist_node) {
  913. // TODO: https://www.brendanlong.com/the-structure-of-an-mpeg-dash-mpd.html
  914. // http://www-itec.uni-klu.ac.at/dash/ddash/mpdGenerator.php?fragmentlength=15&type=full
  915. xmlNodePtr fragmenturl_node = NULL;
  916. segmentlists_tab[0] = representation_segmentlist_node;
  917. segmentlists_tab[1] = adaptionset_segmentlist_node;
  918. segmentlists_tab[2] = period_segmentlist_node;
  919. val = get_val_from_nodes_tab(segmentlists_tab, 3, "duration");
  920. if (val) {
  921. rep->fragment_duration = (int64_t) strtoll(val, NULL, 10);
  922. av_log(s, AV_LOG_TRACE, "rep->fragment_duration = [%"PRId64"]\n", rep->fragment_duration);
  923. xmlFree(val);
  924. }
  925. val = get_val_from_nodes_tab(segmentlists_tab, 3, "timescale");
  926. if (val) {
  927. rep->fragment_timescale = (int64_t) strtoll(val, NULL, 10);
  928. av_log(s, AV_LOG_TRACE, "rep->fragment_timescale = [%"PRId64"]\n", rep->fragment_timescale);
  929. xmlFree(val);
  930. }
  931. val = get_val_from_nodes_tab(segmentlists_tab, 3, "startNumber");
  932. if (val) {
  933. rep->start_number = rep->first_seq_no = (int64_t) strtoll(val, NULL, 10);
  934. av_log(s, AV_LOG_TRACE, "rep->first_seq_no = [%"PRId64"]\n", rep->first_seq_no);
  935. xmlFree(val);
  936. }
  937. fragmenturl_node = xmlFirstElementChild(representation_segmentlist_node);
  938. while (fragmenturl_node) {
  939. ret = parse_manifest_segmenturlnode(s, rep, fragmenturl_node,
  940. baseurl_nodes, rep->id,
  941. rep_bandwidth_val);
  942. if (ret < 0)
  943. goto free;
  944. fragmenturl_node = xmlNextElementSibling(fragmenturl_node);
  945. }
  946. fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
  947. if (!fragment_timeline_node)
  948. fragment_timeline_node = find_child_node_by_name(period_segmentlist_node, "SegmentTimeline");
  949. if (fragment_timeline_node) {
  950. fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
  951. while (fragment_timeline_node) {
  952. ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
  953. if (ret < 0)
  954. goto free;
  955. fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
  956. }
  957. }
  958. } else {
  959. av_log(s, AV_LOG_ERROR, "Unknown format of Representation node id '%s' \n",
  960. rep->id ? rep->id : "");
  961. goto free;
  962. }
  963. if (rep->fragment_duration > 0 && !rep->fragment_timescale)
  964. rep->fragment_timescale = 1;
  965. rep->bandwidth = rep_bandwidth_val ? atoi(rep_bandwidth_val) : 0;
  966. rep->framerate = av_make_q(0, 0);
  967. if (type == AVMEDIA_TYPE_VIDEO) {
  968. char *rep_framerate_val = xmlGetProp(representation_node, "frameRate");
  969. if (rep_framerate_val) {
  970. ret = av_parse_video_rate(&rep->framerate, rep_framerate_val);
  971. if (ret < 0)
  972. av_log(s, AV_LOG_VERBOSE, "Ignoring invalid frame rate '%s'\n", rep_framerate_val);
  973. xmlFree(rep_framerate_val);
  974. }
  975. }
  976. switch (type) {
  977. case AVMEDIA_TYPE_VIDEO:
  978. ret = av_dynarray_add_nofree(&c->videos, &c->n_videos, rep);
  979. break;
  980. case AVMEDIA_TYPE_AUDIO:
  981. ret = av_dynarray_add_nofree(&c->audios, &c->n_audios, rep);
  982. break;
  983. case AVMEDIA_TYPE_SUBTITLE:
  984. ret = av_dynarray_add_nofree(&c->subtitles, &c->n_subtitles, rep);
  985. break;
  986. }
  987. if (ret < 0)
  988. goto free;
  989. end:
  990. if (rep_bandwidth_val)
  991. xmlFree(rep_bandwidth_val);
  992. return ret;
  993. enomem:
  994. ret = AVERROR(ENOMEM);
  995. free:
  996. free_representation(rep);
  997. goto end;
  998. }
  999. static int parse_manifest_adaptationset_attr(AVFormatContext *s, xmlNodePtr adaptionset_node)
  1000. {
  1001. DASHContext *c = s->priv_data;
  1002. if (!adaptionset_node) {
  1003. av_log(s, AV_LOG_WARNING, "Cannot get AdaptionSet\n");
  1004. return AVERROR(EINVAL);
  1005. }
  1006. c->adaptionset_lang = xmlGetProp(adaptionset_node, "lang");
  1007. return 0;
  1008. }
  1009. static int parse_manifest_adaptationset(AVFormatContext *s, const char *url,
  1010. xmlNodePtr adaptionset_node,
  1011. xmlNodePtr mpd_baseurl_node,
  1012. xmlNodePtr period_baseurl_node,
  1013. xmlNodePtr period_segmenttemplate_node,
  1014. xmlNodePtr period_segmentlist_node)
  1015. {
  1016. int ret = 0;
  1017. DASHContext *c = s->priv_data;
  1018. xmlNodePtr fragment_template_node = NULL;
  1019. xmlNodePtr content_component_node = NULL;
  1020. xmlNodePtr adaptionset_baseurl_node = NULL;
  1021. xmlNodePtr adaptionset_segmentlist_node = NULL;
  1022. xmlNodePtr adaptionset_supplementalproperty_node = NULL;
  1023. xmlNodePtr node = NULL;
  1024. ret = parse_manifest_adaptationset_attr(s, adaptionset_node);
  1025. if (ret < 0)
  1026. return ret;
  1027. node = xmlFirstElementChild(adaptionset_node);
  1028. while (node) {
  1029. if (!av_strcasecmp(node->name, "SegmentTemplate")) {
  1030. fragment_template_node = node;
  1031. } else if (!av_strcasecmp(node->name, "ContentComponent")) {
  1032. content_component_node = node;
  1033. } else if (!av_strcasecmp(node->name, "BaseURL")) {
  1034. adaptionset_baseurl_node = node;
  1035. } else if (!av_strcasecmp(node->name, "SegmentList")) {
  1036. adaptionset_segmentlist_node = node;
  1037. } else if (!av_strcasecmp(node->name, "SupplementalProperty")) {
  1038. adaptionset_supplementalproperty_node = node;
  1039. } else if (!av_strcasecmp(node->name, "Representation")) {
  1040. ret = parse_manifest_representation(s, url, node,
  1041. adaptionset_node,
  1042. mpd_baseurl_node,
  1043. period_baseurl_node,
  1044. period_segmenttemplate_node,
  1045. period_segmentlist_node,
  1046. fragment_template_node,
  1047. content_component_node,
  1048. adaptionset_baseurl_node,
  1049. adaptionset_segmentlist_node,
  1050. adaptionset_supplementalproperty_node);
  1051. if (ret < 0)
  1052. goto err;
  1053. }
  1054. node = xmlNextElementSibling(node);
  1055. }
  1056. err:
  1057. xmlFree(c->adaptionset_lang);
  1058. c->adaptionset_lang = NULL;
  1059. return ret;
  1060. }
  1061. static int parse_programinformation(AVFormatContext *s, xmlNodePtr node)
  1062. {
  1063. xmlChar *val = NULL;
  1064. node = xmlFirstElementChild(node);
  1065. while (node) {
  1066. if (!av_strcasecmp(node->name, "Title")) {
  1067. val = xmlNodeGetContent(node);
  1068. if (val) {
  1069. av_dict_set(&s->metadata, "Title", val, 0);
  1070. }
  1071. } else if (!av_strcasecmp(node->name, "Source")) {
  1072. val = xmlNodeGetContent(node);
  1073. if (val) {
  1074. av_dict_set(&s->metadata, "Source", val, 0);
  1075. }
  1076. } else if (!av_strcasecmp(node->name, "Copyright")) {
  1077. val = xmlNodeGetContent(node);
  1078. if (val) {
  1079. av_dict_set(&s->metadata, "Copyright", val, 0);
  1080. }
  1081. }
  1082. node = xmlNextElementSibling(node);
  1083. xmlFree(val);
  1084. val = NULL;
  1085. }
  1086. return 0;
  1087. }
  1088. static int parse_manifest(AVFormatContext *s, const char *url, AVIOContext *in)
  1089. {
  1090. DASHContext *c = s->priv_data;
  1091. int ret = 0;
  1092. int close_in = 0;
  1093. AVBPrint buf;
  1094. AVDictionary *opts = NULL;
  1095. xmlDoc *doc = NULL;
  1096. xmlNodePtr root_element = NULL;
  1097. xmlNodePtr node = NULL;
  1098. xmlNodePtr period_node = NULL;
  1099. xmlNodePtr tmp_node = NULL;
  1100. xmlNodePtr mpd_baseurl_node = NULL;
  1101. xmlNodePtr period_baseurl_node = NULL;
  1102. xmlNodePtr period_segmenttemplate_node = NULL;
  1103. xmlNodePtr period_segmentlist_node = NULL;
  1104. xmlNodePtr adaptionset_node = NULL;
  1105. xmlAttrPtr attr = NULL;
  1106. char *val = NULL;
  1107. uint32_t period_duration_sec = 0;
  1108. uint32_t period_start_sec = 0;
  1109. if (!in) {
  1110. close_in = 1;
  1111. av_dict_copy(&opts, c->avio_opts, 0);
  1112. ret = ffio_open_whitelist(&in, url, AVIO_FLAG_READ, c->interrupt_callback, &opts, s->protocol_whitelist, s->protocol_blacklist);
  1113. av_dict_free(&opts);
  1114. if (ret < 0)
  1115. return ret;
  1116. }
  1117. if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&c->base_url) < 0)
  1118. c->base_url = av_strdup(url);
  1119. av_bprint_init(&buf, 0, INT_MAX); // xmlReadMemory uses integer bufsize
  1120. if ((ret = avio_read_to_bprint(in, &buf, SIZE_MAX)) < 0 ||
  1121. !avio_feof(in)) {
  1122. av_log(s, AV_LOG_ERROR, "Unable to read to manifest '%s'\n", url);
  1123. if (ret == 0)
  1124. ret = AVERROR_INVALIDDATA;
  1125. } else {
  1126. LIBXML_TEST_VERSION
  1127. doc = xmlReadMemory(buf.str, buf.len, c->base_url, NULL, 0);
  1128. root_element = xmlDocGetRootElement(doc);
  1129. node = root_element;
  1130. if (!node) {
  1131. ret = AVERROR_INVALIDDATA;
  1132. av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing root node\n", url);
  1133. goto cleanup;
  1134. }
  1135. if (node->type != XML_ELEMENT_NODE ||
  1136. av_strcasecmp(node->name, "MPD")) {
  1137. ret = AVERROR_INVALIDDATA;
  1138. av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - wrong root node name[%s] type[%d]\n", url, node->name, (int)node->type);
  1139. goto cleanup;
  1140. }
  1141. val = xmlGetProp(node, "type");
  1142. if (!val) {
  1143. av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing type attrib\n", url);
  1144. ret = AVERROR_INVALIDDATA;
  1145. goto cleanup;
  1146. }
  1147. if (!av_strcasecmp(val, "dynamic"))
  1148. c->is_live = 1;
  1149. xmlFree(val);
  1150. attr = node->properties;
  1151. while (attr) {
  1152. val = xmlGetProp(node, attr->name);
  1153. if (!av_strcasecmp(attr->name, "availabilityStartTime")) {
  1154. c->availability_start_time = get_utc_date_time_insec(s, val);
  1155. av_log(s, AV_LOG_TRACE, "c->availability_start_time = [%"PRId64"]\n", c->availability_start_time);
  1156. } else if (!av_strcasecmp(attr->name, "availabilityEndTime")) {
  1157. c->availability_end_time = get_utc_date_time_insec(s, val);
  1158. av_log(s, AV_LOG_TRACE, "c->availability_end_time = [%"PRId64"]\n", c->availability_end_time);
  1159. } else if (!av_strcasecmp(attr->name, "publishTime")) {
  1160. c->publish_time = get_utc_date_time_insec(s, val);
  1161. av_log(s, AV_LOG_TRACE, "c->publish_time = [%"PRId64"]\n", c->publish_time);
  1162. } else if (!av_strcasecmp(attr->name, "minimumUpdatePeriod")) {
  1163. c->minimum_update_period = get_duration_insec(s, val);
  1164. av_log(s, AV_LOG_TRACE, "c->minimum_update_period = [%"PRId64"]\n", c->minimum_update_period);
  1165. } else if (!av_strcasecmp(attr->name, "timeShiftBufferDepth")) {
  1166. c->time_shift_buffer_depth = get_duration_insec(s, val);
  1167. av_log(s, AV_LOG_TRACE, "c->time_shift_buffer_depth = [%"PRId64"]\n", c->time_shift_buffer_depth);
  1168. } else if (!av_strcasecmp(attr->name, "minBufferTime")) {
  1169. c->min_buffer_time = get_duration_insec(s, val);
  1170. av_log(s, AV_LOG_TRACE, "c->min_buffer_time = [%"PRId64"]\n", c->min_buffer_time);
  1171. } else if (!av_strcasecmp(attr->name, "suggestedPresentationDelay")) {
  1172. c->suggested_presentation_delay = get_duration_insec(s, val);
  1173. av_log(s, AV_LOG_TRACE, "c->suggested_presentation_delay = [%"PRId64"]\n", c->suggested_presentation_delay);
  1174. } else if (!av_strcasecmp(attr->name, "mediaPresentationDuration")) {
  1175. c->media_presentation_duration = get_duration_insec(s, val);
  1176. av_log(s, AV_LOG_TRACE, "c->media_presentation_duration = [%"PRId64"]\n", c->media_presentation_duration);
  1177. }
  1178. attr = attr->next;
  1179. xmlFree(val);
  1180. }
  1181. tmp_node = find_child_node_by_name(node, "BaseURL");
  1182. if (tmp_node) {
  1183. mpd_baseurl_node = xmlCopyNode(tmp_node,1);
  1184. } else {
  1185. mpd_baseurl_node = xmlNewNode(NULL, "BaseURL");
  1186. }
  1187. // at now we can handle only one period, with the longest duration
  1188. node = xmlFirstElementChild(node);
  1189. while (node) {
  1190. if (!av_strcasecmp(node->name, "Period")) {
  1191. period_duration_sec = 0;
  1192. period_start_sec = 0;
  1193. attr = node->properties;
  1194. while (attr) {
  1195. val = xmlGetProp(node, attr->name);
  1196. if (!av_strcasecmp(attr->name, "duration")) {
  1197. period_duration_sec = get_duration_insec(s, val);
  1198. } else if (!av_strcasecmp(attr->name, "start")) {
  1199. period_start_sec = get_duration_insec(s, val);
  1200. }
  1201. attr = attr->next;
  1202. xmlFree(val);
  1203. }
  1204. if ((period_duration_sec) >= (c->period_duration)) {
  1205. period_node = node;
  1206. c->period_duration = period_duration_sec;
  1207. c->period_start = period_start_sec;
  1208. if (c->period_start > 0)
  1209. c->media_presentation_duration = c->period_duration;
  1210. }
  1211. } else if (!av_strcasecmp(node->name, "ProgramInformation")) {
  1212. parse_programinformation(s, node);
  1213. }
  1214. node = xmlNextElementSibling(node);
  1215. }
  1216. if (!period_node) {
  1217. av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing Period node\n", url);
  1218. ret = AVERROR_INVALIDDATA;
  1219. goto cleanup;
  1220. }
  1221. adaptionset_node = xmlFirstElementChild(period_node);
  1222. while (adaptionset_node) {
  1223. if (!av_strcasecmp(adaptionset_node->name, "BaseURL")) {
  1224. period_baseurl_node = adaptionset_node;
  1225. } else if (!av_strcasecmp(adaptionset_node->name, "SegmentTemplate")) {
  1226. period_segmenttemplate_node = adaptionset_node;
  1227. } else if (!av_strcasecmp(adaptionset_node->name, "SegmentList")) {
  1228. period_segmentlist_node = adaptionset_node;
  1229. } else if (!av_strcasecmp(adaptionset_node->name, "AdaptationSet")) {
  1230. parse_manifest_adaptationset(s, url, adaptionset_node, mpd_baseurl_node, period_baseurl_node, period_segmenttemplate_node, period_segmentlist_node);
  1231. }
  1232. adaptionset_node = xmlNextElementSibling(adaptionset_node);
  1233. }
  1234. cleanup:
  1235. /*free the document */
  1236. xmlFreeDoc(doc);
  1237. xmlCleanupParser();
  1238. xmlFreeNode(mpd_baseurl_node);
  1239. }
  1240. av_bprint_finalize(&buf, NULL);
  1241. if (close_in) {
  1242. avio_close(in);
  1243. }
  1244. return ret;
  1245. }
  1246. static int64_t calc_cur_seg_no(AVFormatContext *s, struct representation *pls)
  1247. {
  1248. DASHContext *c = s->priv_data;
  1249. int64_t num = 0;
  1250. int64_t start_time_offset = 0;
  1251. if (c->is_live) {
  1252. if (pls->n_fragments) {
  1253. av_log(s, AV_LOG_TRACE, "in n_fragments mode\n");
  1254. num = pls->first_seq_no;
  1255. } else if (pls->n_timelines) {
  1256. av_log(s, AV_LOG_TRACE, "in n_timelines mode\n");
  1257. start_time_offset = get_segment_start_time_based_on_timeline(pls, 0xFFFFFFFF) - 60 * pls->fragment_timescale; // 60 seconds before end
  1258. num = calc_next_seg_no_from_timelines(pls, start_time_offset);
  1259. if (num == -1)
  1260. num = pls->first_seq_no;
  1261. else
  1262. num += pls->first_seq_no;
  1263. } else if (pls->fragment_duration){
  1264. av_log(s, AV_LOG_TRACE, "in fragment_duration mode fragment_timescale = %"PRId64", presentation_timeoffset = %"PRId64"\n", pls->fragment_timescale, pls->presentation_timeoffset);
  1265. if (pls->presentation_timeoffset) {
  1266. num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time) * pls->fragment_timescale)-pls->presentation_timeoffset) / pls->fragment_duration - c->min_buffer_time;
  1267. } else if (c->publish_time > 0 && !c->availability_start_time) {
  1268. if (c->min_buffer_time) {
  1269. num = pls->first_seq_no + (((c->publish_time + pls->fragment_duration) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration - c->min_buffer_time;
  1270. } else {
  1271. num = pls->first_seq_no + (((c->publish_time - c->time_shift_buffer_depth + pls->fragment_duration) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
  1272. }
  1273. } else {
  1274. num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
  1275. }
  1276. }
  1277. } else {
  1278. num = pls->first_seq_no;
  1279. }
  1280. return num;
  1281. }
  1282. static int64_t calc_min_seg_no(AVFormatContext *s, struct representation *pls)
  1283. {
  1284. DASHContext *c = s->priv_data;
  1285. int64_t num = 0;
  1286. if (c->is_live && pls->fragment_duration) {
  1287. av_log(s, AV_LOG_TRACE, "in live mode\n");
  1288. num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time) - c->time_shift_buffer_depth) * pls->fragment_timescale) / pls->fragment_duration;
  1289. } else {
  1290. num = pls->first_seq_no;
  1291. }
  1292. return num;
  1293. }
  1294. static int64_t calc_max_seg_no(struct representation *pls, DASHContext *c)
  1295. {
  1296. int64_t num = 0;
  1297. if (pls->n_fragments) {
  1298. num = pls->first_seq_no + pls->n_fragments - 1;
  1299. } else if (pls->n_timelines) {
  1300. int i = 0;
  1301. num = pls->first_seq_no + pls->n_timelines - 1;
  1302. for (i = 0; i < pls->n_timelines; i++) {
  1303. if (pls->timelines[i]->repeat == -1) {
  1304. int length_of_each_segment = pls->timelines[i]->duration / pls->fragment_timescale;
  1305. num = c->period_duration / length_of_each_segment;
  1306. } else {
  1307. num += pls->timelines[i]->repeat;
  1308. }
  1309. }
  1310. } else if (c->is_live && pls->fragment_duration) {
  1311. num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time)) * pls->fragment_timescale) / pls->fragment_duration;
  1312. } else if (pls->fragment_duration) {
  1313. num = pls->first_seq_no + av_rescale_rnd(1, c->media_presentation_duration * pls->fragment_timescale, pls->fragment_duration, AV_ROUND_UP);
  1314. }
  1315. return num;
  1316. }
  1317. static void move_timelines(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
  1318. {
  1319. if (rep_dest && rep_src ) {
  1320. free_timelines_list(rep_dest);
  1321. rep_dest->timelines = rep_src->timelines;
  1322. rep_dest->n_timelines = rep_src->n_timelines;
  1323. rep_dest->first_seq_no = rep_src->first_seq_no;
  1324. rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
  1325. rep_src->timelines = NULL;
  1326. rep_src->n_timelines = 0;
  1327. rep_dest->cur_seq_no = rep_src->cur_seq_no;
  1328. }
  1329. }
  1330. static void move_segments(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
  1331. {
  1332. if (rep_dest && rep_src ) {
  1333. free_fragment_list(rep_dest);
  1334. if (rep_src->start_number > (rep_dest->start_number + rep_dest->n_fragments))
  1335. rep_dest->cur_seq_no = 0;
  1336. else
  1337. rep_dest->cur_seq_no += rep_src->start_number - rep_dest->start_number;
  1338. rep_dest->fragments = rep_src->fragments;
  1339. rep_dest->n_fragments = rep_src->n_fragments;
  1340. rep_dest->parent = rep_src->parent;
  1341. rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
  1342. rep_src->fragments = NULL;
  1343. rep_src->n_fragments = 0;
  1344. }
  1345. }
  1346. static int refresh_manifest(AVFormatContext *s)
  1347. {
  1348. int ret = 0, i;
  1349. DASHContext *c = s->priv_data;
  1350. // save current context
  1351. int n_videos = c->n_videos;
  1352. struct representation **videos = c->videos;
  1353. int n_audios = c->n_audios;
  1354. struct representation **audios = c->audios;
  1355. int n_subtitles = c->n_subtitles;
  1356. struct representation **subtitles = c->subtitles;
  1357. char *base_url = c->base_url;
  1358. c->base_url = NULL;
  1359. c->n_videos = 0;
  1360. c->videos = NULL;
  1361. c->n_audios = 0;
  1362. c->audios = NULL;
  1363. c->n_subtitles = 0;
  1364. c->subtitles = NULL;
  1365. ret = parse_manifest(s, s->url, NULL);
  1366. if (ret)
  1367. goto finish;
  1368. if (c->n_videos != n_videos) {
  1369. av_log(c, AV_LOG_ERROR,
  1370. "new manifest has mismatched no. of video representations, %d -> %d\n",
  1371. n_videos, c->n_videos);
  1372. return AVERROR_INVALIDDATA;
  1373. }
  1374. if (c->n_audios != n_audios) {
  1375. av_log(c, AV_LOG_ERROR,
  1376. "new manifest has mismatched no. of audio representations, %d -> %d\n",
  1377. n_audios, c->n_audios);
  1378. return AVERROR_INVALIDDATA;
  1379. }
  1380. if (c->n_subtitles != n_subtitles) {
  1381. av_log(c, AV_LOG_ERROR,
  1382. "new manifest has mismatched no. of subtitles representations, %d -> %d\n",
  1383. n_subtitles, c->n_subtitles);
  1384. return AVERROR_INVALIDDATA;
  1385. }
  1386. for (i = 0; i < n_videos; i++) {
  1387. struct representation *cur_video = videos[i];
  1388. struct representation *ccur_video = c->videos[i];
  1389. if (cur_video->timelines) {
  1390. // calc current time
  1391. int64_t currentTime = get_segment_start_time_based_on_timeline(cur_video, cur_video->cur_seq_no) / cur_video->fragment_timescale;
  1392. // update segments
  1393. ccur_video->cur_seq_no = calc_next_seg_no_from_timelines(ccur_video, currentTime * cur_video->fragment_timescale - 1);
  1394. if (ccur_video->cur_seq_no >= 0) {
  1395. move_timelines(ccur_video, cur_video, c);
  1396. }
  1397. }
  1398. if (cur_video->fragments) {
  1399. move_segments(ccur_video, cur_video, c);
  1400. }
  1401. }
  1402. for (i = 0; i < n_audios; i++) {
  1403. struct representation *cur_audio = audios[i];
  1404. struct representation *ccur_audio = c->audios[i];
  1405. if (cur_audio->timelines) {
  1406. // calc current time
  1407. int64_t currentTime = get_segment_start_time_based_on_timeline(cur_audio, cur_audio->cur_seq_no) / cur_audio->fragment_timescale;
  1408. // update segments
  1409. ccur_audio->cur_seq_no = calc_next_seg_no_from_timelines(ccur_audio, currentTime * cur_audio->fragment_timescale - 1);
  1410. if (ccur_audio->cur_seq_no >= 0) {
  1411. move_timelines(ccur_audio, cur_audio, c);
  1412. }
  1413. }
  1414. if (cur_audio->fragments) {
  1415. move_segments(ccur_audio, cur_audio, c);
  1416. }
  1417. }
  1418. finish:
  1419. // restore context
  1420. if (c->base_url)
  1421. av_free(base_url);
  1422. else
  1423. c->base_url = base_url;
  1424. if (c->subtitles)
  1425. free_subtitle_list(c);
  1426. if (c->audios)
  1427. free_audio_list(c);
  1428. if (c->videos)
  1429. free_video_list(c);
  1430. c->n_subtitles = n_subtitles;
  1431. c->subtitles = subtitles;
  1432. c->n_audios = n_audios;
  1433. c->audios = audios;
  1434. c->n_videos = n_videos;
  1435. c->videos = videos;
  1436. return ret;
  1437. }
  1438. static struct fragment *get_current_fragment(struct representation *pls)
  1439. {
  1440. int64_t min_seq_no = 0;
  1441. int64_t max_seq_no = 0;
  1442. struct fragment *seg = NULL;
  1443. struct fragment *seg_ptr = NULL;
  1444. DASHContext *c = pls->parent->priv_data;
  1445. while (( !ff_check_interrupt(c->interrupt_callback)&& pls->n_fragments > 0)) {
  1446. if (pls->cur_seq_no < pls->n_fragments) {
  1447. seg_ptr = pls->fragments[pls->cur_seq_no];
  1448. seg = av_mallocz(sizeof(struct fragment));
  1449. if (!seg) {
  1450. return NULL;
  1451. }
  1452. seg->url = av_strdup(seg_ptr->url);
  1453. if (!seg->url) {
  1454. av_free(seg);
  1455. return NULL;
  1456. }
  1457. seg->size = seg_ptr->size;
  1458. seg->url_offset = seg_ptr->url_offset;
  1459. return seg;
  1460. } else if (c->is_live) {
  1461. refresh_manifest(pls->parent);
  1462. } else {
  1463. break;
  1464. }
  1465. }
  1466. if (c->is_live) {
  1467. min_seq_no = calc_min_seg_no(pls->parent, pls);
  1468. max_seq_no = calc_max_seg_no(pls, c);
  1469. if (pls->timelines || pls->fragments) {
  1470. refresh_manifest(pls->parent);
  1471. }
  1472. if (pls->cur_seq_no <= min_seq_no) {
  1473. av_log(pls->parent, AV_LOG_VERBOSE, "old fragment: cur[%"PRId64"] min[%"PRId64"] max[%"PRId64"]\n", (int64_t)pls->cur_seq_no, min_seq_no, max_seq_no);
  1474. pls->cur_seq_no = calc_cur_seg_no(pls->parent, pls);
  1475. } else if (pls->cur_seq_no > max_seq_no) {
  1476. av_log(pls->parent, AV_LOG_VERBOSE, "new fragment: min[%"PRId64"] max[%"PRId64"]\n", min_seq_no, max_seq_no);
  1477. }
  1478. seg = av_mallocz(sizeof(struct fragment));
  1479. if (!seg) {
  1480. return NULL;
  1481. }
  1482. } else if (pls->cur_seq_no <= pls->last_seq_no) {
  1483. seg = av_mallocz(sizeof(struct fragment));
  1484. if (!seg) {
  1485. return NULL;
  1486. }
  1487. }
  1488. if (seg) {
  1489. char *tmpfilename;
  1490. if (!pls->url_template) {
  1491. av_log(pls->parent, AV_LOG_ERROR, "Cannot get fragment, missing template URL\n");
  1492. av_free(seg);
  1493. return NULL;
  1494. }
  1495. tmpfilename = av_mallocz(c->max_url_size);
  1496. if (!tmpfilename) {
  1497. av_free(seg);
  1498. return NULL;
  1499. }
  1500. ff_dash_fill_tmpl_params(tmpfilename, c->max_url_size, pls->url_template, 0, pls->cur_seq_no, 0, get_segment_start_time_based_on_timeline(pls, pls->cur_seq_no));
  1501. seg->url = av_strireplace(pls->url_template, pls->url_template, tmpfilename);
  1502. if (!seg->url) {
  1503. av_log(pls->parent, AV_LOG_WARNING, "Unable to resolve template url '%s', try to use origin template\n", pls->url_template);
  1504. seg->url = av_strdup(pls->url_template);
  1505. if (!seg->url) {
  1506. av_log(pls->parent, AV_LOG_ERROR, "Cannot resolve template url '%s'\n", pls->url_template);
  1507. av_free(tmpfilename);
  1508. av_free(seg);
  1509. return NULL;
  1510. }
  1511. }
  1512. av_free(tmpfilename);
  1513. seg->size = -1;
  1514. }
  1515. return seg;
  1516. }
  1517. static int read_from_url(struct representation *pls, struct fragment *seg,
  1518. uint8_t *buf, int buf_size)
  1519. {
  1520. int ret;
  1521. /* limit read if the fragment was only a part of a file */
  1522. if (seg->size >= 0)
  1523. buf_size = FFMIN(buf_size, pls->cur_seg_size - pls->cur_seg_offset);
  1524. ret = avio_read(pls->input, buf, buf_size);
  1525. if (ret > 0)
  1526. pls->cur_seg_offset += ret;
  1527. return ret;
  1528. }
  1529. static int open_input(DASHContext *c, struct representation *pls, struct fragment *seg)
  1530. {
  1531. AVDictionary *opts = NULL;
  1532. char *url = NULL;
  1533. int ret = 0;
  1534. url = av_mallocz(c->max_url_size);
  1535. if (!url) {
  1536. ret = AVERROR(ENOMEM);
  1537. goto cleanup;
  1538. }
  1539. if (seg->size >= 0) {
  1540. /* try to restrict the HTTP request to the part we want
  1541. * (if this is in fact a HTTP request) */
  1542. av_dict_set_int(&opts, "offset", seg->url_offset, 0);
  1543. av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
  1544. }
  1545. ff_make_absolute_url(url, c->max_url_size, c->base_url, seg->url);
  1546. av_log(pls->parent, AV_LOG_VERBOSE, "DASH request for url '%s', offset %"PRId64"\n",
  1547. url, seg->url_offset);
  1548. ret = open_url(pls->parent, &pls->input, url, &c->avio_opts, opts, NULL);
  1549. cleanup:
  1550. av_free(url);
  1551. av_dict_free(&opts);
  1552. pls->cur_seg_offset = 0;
  1553. pls->cur_seg_size = seg->size;
  1554. return ret;
  1555. }
  1556. static int update_init_section(struct representation *pls)
  1557. {
  1558. static const int max_init_section_size = 1024 * 1024;
  1559. DASHContext *c = pls->parent->priv_data;
  1560. int64_t sec_size;
  1561. int64_t urlsize;
  1562. int ret;
  1563. if (!pls->init_section || pls->init_sec_buf)
  1564. return 0;
  1565. ret = open_input(c, pls, pls->init_section);
  1566. if (ret < 0) {
  1567. av_log(pls->parent, AV_LOG_WARNING,
  1568. "Failed to open an initialization section\n");
  1569. return ret;
  1570. }
  1571. if (pls->init_section->size >= 0)
  1572. sec_size = pls->init_section->size;
  1573. else if ((urlsize = avio_size(pls->input)) >= 0)
  1574. sec_size = urlsize;
  1575. else
  1576. sec_size = max_init_section_size;
  1577. av_log(pls->parent, AV_LOG_DEBUG,
  1578. "Downloading an initialization section of size %"PRId64"\n",
  1579. sec_size);
  1580. sec_size = FFMIN(sec_size, max_init_section_size);
  1581. av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
  1582. ret = read_from_url(pls, pls->init_section, pls->init_sec_buf,
  1583. pls->init_sec_buf_size);
  1584. ff_format_io_close(pls->parent, &pls->input);
  1585. if (ret < 0)
  1586. return ret;
  1587. pls->init_sec_data_len = ret;
  1588. pls->init_sec_buf_read_offset = 0;
  1589. return 0;
  1590. }
  1591. static int64_t seek_data(void *opaque, int64_t offset, int whence)
  1592. {
  1593. struct representation *v = opaque;
  1594. if (v->n_fragments && !v->init_sec_data_len) {
  1595. return avio_seek(v->input, offset, whence);
  1596. }
  1597. return AVERROR(ENOSYS);
  1598. }
  1599. static int read_data(void *opaque, uint8_t *buf, int buf_size)
  1600. {
  1601. int ret = 0;
  1602. struct representation *v = opaque;
  1603. DASHContext *c = v->parent->priv_data;
  1604. restart:
  1605. if (!v->input) {
  1606. free_fragment(&v->cur_seg);
  1607. v->cur_seg = get_current_fragment(v);
  1608. if (!v->cur_seg) {
  1609. ret = AVERROR_EOF;
  1610. goto end;
  1611. }
  1612. /* load/update Media Initialization Section, if any */
  1613. ret = update_init_section(v);
  1614. if (ret)
  1615. goto end;
  1616. ret = open_input(c, v, v->cur_seg);
  1617. if (ret < 0) {
  1618. if (ff_check_interrupt(c->interrupt_callback)) {
  1619. ret = AVERROR_EXIT;
  1620. goto end;
  1621. }
  1622. av_log(v->parent, AV_LOG_WARNING, "Failed to open fragment of playlist\n");
  1623. v->cur_seq_no++;
  1624. goto restart;
  1625. }
  1626. }
  1627. if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
  1628. /* Push init section out first before first actual fragment */
  1629. int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
  1630. memcpy(buf, v->init_sec_buf, copy_size);
  1631. v->init_sec_buf_read_offset += copy_size;
  1632. ret = copy_size;
  1633. goto end;
  1634. }
  1635. /* check the v->cur_seg, if it is null, get current and double check if the new v->cur_seg*/
  1636. if (!v->cur_seg) {
  1637. v->cur_seg = get_current_fragment(v);
  1638. }
  1639. if (!v->cur_seg) {
  1640. ret = AVERROR_EOF;
  1641. goto end;
  1642. }
  1643. ret = read_from_url(v, v->cur_seg, buf, buf_size);
  1644. if (ret > 0)
  1645. goto end;
  1646. if (c->is_live || v->cur_seq_no < v->last_seq_no) {
  1647. if (!v->is_restart_needed)
  1648. v->cur_seq_no++;
  1649. v->is_restart_needed = 1;
  1650. }
  1651. end:
  1652. return ret;
  1653. }
  1654. static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
  1655. int flags, AVDictionary **opts)
  1656. {
  1657. av_log(s, AV_LOG_ERROR,
  1658. "A DASH playlist item '%s' referred to an external file '%s'. "
  1659. "Opening this file was forbidden for security reasons\n",
  1660. s->url, url);
  1661. return AVERROR(EPERM);
  1662. }
  1663. static void close_demux_for_component(struct representation *pls)
  1664. {
  1665. /* note: the internal buffer could have changed */
  1666. av_freep(&pls->pb.pub.buffer);
  1667. memset(&pls->pb, 0x00, sizeof(pls->pb));
  1668. pls->ctx->pb = NULL;
  1669. avformat_close_input(&pls->ctx);
  1670. }
  1671. static int reopen_demux_for_component(AVFormatContext *s, struct representation *pls)
  1672. {
  1673. DASHContext *c = s->priv_data;
  1674. const AVInputFormat *in_fmt = NULL;
  1675. AVDictionary *in_fmt_opts = NULL;
  1676. uint8_t *avio_ctx_buffer = NULL;
  1677. int ret = 0, i;
  1678. if (pls->ctx) {
  1679. close_demux_for_component(pls);
  1680. }
  1681. if (ff_check_interrupt(&s->interrupt_callback)) {
  1682. ret = AVERROR_EXIT;
  1683. goto fail;
  1684. }
  1685. if (!(pls->ctx = avformat_alloc_context())) {
  1686. ret = AVERROR(ENOMEM);
  1687. goto fail;
  1688. }
  1689. avio_ctx_buffer = av_malloc(INITIAL_BUFFER_SIZE);
  1690. if (!avio_ctx_buffer ) {
  1691. ret = AVERROR(ENOMEM);
  1692. avformat_free_context(pls->ctx);
  1693. pls->ctx = NULL;
  1694. goto fail;
  1695. }
  1696. ffio_init_context(&pls->pb, avio_ctx_buffer, INITIAL_BUFFER_SIZE, 0,
  1697. pls, read_data, NULL, c->is_live ? NULL : seek_data);
  1698. pls->pb.pub.seekable = 0;
  1699. if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
  1700. goto fail;
  1701. pls->ctx->flags = AVFMT_FLAG_CUSTOM_IO;
  1702. pls->ctx->probesize = s->probesize > 0 ? s->probesize : 1024 * 4;
  1703. pls->ctx->max_analyze_duration = s->max_analyze_duration > 0 ? s->max_analyze_duration : 4 * AV_TIME_BASE;
  1704. pls->ctx->interrupt_callback = s->interrupt_callback;
  1705. ret = av_probe_input_buffer(&pls->pb.pub, &in_fmt, "", NULL, 0, 0);
  1706. if (ret < 0) {
  1707. av_log(s, AV_LOG_ERROR, "Error when loading first fragment of playlist\n");
  1708. avformat_free_context(pls->ctx);
  1709. pls->ctx = NULL;
  1710. goto fail;
  1711. }
  1712. pls->ctx->pb = &pls->pb.pub;
  1713. pls->ctx->io_open = nested_io_open;
  1714. if (c->cenc_decryption_key)
  1715. av_dict_set(&in_fmt_opts, "decryption_key", c->cenc_decryption_key, 0);
  1716. // provide additional information from mpd if available
  1717. ret = avformat_open_input(&pls->ctx, "", in_fmt, &in_fmt_opts); //pls->init_section->url
  1718. av_dict_free(&in_fmt_opts);
  1719. if (ret < 0)
  1720. goto fail;
  1721. if (pls->n_fragments) {
  1722. #if FF_API_R_FRAME_RATE
  1723. if (pls->framerate.den) {
  1724. for (i = 0; i < pls->ctx->nb_streams; i++)
  1725. pls->ctx->streams[i]->r_frame_rate = pls->framerate;
  1726. }
  1727. #endif
  1728. ret = avformat_find_stream_info(pls->ctx, NULL);
  1729. if (ret < 0)
  1730. goto fail;
  1731. }
  1732. fail:
  1733. return ret;
  1734. }
  1735. static int open_demux_for_component(AVFormatContext *s, struct representation *pls)
  1736. {
  1737. int ret = 0;
  1738. int i;
  1739. pls->parent = s;
  1740. pls->cur_seq_no = calc_cur_seg_no(s, pls);
  1741. if (!pls->last_seq_no)
  1742. pls->last_seq_no = calc_max_seg_no(pls, s->priv_data);
  1743. ret = reopen_demux_for_component(s, pls);
  1744. if (ret < 0)
  1745. return ret;
  1746. for (i = 0; i < pls->ctx->nb_streams; i++) {
  1747. AVStream *st = avformat_new_stream(s, NULL);
  1748. AVStream *ist = pls->ctx->streams[i];
  1749. if (!st)
  1750. return AVERROR(ENOMEM);
  1751. st->id = i;
  1752. ret = avcodec_parameters_copy(st->codecpar, ist->codecpar);
  1753. if (ret < 0)
  1754. return ret;
  1755. avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
  1756. // copy disposition
  1757. st->disposition = ist->disposition;
  1758. }
  1759. return 0;
  1760. }
  1761. static int is_common_init_section_exist(struct representation **pls, int n_pls)
  1762. {
  1763. struct fragment *first_init_section = pls[0]->init_section;
  1764. char *url =NULL;
  1765. int64_t url_offset = -1;
  1766. int64_t size = -1;
  1767. int i = 0;
  1768. if (first_init_section == NULL || n_pls == 0)
  1769. return 0;
  1770. url = first_init_section->url;
  1771. url_offset = first_init_section->url_offset;
  1772. size = pls[0]->init_section->size;
  1773. for (i=0;i<n_pls;i++) {
  1774. if (!pls[i]->init_section)
  1775. continue;
  1776. if (av_strcasecmp(pls[i]->init_section->url, url) ||
  1777. pls[i]->init_section->url_offset != url_offset ||
  1778. pls[i]->init_section->size != size) {
  1779. return 0;
  1780. }
  1781. }
  1782. return 1;
  1783. }
  1784. static int copy_init_section(struct representation *rep_dest, struct representation *rep_src)
  1785. {
  1786. rep_dest->init_sec_buf = av_mallocz(rep_src->init_sec_buf_size);
  1787. if (!rep_dest->init_sec_buf) {
  1788. av_log(rep_dest->ctx, AV_LOG_WARNING, "Cannot alloc memory for init_sec_buf\n");
  1789. return AVERROR(ENOMEM);
  1790. }
  1791. memcpy(rep_dest->init_sec_buf, rep_src->init_sec_buf, rep_src->init_sec_data_len);
  1792. rep_dest->init_sec_buf_size = rep_src->init_sec_buf_size;
  1793. rep_dest->init_sec_data_len = rep_src->init_sec_data_len;
  1794. rep_dest->cur_timestamp = rep_src->cur_timestamp;
  1795. return 0;
  1796. }
  1797. static void move_metadata(AVStream *st, const char *key, char **value)
  1798. {
  1799. if (*value) {
  1800. av_dict_set(&st->metadata, key, *value, AV_DICT_DONT_STRDUP_VAL);
  1801. *value = NULL;
  1802. }
  1803. }
  1804. static int dash_read_header(AVFormatContext *s)
  1805. {
  1806. DASHContext *c = s->priv_data;
  1807. struct representation *rep;
  1808. AVProgram *program;
  1809. int ret = 0;
  1810. int stream_index = 0;
  1811. int i;
  1812. c->interrupt_callback = &s->interrupt_callback;
  1813. if ((ret = ffio_copy_url_options(s->pb, &c->avio_opts)) < 0)
  1814. return ret;
  1815. if ((ret = parse_manifest(s, s->url, s->pb)) < 0)
  1816. return ret;
  1817. /* If this isn't a live stream, fill the total duration of the
  1818. * stream. */
  1819. if (!c->is_live) {
  1820. s->duration = (int64_t) c->media_presentation_duration * AV_TIME_BASE;
  1821. } else {
  1822. av_dict_set(&c->avio_opts, "seekable", "0", 0);
  1823. }
  1824. if(c->n_videos)
  1825. c->is_init_section_common_video = is_common_init_section_exist(c->videos, c->n_videos);
  1826. /* Open the demuxer for video and audio components if available */
  1827. for (i = 0; i < c->n_videos; i++) {
  1828. rep = c->videos[i];
  1829. if (i > 0 && c->is_init_section_common_video) {
  1830. ret = copy_init_section(rep, c->videos[0]);
  1831. if (ret < 0)
  1832. return ret;
  1833. }
  1834. ret = open_demux_for_component(s, rep);
  1835. if (ret)
  1836. return ret;
  1837. rep->stream_index = stream_index;
  1838. ++stream_index;
  1839. }
  1840. if(c->n_audios)
  1841. c->is_init_section_common_audio = is_common_init_section_exist(c->audios, c->n_audios);
  1842. for (i = 0; i < c->n_audios; i++) {
  1843. rep = c->audios[i];
  1844. if (i > 0 && c->is_init_section_common_audio) {
  1845. ret = copy_init_section(rep, c->audios[0]);
  1846. if (ret < 0)
  1847. return ret;
  1848. }
  1849. ret = open_demux_for_component(s, rep);
  1850. if (ret)
  1851. return ret;
  1852. rep->stream_index = stream_index;
  1853. ++stream_index;
  1854. }
  1855. if (c->n_subtitles)
  1856. c->is_init_section_common_subtitle = is_common_init_section_exist(c->subtitles, c->n_subtitles);
  1857. for (i = 0; i < c->n_subtitles; i++) {
  1858. rep = c->subtitles[i];
  1859. if (i > 0 && c->is_init_section_common_subtitle) {
  1860. ret = copy_init_section(rep, c->subtitles[0]);
  1861. if (ret < 0)
  1862. return ret;
  1863. }
  1864. ret = open_demux_for_component(s, rep);
  1865. if (ret)
  1866. return ret;
  1867. rep->stream_index = stream_index;
  1868. ++stream_index;
  1869. }
  1870. if (!stream_index)
  1871. return AVERROR_INVALIDDATA;
  1872. /* Create a program */
  1873. program = av_new_program(s, 0);
  1874. if (!program)
  1875. return AVERROR(ENOMEM);
  1876. for (i = 0; i < c->n_videos; i++) {
  1877. rep = c->videos[i];
  1878. av_program_add_stream_index(s, 0, rep->stream_index);
  1879. rep->assoc_stream = s->streams[rep->stream_index];
  1880. if (rep->bandwidth > 0)
  1881. av_dict_set_int(&rep->assoc_stream->metadata, "variant_bitrate", rep->bandwidth, 0);
  1882. move_metadata(rep->assoc_stream, "id", &rep->id);
  1883. }
  1884. for (i = 0; i < c->n_audios; i++) {
  1885. rep = c->audios[i];
  1886. av_program_add_stream_index(s, 0, rep->stream_index);
  1887. rep->assoc_stream = s->streams[rep->stream_index];
  1888. if (rep->bandwidth > 0)
  1889. av_dict_set_int(&rep->assoc_stream->metadata, "variant_bitrate", rep->bandwidth, 0);
  1890. move_metadata(rep->assoc_stream, "id", &rep->id);
  1891. move_metadata(rep->assoc_stream, "language", &rep->lang);
  1892. }
  1893. for (i = 0; i < c->n_subtitles; i++) {
  1894. rep = c->subtitles[i];
  1895. av_program_add_stream_index(s, 0, rep->stream_index);
  1896. rep->assoc_stream = s->streams[rep->stream_index];
  1897. move_metadata(rep->assoc_stream, "id", &rep->id);
  1898. move_metadata(rep->assoc_stream, "language", &rep->lang);
  1899. }
  1900. return 0;
  1901. }
  1902. static void recheck_discard_flags(AVFormatContext *s, struct representation **p, int n)
  1903. {
  1904. int i, j;
  1905. for (i = 0; i < n; i++) {
  1906. struct representation *pls = p[i];
  1907. int needed = !pls->assoc_stream || pls->assoc_stream->discard < AVDISCARD_ALL;
  1908. if (needed && !pls->ctx) {
  1909. pls->cur_seg_offset = 0;
  1910. pls->init_sec_buf_read_offset = 0;
  1911. /* Catch up */
  1912. for (j = 0; j < n; j++) {
  1913. pls->cur_seq_no = FFMAX(pls->cur_seq_no, p[j]->cur_seq_no);
  1914. }
  1915. reopen_demux_for_component(s, pls);
  1916. av_log(s, AV_LOG_INFO, "Now receiving stream_index %d\n", pls->stream_index);
  1917. } else if (!needed && pls->ctx) {
  1918. close_demux_for_component(pls);
  1919. ff_format_io_close(pls->parent, &pls->input);
  1920. av_log(s, AV_LOG_INFO, "No longer receiving stream_index %d\n", pls->stream_index);
  1921. }
  1922. }
  1923. }
  1924. static int dash_read_packet(AVFormatContext *s, AVPacket *pkt)
  1925. {
  1926. DASHContext *c = s->priv_data;
  1927. int ret = 0, i;
  1928. int64_t mints = 0;
  1929. struct representation *cur = NULL;
  1930. struct representation *rep = NULL;
  1931. recheck_discard_flags(s, c->videos, c->n_videos);
  1932. recheck_discard_flags(s, c->audios, c->n_audios);
  1933. recheck_discard_flags(s, c->subtitles, c->n_subtitles);
  1934. for (i = 0; i < c->n_videos; i++) {
  1935. rep = c->videos[i];
  1936. if (!rep->ctx)
  1937. continue;
  1938. if (!cur || rep->cur_timestamp < mints) {
  1939. cur = rep;
  1940. mints = rep->cur_timestamp;
  1941. }
  1942. }
  1943. for (i = 0; i < c->n_audios; i++) {
  1944. rep = c->audios[i];
  1945. if (!rep->ctx)
  1946. continue;
  1947. if (!cur || rep->cur_timestamp < mints) {
  1948. cur = rep;
  1949. mints = rep->cur_timestamp;
  1950. }
  1951. }
  1952. for (i = 0; i < c->n_subtitles; i++) {
  1953. rep = c->subtitles[i];
  1954. if (!rep->ctx)
  1955. continue;
  1956. if (!cur || rep->cur_timestamp < mints) {
  1957. cur = rep;
  1958. mints = rep->cur_timestamp;
  1959. }
  1960. }
  1961. if (!cur) {
  1962. return AVERROR_INVALIDDATA;
  1963. }
  1964. while (!ff_check_interrupt(c->interrupt_callback) && !ret) {
  1965. ret = av_read_frame(cur->ctx, pkt);
  1966. if (ret >= 0) {
  1967. /* If we got a packet, return it */
  1968. cur->cur_timestamp = av_rescale(pkt->pts, (int64_t)cur->ctx->streams[0]->time_base.num * 90000, cur->ctx->streams[0]->time_base.den);
  1969. pkt->stream_index = cur->stream_index;
  1970. return 0;
  1971. }
  1972. if (cur->is_restart_needed) {
  1973. cur->cur_seg_offset = 0;
  1974. cur->init_sec_buf_read_offset = 0;
  1975. cur->is_restart_needed = 0;
  1976. ff_format_io_close(cur->parent, &cur->input);
  1977. ret = reopen_demux_for_component(s, cur);
  1978. }
  1979. }
  1980. return AVERROR_EOF;
  1981. }
  1982. static int dash_close(AVFormatContext *s)
  1983. {
  1984. DASHContext *c = s->priv_data;
  1985. free_audio_list(c);
  1986. free_video_list(c);
  1987. free_subtitle_list(c);
  1988. av_dict_free(&c->avio_opts);
  1989. av_freep(&c->base_url);
  1990. return 0;
  1991. }
  1992. static int dash_seek(AVFormatContext *s, struct representation *pls, int64_t seek_pos_msec, int flags, int dry_run)
  1993. {
  1994. int ret = 0;
  1995. int i = 0;
  1996. int j = 0;
  1997. int64_t duration = 0;
  1998. av_log(pls->parent, AV_LOG_VERBOSE, "DASH seek pos[%"PRId64"ms] %s\n",
  1999. seek_pos_msec, dry_run ? " (dry)" : "");
  2000. // single fragment mode
  2001. if (pls->n_fragments == 1) {
  2002. pls->cur_timestamp = 0;
  2003. pls->cur_seg_offset = 0;
  2004. if (dry_run)
  2005. return 0;
  2006. ff_read_frame_flush(pls->ctx);
  2007. return av_seek_frame(pls->ctx, -1, seek_pos_msec * 1000, flags);
  2008. }
  2009. ff_format_io_close(pls->parent, &pls->input);
  2010. // find the nearest fragment
  2011. if (pls->n_timelines > 0 && pls->fragment_timescale > 0) {
  2012. int64_t num = pls->first_seq_no;
  2013. av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline start n_timelines[%d] "
  2014. "last_seq_no[%"PRId64"].\n",
  2015. (int)pls->n_timelines, (int64_t)pls->last_seq_no);
  2016. for (i = 0; i < pls->n_timelines; i++) {
  2017. if (pls->timelines[i]->starttime > 0) {
  2018. duration = pls->timelines[i]->starttime;
  2019. }
  2020. duration += pls->timelines[i]->duration;
  2021. if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
  2022. goto set_seq_num;
  2023. }
  2024. for (j = 0; j < pls->timelines[i]->repeat; j++) {
  2025. duration += pls->timelines[i]->duration;
  2026. num++;
  2027. if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
  2028. goto set_seq_num;
  2029. }
  2030. }
  2031. num++;
  2032. }
  2033. set_seq_num:
  2034. pls->cur_seq_no = num > pls->last_seq_no ? pls->last_seq_no : num;
  2035. av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline end cur_seq_no[%"PRId64"].\n",
  2036. (int64_t)pls->cur_seq_no);
  2037. } else if (pls->fragment_duration > 0) {
  2038. pls->cur_seq_no = pls->first_seq_no + ((seek_pos_msec * pls->fragment_timescale) / pls->fragment_duration) / 1000;
  2039. } else {
  2040. av_log(pls->parent, AV_LOG_ERROR, "dash_seek missing timeline or fragment_duration\n");
  2041. pls->cur_seq_no = pls->first_seq_no;
  2042. }
  2043. pls->cur_timestamp = 0;
  2044. pls->cur_seg_offset = 0;
  2045. pls->init_sec_buf_read_offset = 0;
  2046. ret = dry_run ? 0 : reopen_demux_for_component(s, pls);
  2047. return ret;
  2048. }
  2049. static int dash_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  2050. {
  2051. int ret = 0, i;
  2052. DASHContext *c = s->priv_data;
  2053. int64_t seek_pos_msec = av_rescale_rnd(timestamp, 1000,
  2054. s->streams[stream_index]->time_base.den,
  2055. flags & AVSEEK_FLAG_BACKWARD ?
  2056. AV_ROUND_DOWN : AV_ROUND_UP);
  2057. if ((flags & AVSEEK_FLAG_BYTE) || c->is_live)
  2058. return AVERROR(ENOSYS);
  2059. /* Seek in discarded streams with dry_run=1 to avoid reopening them */
  2060. for (i = 0; i < c->n_videos; i++) {
  2061. if (!ret)
  2062. ret = dash_seek(s, c->videos[i], seek_pos_msec, flags, !c->videos[i]->ctx);
  2063. }
  2064. for (i = 0; i < c->n_audios; i++) {
  2065. if (!ret)
  2066. ret = dash_seek(s, c->audios[i], seek_pos_msec, flags, !c->audios[i]->ctx);
  2067. }
  2068. for (i = 0; i < c->n_subtitles; i++) {
  2069. if (!ret)
  2070. ret = dash_seek(s, c->subtitles[i], seek_pos_msec, flags, !c->subtitles[i]->ctx);
  2071. }
  2072. return ret;
  2073. }
  2074. static int dash_probe(const AVProbeData *p)
  2075. {
  2076. if (!av_stristr(p->buf, "<MPD"))
  2077. return 0;
  2078. if (av_stristr(p->buf, "dash:profile:isoff-on-demand:2011") ||
  2079. av_stristr(p->buf, "dash:profile:isoff-live:2011") ||
  2080. av_stristr(p->buf, "dash:profile:isoff-live:2012") ||
  2081. av_stristr(p->buf, "dash:profile:isoff-main:2011") ||
  2082. av_stristr(p->buf, "3GPP:PSS:profile:DASH1")) {
  2083. return AVPROBE_SCORE_MAX;
  2084. }
  2085. if (av_stristr(p->buf, "dash:profile")) {
  2086. return AVPROBE_SCORE_MAX;
  2087. }
  2088. return 0;
  2089. }
  2090. #define OFFSET(x) offsetof(DASHContext, x)
  2091. #define FLAGS AV_OPT_FLAG_DECODING_PARAM
  2092. static const AVOption dash_options[] = {
  2093. {"allowed_extensions", "List of file extensions that dash is allowed to access",
  2094. OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
  2095. {.str = "aac,m4a,m4s,m4v,mov,mp4,webm,ts"},
  2096. INT_MIN, INT_MAX, FLAGS},
  2097. { "cenc_decryption_key", "Media decryption key (hex)", OFFSET(cenc_decryption_key), AV_OPT_TYPE_STRING, {.str = NULL}, INT_MIN, INT_MAX, .flags = FLAGS },
  2098. {NULL}
  2099. };
  2100. static const AVClass dash_class = {
  2101. .class_name = "dash",
  2102. .item_name = av_default_item_name,
  2103. .option = dash_options,
  2104. .version = LIBAVUTIL_VERSION_INT,
  2105. };
  2106. const FFInputFormat ff_dash_demuxer = {
  2107. .p.name = "dash",
  2108. .p.long_name = NULL_IF_CONFIG_SMALL("Dynamic Adaptive Streaming over HTTP"),
  2109. .p.priv_class = &dash_class,
  2110. .p.flags = AVFMT_NO_BYTE_SEEK,
  2111. .priv_data_size = sizeof(DASHContext),
  2112. .flags_internal = FF_INFMT_FLAG_INIT_CLEANUP,
  2113. .read_probe = dash_probe,
  2114. .read_header = dash_read_header,
  2115. .read_packet = dash_read_packet,
  2116. .read_close = dash_close,
  2117. .read_seek = dash_read_seek,
  2118. };