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