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