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