]> git.sesse.net Git - ffmpeg/blob - libavformat/dashdec.c
Merge commit 'fbf77b5ac37bf2a807d8336450801d7aecf2e359'
[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
88     int n_fragments;
89     struct fragment **fragments; /* VOD list of fragment for profile */
90
91     int n_timelines;
92     struct timeline **timelines;
93
94     int64_t first_seq_no;
95     int64_t last_seq_no;
96     int64_t start_number; /* used in case when we have dynamic list of segment to know which segments are new one*/
97
98     int64_t fragment_duration;
99     int64_t fragment_timescale;
100
101     int64_t presentation_timeoffset;
102
103     int64_t cur_seq_no;
104     int64_t cur_seg_offset;
105     int64_t cur_seg_size;
106     struct fragment *cur_seg;
107
108     /* Currently active Media Initialization Section */
109     struct fragment *init_section;
110     uint8_t *init_sec_buf;
111     uint32_t init_sec_buf_size;
112     uint32_t init_sec_data_len;
113     uint32_t init_sec_buf_read_offset;
114     int64_t cur_timestamp;
115     int is_restart_needed;
116 };
117
118 typedef struct DASHContext {
119     const AVClass *class;
120     char *base_url;
121     struct representation *cur_video;
122     struct representation *cur_audio;
123
124     /* MediaPresentationDescription Attribute */
125     uint64_t media_presentation_duration;
126     uint64_t suggested_presentation_delay;
127     uint64_t availability_start_time;
128     uint64_t publish_time;
129     uint64_t minimum_update_period;
130     uint64_t time_shift_buffer_depth;
131     uint64_t min_buffer_time;
132
133     /* Period Attribute */
134     uint64_t period_duration;
135     uint64_t period_start;
136
137     int is_live;
138     AVIOInterruptCB *interrupt_callback;
139     char *user_agent;                    ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
140     char *cookies;                       ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
141     char *headers;                       ///< holds HTTP headers set as an AVOption to the HTTP protocol context
142     char *allowed_extensions;
143     AVDictionary *avio_opts;
144 } DASHContext;
145
146 static uint64_t get_current_time_in_sec(void)
147 {
148     return  av_gettime() / 1000000;
149 }
150
151 static uint64_t get_utc_date_time_insec(AVFormatContext *s, const char *datetime)
152 {
153     struct tm timeinfo;
154     int year = 0;
155     int month = 0;
156     int day = 0;
157     int hour = 0;
158     int minute = 0;
159     int ret = 0;
160     float second = 0.0;
161
162     /* ISO-8601 date parser */
163     if (!datetime)
164         return 0;
165
166     ret = sscanf(datetime, "%d-%d-%dT%d:%d:%fZ", &year, &month, &day, &hour, &minute, &second);
167     /* year, month, day, hour, minute, second  6 arguments */
168     if (ret != 6) {
169         av_log(s, AV_LOG_WARNING, "get_utc_date_time_insec get a wrong time format\n");
170     }
171     timeinfo.tm_year = year - 1900;
172     timeinfo.tm_mon  = month - 1;
173     timeinfo.tm_mday = day;
174     timeinfo.tm_hour = hour;
175     timeinfo.tm_min  = minute;
176     timeinfo.tm_sec  = (int)second;
177
178     return av_timegm(&timeinfo);
179 }
180
181 static uint32_t get_duration_insec(AVFormatContext *s, const char *duration)
182 {
183     /* ISO-8601 duration parser */
184     uint32_t days = 0;
185     uint32_t hours = 0;
186     uint32_t mins = 0;
187     uint32_t secs = 0;
188     int size = 0;
189     float value = 0;
190     char type = '\0';
191     const char *ptr = duration;
192
193     while (*ptr) {
194         if (*ptr == 'P' || *ptr == 'T') {
195             ptr++;
196             continue;
197         }
198
199         if (sscanf(ptr, "%f%c%n", &value, &type, &size) != 2) {
200             av_log(s, AV_LOG_WARNING, "get_duration_insec get a wrong time format\n");
201             return 0; /* parser error */
202         }
203         switch (type) {
204             case 'D':
205                 days = (uint32_t)value;
206                 break;
207             case 'H':
208                 hours = (uint32_t)value;
209                 break;
210             case 'M':
211                 mins = (uint32_t)value;
212                 break;
213             case 'S':
214                 secs = (uint32_t)value;
215                 break;
216             default:
217                 // handle invalid type
218                 break;
219         }
220         ptr += size;
221     }
222     return  ((days * 24 + hours) * 60 + mins) * 60 + secs;
223 }
224
225 static int64_t get_segment_start_time_based_on_timeline(struct representation *pls, int64_t cur_seq_no)
226 {
227     int64_t start_time = 0;
228     int64_t i = 0;
229     int64_t j = 0;
230     int64_t num = 0;
231
232     if (pls->n_timelines) {
233         for (i = 0; i < pls->n_timelines; i++) {
234             if (pls->timelines[i]->starttime > 0) {
235                 start_time = pls->timelines[i]->starttime;
236             }
237             if (num == cur_seq_no)
238                 goto finish;
239
240             start_time += pls->timelines[i]->duration;
241             for (j = 0; j < pls->timelines[i]->repeat; j++) {
242                 num++;
243                 if (num == cur_seq_no)
244                     goto finish;
245                 start_time += pls->timelines[i]->duration;
246             }
247             num++;
248         }
249     }
250 finish:
251     return start_time;
252 }
253
254 static int64_t calc_next_seg_no_from_timelines(struct representation *pls, int64_t cur_time)
255 {
256     int64_t i = 0;
257     int64_t j = 0;
258     int64_t num = 0;
259     int64_t start_time = 0;
260
261     for (i = 0; i < pls->n_timelines; i++) {
262         if (pls->timelines[i]->starttime > 0) {
263             start_time = pls->timelines[i]->starttime;
264         }
265         if (start_time > cur_time)
266             goto finish;
267
268         start_time += pls->timelines[i]->duration;
269         for (j = 0; j < pls->timelines[i]->repeat; j++) {
270             num++;
271             if (start_time > cur_time)
272                 goto finish;
273             start_time += pls->timelines[i]->duration;
274         }
275         num++;
276     }
277
278     return -1;
279
280 finish:
281     return num;
282 }
283
284 static void free_fragment(struct fragment **seg)
285 {
286     if (!(*seg)) {
287         return;
288     }
289     av_freep(&(*seg)->url);
290     av_freep(seg);
291 }
292
293 static void free_fragment_list(struct representation *pls)
294 {
295     int i;
296
297     for (i = 0; i < pls->n_fragments; i++) {
298         free_fragment(&pls->fragments[i]);
299     }
300     av_freep(&pls->fragments);
301     pls->n_fragments = 0;
302 }
303
304 static void free_timelines_list(struct representation *pls)
305 {
306     int i;
307
308     for (i = 0; i < pls->n_timelines; i++) {
309         av_freep(&pls->timelines[i]);
310     }
311     av_freep(&pls->timelines);
312     pls->n_timelines = 0;
313 }
314
315 static void free_representation(struct representation *pls)
316 {
317     free_fragment_list(pls);
318     free_timelines_list(pls);
319     free_fragment(&pls->cur_seg);
320     free_fragment(&pls->init_section);
321     av_freep(&pls->init_sec_buf);
322     av_freep(&pls->pb.buffer);
323     if (pls->input)
324         ff_format_io_close(pls->parent, &pls->input);
325     if (pls->ctx) {
326         pls->ctx->pb = NULL;
327         avformat_close_input(&pls->ctx);
328     }
329
330     av_freep(&pls->url_template);
331     av_freep(&pls);
332 }
333
334 static void set_httpheader_options(DASHContext *c, AVDictionary **opts)
335 {
336     // broker prior HTTP options that should be consistent across requests
337     av_dict_set(opts, "user-agent", c->user_agent, 0);
338     av_dict_set(opts, "cookies", c->cookies, 0);
339     av_dict_set(opts, "headers", c->headers, 0);
340     if (c->is_live) {
341         av_dict_set(opts, "seekable", "0", 0);
342     }
343 }
344 static void update_options(char **dest, const char *name, void *src)
345 {
346     av_freep(dest);
347     av_opt_get(src, name, AV_OPT_SEARCH_CHILDREN, (uint8_t**)dest);
348     if (*dest)
349         av_freep(dest);
350 }
351
352 static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
353                     AVDictionary *opts, AVDictionary *opts2, int *is_http)
354 {
355     DASHContext *c = s->priv_data;
356     AVDictionary *tmp = NULL;
357     const char *proto_name = NULL;
358     int ret;
359
360     av_dict_copy(&tmp, opts, 0);
361     av_dict_copy(&tmp, opts2, 0);
362
363     if (av_strstart(url, "crypto", NULL)) {
364         if (url[6] == '+' || url[6] == ':')
365             proto_name = avio_find_protocol_name(url + 7);
366     }
367
368     if (!proto_name)
369         proto_name = avio_find_protocol_name(url);
370
371     if (!proto_name)
372         return AVERROR_INVALIDDATA;
373
374     // only http(s) & file are allowed
375     if (av_strstart(proto_name, "file", NULL)) {
376         if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
377             av_log(s, AV_LOG_ERROR,
378                 "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
379                 "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
380                 url);
381             return AVERROR_INVALIDDATA;
382         }
383     } else if (av_strstart(proto_name, "http", NULL)) {
384         ;
385     } else
386         return AVERROR_INVALIDDATA;
387
388     if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
389         ;
390     else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
391         ;
392     else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
393         return AVERROR_INVALIDDATA;
394
395     ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);
396     if (ret >= 0) {
397         // update cookies on http response with setcookies.
398         char *new_cookies = NULL;
399
400         if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
401             av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
402
403         if (new_cookies) {
404             av_free(c->cookies);
405             c->cookies = new_cookies;
406         }
407
408         av_dict_set(&opts, "cookies", c->cookies, 0);
409     }
410
411     av_dict_free(&tmp);
412
413     if (is_http)
414         *is_http = av_strstart(proto_name, "http", NULL);
415
416     return ret;
417 }
418
419 static char *get_content_url(xmlNodePtr *baseurl_nodes,
420                              int n_baseurl_nodes,
421                              char *rep_id_val,
422                              char *rep_bandwidth_val,
423                              char *val)
424 {
425     int i;
426     char *text;
427     char *url = NULL;
428     char tmp_str[MAX_URL_SIZE];
429     char tmp_str_2[MAX_URL_SIZE];
430
431     memset(tmp_str, 0, sizeof(tmp_str));
432
433     for (i = 0; i < n_baseurl_nodes; ++i) {
434         if (baseurl_nodes[i] &&
435             baseurl_nodes[i]->children &&
436             baseurl_nodes[i]->children->type == XML_TEXT_NODE) {
437             text = xmlNodeGetContent(baseurl_nodes[i]->children);
438             if (text) {
439                 memset(tmp_str, 0, sizeof(tmp_str));
440                 memset(tmp_str_2, 0, sizeof(tmp_str_2));
441                 ff_make_absolute_url(tmp_str_2, MAX_URL_SIZE, tmp_str, text);
442                 av_strlcpy(tmp_str, tmp_str_2, sizeof(tmp_str));
443                 xmlFree(text);
444             }
445         }
446     }
447
448     if (val)
449         av_strlcat(tmp_str, (const char*)val, sizeof(tmp_str));
450
451     if (rep_id_val) {
452         url = av_strireplace(tmp_str, "$RepresentationID$", (const char*)rep_id_val);
453         if (!url) {
454             return NULL;
455         }
456         av_strlcpy(tmp_str, url, sizeof(tmp_str));
457         av_free(url);
458     }
459     if (rep_bandwidth_val && tmp_str[0] != '\0') {
460         url = av_strireplace(tmp_str, "$Bandwidth$", (const char*)rep_bandwidth_val);
461         if (!url) {
462             return NULL;
463         }
464     }
465     return url;
466 }
467
468 static char *get_val_from_nodes_tab(xmlNodePtr *nodes, const int n_nodes, const char *attrname)
469 {
470     int i;
471     char *val;
472
473     for (i = 0; i < n_nodes; ++i) {
474         if (nodes[i]) {
475             val = xmlGetProp(nodes[i], attrname);
476             if (val)
477                 return val;
478         }
479     }
480
481     return NULL;
482 }
483
484 static xmlNodePtr find_child_node_by_name(xmlNodePtr rootnode, const char *nodename)
485 {
486     xmlNodePtr node = rootnode;
487     if (!node) {
488         return NULL;
489     }
490
491     node = xmlFirstElementChild(node);
492     while (node) {
493         if (!av_strcasecmp(node->name, nodename)) {
494             return node;
495         }
496         node = xmlNextElementSibling(node);
497     }
498     return NULL;
499 }
500
501 static enum AVMediaType get_content_type(xmlNodePtr node)
502 {
503     enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
504     int i = 0;
505     const char *attr;
506     char *val = NULL;
507
508     if (node) {
509         for (i = 0; i < 2; i++) {
510             attr = i ? "mimeType" : "contentType";
511             val = xmlGetProp(node, attr);
512             if (val) {
513                 if (av_stristr((const char *)val, "video")) {
514                     type = AVMEDIA_TYPE_VIDEO;
515                 } else if (av_stristr((const char *)val, "audio")) {
516                     type = AVMEDIA_TYPE_AUDIO;
517                 }
518                 xmlFree(val);
519             }
520         }
521     }
522     return type;
523 }
524
525 static int parse_manifest_segmenturlnode(AVFormatContext *s, struct representation *rep,
526                                          xmlNodePtr fragmenturl_node,
527                                          xmlNodePtr *baseurl_nodes,
528                                          char *rep_id_val,
529                                          char *rep_bandwidth_val)
530 {
531     char *initialization_val = NULL;
532     char *media_val = NULL;
533
534     if (!av_strcasecmp(fragmenturl_node->name, (const char *)"Initialization")) {
535         initialization_val = xmlGetProp(fragmenturl_node, "sourceURL");
536         if (initialization_val) {
537             rep->init_section = av_mallocz(sizeof(struct fragment));
538             if (!rep->init_section) {
539                 xmlFree(initialization_val);
540                 return AVERROR(ENOMEM);
541             }
542             rep->init_section->url = get_content_url(baseurl_nodes, 4,
543                                                      rep_id_val,
544                                                      rep_bandwidth_val,
545                                                      initialization_val);
546             if (!rep->init_section->url) {
547                 av_free(rep->init_section);
548                 xmlFree(initialization_val);
549                 return AVERROR(ENOMEM);
550             }
551             rep->init_section->size = -1;
552             xmlFree(initialization_val);
553         }
554     } else if (!av_strcasecmp(fragmenturl_node->name, (const char *)"SegmentURL")) {
555         media_val = xmlGetProp(fragmenturl_node, "media");
556         if (media_val) {
557             struct fragment *seg = av_mallocz(sizeof(struct fragment));
558             if (!seg) {
559                 xmlFree(media_val);
560                 return AVERROR(ENOMEM);
561             }
562             seg->url = get_content_url(baseurl_nodes, 4,
563                                        rep_id_val,
564                                        rep_bandwidth_val,
565                                        media_val);
566             if (!seg->url) {
567                 av_free(seg);
568                 xmlFree(media_val);
569                 return AVERROR(ENOMEM);
570             }
571             seg->size = -1;
572             dynarray_add(&rep->fragments, &rep->n_fragments, seg);
573             xmlFree(media_val);
574         }
575     }
576
577     return 0;
578 }
579
580 static int parse_manifest_segmenttimeline(AVFormatContext *s, struct representation *rep,
581                                           xmlNodePtr fragment_timeline_node)
582 {
583     xmlAttrPtr attr = NULL;
584     char *val  = NULL;
585
586     if (!av_strcasecmp(fragment_timeline_node->name, (const char *)"S")) {
587         struct timeline *tml = av_mallocz(sizeof(struct timeline));
588         if (!tml) {
589             return AVERROR(ENOMEM);
590         }
591         attr = fragment_timeline_node->properties;
592         while (attr) {
593             val = xmlGetProp(fragment_timeline_node, attr->name);
594
595             if (!val) {
596                 av_log(s, AV_LOG_WARNING, "parse_manifest_segmenttimeline attr->name = %s val is NULL\n", attr->name);
597                 continue;
598             }
599
600             if (!av_strcasecmp(attr->name, (const char *)"t")) {
601                 tml->starttime = (int64_t)strtoll(val, NULL, 10);
602             } else if (!av_strcasecmp(attr->name, (const char *)"r")) {
603                 tml->repeat =(int64_t) strtoll(val, NULL, 10);
604             } else if (!av_strcasecmp(attr->name, (const char *)"d")) {
605                 tml->duration = (int64_t)strtoll(val, NULL, 10);
606             }
607             attr = attr->next;
608             xmlFree(val);
609         }
610         dynarray_add(&rep->timelines, &rep->n_timelines, tml);
611     }
612
613     return 0;
614 }
615
616 static int parse_manifest_representation(AVFormatContext *s, const char *url,
617                                          xmlNodePtr node,
618                                          xmlNodePtr adaptionset_node,
619                                          xmlNodePtr mpd_baseurl_node,
620                                          xmlNodePtr period_baseurl_node,
621                                          xmlNodePtr fragment_template_node,
622                                          xmlNodePtr content_component_node,
623                                          xmlNodePtr adaptionset_baseurl_node)
624 {
625     int32_t ret = 0;
626     int32_t audio_rep_idx = 0;
627     int32_t video_rep_idx = 0;
628     DASHContext *c = s->priv_data;
629     struct representation *rep = NULL;
630     struct fragment *seg = NULL;
631     xmlNodePtr representation_segmenttemplate_node = NULL;
632     xmlNodePtr representation_baseurl_node = NULL;
633     xmlNodePtr representation_segmentlist_node = NULL;
634     xmlNodePtr fragment_timeline_node = NULL;
635     xmlNodePtr fragment_templates_tab[2];
636     char *duration_val = NULL;
637     char *presentation_timeoffset_val = NULL;
638     char *startnumber_val = NULL;
639     char *timescale_val = NULL;
640     char *initialization_val = NULL;
641     char *media_val = NULL;
642     xmlNodePtr baseurl_nodes[4];
643     xmlNodePtr representation_node = node;
644     char *rep_id_val = xmlGetProp(representation_node, "id");
645     char *rep_bandwidth_val = xmlGetProp(representation_node, "bandwidth");
646     enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
647
648     // try get information from representation
649     if (type == AVMEDIA_TYPE_UNKNOWN)
650         type = get_content_type(representation_node);
651     // try get information from contentComponen
652     if (type == AVMEDIA_TYPE_UNKNOWN)
653         type = get_content_type(content_component_node);
654     // try get information from adaption set
655     if (type == AVMEDIA_TYPE_UNKNOWN)
656         type = get_content_type(adaptionset_node);
657     if (type == AVMEDIA_TYPE_UNKNOWN) {
658         av_log(s, AV_LOG_VERBOSE, "Parsing '%s' - skipp not supported representation type\n", url);
659     } else if ((type == AVMEDIA_TYPE_VIDEO && !c->cur_video) || (type == AVMEDIA_TYPE_AUDIO && !c->cur_audio)) {
660         // convert selected representation to our internal struct
661         rep = av_mallocz(sizeof(struct representation));
662         if (!rep) {
663             ret = AVERROR(ENOMEM);
664             goto end;
665         }
666         representation_segmenttemplate_node = find_child_node_by_name(representation_node, "SegmentTemplate");
667         representation_baseurl_node = find_child_node_by_name(representation_node, "BaseURL");
668         representation_segmentlist_node = find_child_node_by_name(representation_node, "SegmentList");
669
670         baseurl_nodes[0] = mpd_baseurl_node;
671         baseurl_nodes[1] = period_baseurl_node;
672         baseurl_nodes[2] = adaptionset_baseurl_node;
673         baseurl_nodes[3] = representation_baseurl_node;
674
675         if (representation_segmenttemplate_node || fragment_template_node) {
676             fragment_timeline_node = NULL;
677             fragment_templates_tab[0] = representation_segmenttemplate_node;
678             fragment_templates_tab[1] = fragment_template_node;
679
680             presentation_timeoffset_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "presentationTimeOffset");
681             duration_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "duration");
682             startnumber_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "startNumber");
683             timescale_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "timescale");
684             initialization_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "initialization");
685             media_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "media");
686
687             if (initialization_val) {
688                 rep->init_section = av_mallocz(sizeof(struct fragment));
689                 if (!rep->init_section) {
690                     av_free(rep);
691                     ret = AVERROR(ENOMEM);
692                     goto end;
693                 }
694                 rep->init_section->url = get_content_url(baseurl_nodes, 4, rep_id_val, rep_bandwidth_val, initialization_val);
695                 if (!rep->init_section->url) {
696                     av_free(rep->init_section);
697                     av_free(rep);
698                     ret = AVERROR(ENOMEM);
699                     goto end;
700                 }
701                 rep->init_section->size = -1;
702                 xmlFree(initialization_val);
703             }
704
705             if (media_val) {
706                 rep->url_template = get_content_url(baseurl_nodes, 4, rep_id_val, rep_bandwidth_val, media_val);
707                 xmlFree(media_val);
708             }
709
710             if (presentation_timeoffset_val) {
711                 rep->presentation_timeoffset = (int64_t) strtoll(presentation_timeoffset_val, NULL, 10);
712                 xmlFree(presentation_timeoffset_val);
713             }
714             if (duration_val) {
715                 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
716                 xmlFree(duration_val);
717             }
718             if (timescale_val) {
719                 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
720                 xmlFree(timescale_val);
721             }
722             if (startnumber_val) {
723                 rep->first_seq_no = (int64_t) strtoll(startnumber_val, NULL, 10);
724                 xmlFree(startnumber_val);
725             }
726
727             fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
728
729             if (!fragment_timeline_node)
730                 fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
731             if (fragment_timeline_node) {
732                 fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
733                 while (fragment_timeline_node) {
734                     ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
735                     if (ret < 0) {
736                         return ret;
737                     }
738                     fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
739                 }
740             }
741         } else if (representation_baseurl_node && !representation_segmentlist_node) {
742             seg = av_mallocz(sizeof(struct fragment));
743             if (!seg) {
744                 ret = AVERROR(ENOMEM);
745                 goto end;
746             }
747             seg->url = get_content_url(baseurl_nodes, 4, rep_id_val, rep_bandwidth_val, NULL);
748             if (!seg->url) {
749                 av_free(seg);
750                 ret = AVERROR(ENOMEM);
751                 goto end;
752             }
753             seg->size = -1;
754             dynarray_add(&rep->fragments, &rep->n_fragments, seg);
755         } else if (representation_segmentlist_node) {
756             // TODO: https://www.brendanlong.com/the-structure-of-an-mpeg-dash-mpd.html
757             // http://www-itec.uni-klu.ac.at/dash/ddash/mpdGenerator.php?fragmentlength=15&type=full
758             xmlNodePtr fragmenturl_node = NULL;
759             duration_val = xmlGetProp(representation_segmentlist_node, "duration");
760             timescale_val = xmlGetProp(representation_segmentlist_node, "timescale");
761             if (duration_val) {
762                 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
763                 xmlFree(duration_val);
764             }
765             if (timescale_val) {
766                 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
767                 xmlFree(timescale_val);
768             }
769             fragmenturl_node = xmlFirstElementChild(representation_segmentlist_node);
770             while (fragmenturl_node) {
771                 ret = parse_manifest_segmenturlnode(s, rep, fragmenturl_node,
772                                                     baseurl_nodes,
773                                                     rep_id_val,
774                                                     rep_bandwidth_val);
775                 if (ret < 0) {
776                     return ret;
777                 }
778                 fragmenturl_node = xmlNextElementSibling(fragmenturl_node);
779             }
780
781             fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
782
783             if (!fragment_timeline_node)
784                 fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
785             if (fragment_timeline_node) {
786                 fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
787                 while (fragment_timeline_node) {
788                     ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
789                     if (ret < 0) {
790                         return ret;
791                     }
792                     fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
793                 }
794             }
795         } else {
796             free_representation(rep);
797             rep = NULL;
798             av_log(s, AV_LOG_ERROR, "Unknown format of Representation node id[%s] \n", (const char *)rep_id_val);
799         }
800
801         if (rep) {
802             if (rep->fragment_duration > 0 && !rep->fragment_timescale)
803                 rep->fragment_timescale = 1;
804             if (type == AVMEDIA_TYPE_VIDEO) {
805                 rep->rep_idx = video_rep_idx;
806                 c->cur_video = rep;
807             } else {
808                 rep->rep_idx = audio_rep_idx;
809                 c->cur_audio = rep;
810             }
811         }
812     }
813
814     video_rep_idx += type == AVMEDIA_TYPE_VIDEO;
815     audio_rep_idx += type == AVMEDIA_TYPE_AUDIO;
816
817 end:
818     if (rep_id_val)
819         xmlFree(rep_id_val);
820     if (rep_bandwidth_val)
821         xmlFree(rep_bandwidth_val);
822
823     return ret;
824 }
825
826 static int parse_manifest_adaptationset(AVFormatContext *s, const char *url,
827                                         xmlNodePtr adaptionset_node,
828                                         xmlNodePtr mpd_baseurl_node,
829                                         xmlNodePtr period_baseurl_node)
830 {
831     int ret = 0;
832     xmlNodePtr fragment_template_node = NULL;
833     xmlNodePtr content_component_node = NULL;
834     xmlNodePtr adaptionset_baseurl_node = NULL;
835     xmlNodePtr node = NULL;
836
837     node = xmlFirstElementChild(adaptionset_node);
838     while (node) {
839         if (!av_strcasecmp(node->name, (const char *)"SegmentTemplate")) {
840             fragment_template_node = node;
841         } else if (!av_strcasecmp(node->name, (const char *)"ContentComponent")) {
842             content_component_node = node;
843         } else if (!av_strcasecmp(node->name, (const char *)"BaseURL")) {
844             adaptionset_baseurl_node = node;
845         } else if (!av_strcasecmp(node->name, (const char *)"Representation")) {
846             ret = parse_manifest_representation(s, url, node,
847                                                 adaptionset_node,
848                                                 mpd_baseurl_node,
849                                                 period_baseurl_node,
850                                                 fragment_template_node,
851                                                 content_component_node,
852                                                 adaptionset_baseurl_node);
853             if (ret < 0) {
854                 return ret;
855             }
856         }
857         node = xmlNextElementSibling(node);
858     }
859     return 0;
860 }
861
862 static int parse_manifest(AVFormatContext *s, const char *url, AVIOContext *in)
863 {
864     DASHContext *c = s->priv_data;
865     int ret = 0;
866     int close_in = 0;
867     uint8_t *new_url = NULL;
868     int64_t filesize = 0;
869     char *buffer = NULL;
870     AVDictionary *opts = NULL;
871     xmlDoc *doc = NULL;
872     xmlNodePtr root_element = NULL;
873     xmlNodePtr node = NULL;
874     xmlNodePtr period_node = NULL;
875     xmlNodePtr mpd_baseurl_node = NULL;
876     xmlNodePtr period_baseurl_node = NULL;
877     xmlNodePtr adaptionset_node = NULL;
878     xmlAttrPtr attr = NULL;
879     char *val  = NULL;
880     uint32_t perdiod_duration_sec = 0;
881     uint32_t perdiod_start_sec = 0;
882     int32_t audio_rep_idx = 0;
883     int32_t video_rep_idx = 0;
884
885     if (!in) {
886         close_in = 1;
887
888         set_httpheader_options(c, &opts);
889         ret = avio_open2(&in, url, AVIO_FLAG_READ, c->interrupt_callback, &opts);
890         av_dict_free(&opts);
891         if (ret < 0)
892             return ret;
893     }
894
895     if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0) {
896         c->base_url = av_strdup(new_url);
897     } else {
898         c->base_url = av_strdup(url);
899     }
900
901     filesize = avio_size(in);
902     if (filesize <= 0) {
903         filesize = 8 * 1024;
904     }
905
906     buffer = av_mallocz(filesize);
907     if (!buffer) {
908         av_free(c->base_url);
909         return AVERROR(ENOMEM);
910     }
911
912     filesize = avio_read(in, buffer, filesize);
913     if (filesize <= 0) {
914         av_log(s, AV_LOG_ERROR, "Unable to read to offset '%s'\n", url);
915         ret = AVERROR_INVALIDDATA;
916     } else {
917         LIBXML_TEST_VERSION
918
919         doc = xmlReadMemory(buffer, filesize, c->base_url, NULL, 0);
920         root_element = xmlDocGetRootElement(doc);
921         node = root_element;
922
923         if (!node) {
924             ret = AVERROR_INVALIDDATA;
925             av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing root node\n", url);
926             goto cleanup;
927         }
928
929         if (node->type != XML_ELEMENT_NODE ||
930             av_strcasecmp(node->name, (const char *)"MPD")) {
931             ret = AVERROR_INVALIDDATA;
932             av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - wrong root node name[%s] type[%d]\n", url, node->name, (int)node->type);
933             goto cleanup;
934         }
935
936         val = xmlGetProp(node, "type");
937         if (!val) {
938             av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing type attrib\n", url);
939             ret = AVERROR_INVALIDDATA;
940             goto cleanup;
941         }
942         if (!av_strcasecmp(val, (const char *)"dynamic"))
943             c->is_live = 1;
944         xmlFree(val);
945
946         attr = node->properties;
947         while (attr) {
948             val = xmlGetProp(node, attr->name);
949
950             if (!av_strcasecmp(attr->name, (const char *)"availabilityStartTime")) {
951                 c->availability_start_time = get_utc_date_time_insec(s, (const char *)val);
952             } else if (!av_strcasecmp(attr->name, (const char *)"publishTime")) {
953                 c->publish_time = get_utc_date_time_insec(s, (const char *)val);
954             } else if (!av_strcasecmp(attr->name, (const char *)"minimumUpdatePeriod")) {
955                 c->minimum_update_period = get_duration_insec(s, (const char *)val);
956             } else if (!av_strcasecmp(attr->name, (const char *)"timeShiftBufferDepth")) {
957                 c->time_shift_buffer_depth = get_duration_insec(s, (const char *)val);
958             } else if (!av_strcasecmp(attr->name, (const char *)"minBufferTime")) {
959                 c->min_buffer_time = get_duration_insec(s, (const char *)val);
960             } else if (!av_strcasecmp(attr->name, (const char *)"suggestedPresentationDelay")) {
961                 c->suggested_presentation_delay = get_duration_insec(s, (const char *)val);
962             } else if (!av_strcasecmp(attr->name, (const char *)"mediaPresentationDuration")) {
963                 c->media_presentation_duration = get_duration_insec(s, (const char *)val);
964             }
965             attr = attr->next;
966             xmlFree(val);
967         }
968
969         mpd_baseurl_node = find_child_node_by_name(node, "BaseURL");
970
971         // at now we can handle only one period, with the longest duration
972         node = xmlFirstElementChild(node);
973         while (node) {
974             if (!av_strcasecmp(node->name, (const char *)"Period")) {
975                 perdiod_duration_sec = 0;
976                 perdiod_start_sec = 0;
977                 attr = node->properties;
978                 while (attr) {
979                     val = xmlGetProp(node, attr->name);
980                     if (!av_strcasecmp(attr->name, (const char *)"duration")) {
981                         perdiod_duration_sec = get_duration_insec(s, (const char *)val);
982                     } else if (!av_strcasecmp(attr->name, (const char *)"start")) {
983                         perdiod_start_sec = get_duration_insec(s, (const char *)val);
984                     }
985                     attr = attr->next;
986                     xmlFree(val);
987                 }
988                 if ((perdiod_duration_sec) >= (c->period_duration)) {
989                     period_node = node;
990                     c->period_duration = perdiod_duration_sec;
991                     c->period_start = perdiod_start_sec;
992                     if (c->period_start > 0)
993                         c->media_presentation_duration = c->period_duration;
994                 }
995             }
996             node = xmlNextElementSibling(node);
997         }
998         if (!period_node) {
999             av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing Period node\n", url);
1000             ret = AVERROR_INVALIDDATA;
1001             goto cleanup;
1002         }
1003
1004         adaptionset_node = xmlFirstElementChild(period_node);
1005         while (adaptionset_node) {
1006             if (!av_strcasecmp(adaptionset_node->name, (const char *)"BaseURL")) {
1007                 period_baseurl_node = adaptionset_node;
1008             } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"AdaptationSet")) {
1009                 parse_manifest_adaptationset(s, url, adaptionset_node, mpd_baseurl_node, period_baseurl_node);
1010             }
1011             adaptionset_node = xmlNextElementSibling(adaptionset_node);
1012         }
1013         if (c->cur_video) {
1014             c->cur_video->rep_count = video_rep_idx;
1015             av_log(s, AV_LOG_VERBOSE, "rep_idx[%d]\n", (int)c->cur_video->rep_idx);
1016             av_log(s, AV_LOG_VERBOSE, "rep_count[%d]\n", (int)video_rep_idx);
1017         }
1018         if (c->cur_audio) {
1019             c->cur_audio->rep_count = audio_rep_idx;
1020         }
1021 cleanup:
1022         /*free the document */
1023         xmlFreeDoc(doc);
1024         xmlCleanupParser();
1025     }
1026
1027     av_free(new_url);
1028     av_free(buffer);
1029     if (close_in) {
1030         avio_close(in);
1031     }
1032     return ret;
1033 }
1034
1035 static int64_t calc_cur_seg_no(AVFormatContext *s, struct representation *pls)
1036 {
1037     DASHContext *c = s->priv_data;
1038     int64_t num = 0;
1039     int64_t start_time_offset = 0;
1040
1041     if (c->is_live) {
1042         if (pls->n_fragments) {
1043             num = pls->first_seq_no;
1044         } else if (pls->n_timelines) {
1045             start_time_offset = get_segment_start_time_based_on_timeline(pls, 0xFFFFFFFF) - pls->timelines[pls->first_seq_no]->starttime; // total duration of playlist
1046             if (start_time_offset < 60 * pls->fragment_timescale)
1047                 start_time_offset = 0;
1048             else
1049                 start_time_offset = start_time_offset - 60 * pls->fragment_timescale;
1050
1051             num = calc_next_seg_no_from_timelines(pls, pls->timelines[pls->first_seq_no]->starttime + start_time_offset);
1052             if (num == -1)
1053                 num = pls->first_seq_no;
1054         } else if (pls->fragment_duration){
1055             if (pls->presentation_timeoffset) {
1056                 num = pls->presentation_timeoffset * pls->fragment_timescale / pls->fragment_duration;
1057             } else if (c->publish_time > 0 && !c->availability_start_time) {
1058                 num = pls->first_seq_no + (((c->publish_time - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
1059             } else {
1060                 num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
1061             }
1062         }
1063     } else {
1064         num = pls->first_seq_no;
1065     }
1066     return num;
1067 }
1068
1069 static int64_t calc_min_seg_no(AVFormatContext *s, struct representation *pls)
1070 {
1071     DASHContext *c = s->priv_data;
1072     int64_t num = 0;
1073
1074     if (c->is_live && pls->fragment_duration) {
1075         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;
1076     } else {
1077         num = pls->first_seq_no;
1078     }
1079     return num;
1080 }
1081
1082 static int64_t calc_max_seg_no(struct representation *pls, DASHContext *c)
1083 {
1084     int64_t num = 0;
1085
1086     if (pls->n_fragments) {
1087         num = pls->first_seq_no + pls->n_fragments - 1;
1088     } else if (pls->n_timelines) {
1089         int i = 0;
1090         num = pls->first_seq_no + pls->n_timelines - 1;
1091         for (i = 0; i < pls->n_timelines; i++) {
1092             num += pls->timelines[i]->repeat;
1093         }
1094     } else if (c->is_live && pls->fragment_duration) {
1095         num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time)) * pls->fragment_timescale)  / pls->fragment_duration;
1096     } else if (pls->fragment_duration) {
1097         num = pls->first_seq_no + (c->media_presentation_duration * pls->fragment_timescale) / pls->fragment_duration;
1098     }
1099
1100     return num;
1101 }
1102
1103 static void move_timelines(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1104 {
1105     if (rep_dest && rep_src ) {
1106         free_timelines_list(rep_dest);
1107         rep_dest->timelines    = rep_src->timelines;
1108         rep_dest->n_timelines  = rep_src->n_timelines;
1109         rep_dest->first_seq_no = rep_src->first_seq_no;
1110         rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1111         rep_src->timelines = NULL;
1112         rep_src->n_timelines = 0;
1113         rep_dest->cur_seq_no = rep_src->cur_seq_no;
1114     }
1115 }
1116
1117 static void move_segments(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1118 {
1119     if (rep_dest && rep_src ) {
1120         free_fragment_list(rep_dest);
1121         if (rep_src->start_number > (rep_dest->start_number + rep_dest->n_fragments))
1122             rep_dest->cur_seq_no = 0;
1123         else
1124             rep_dest->cur_seq_no += rep_src->start_number - rep_dest->start_number;
1125         rep_dest->fragments    = rep_src->fragments;
1126         rep_dest->n_fragments  = rep_src->n_fragments;
1127         rep_dest->parent  = rep_src->parent;
1128         rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1129         rep_src->fragments = NULL;
1130         rep_src->n_fragments = 0;
1131     }
1132 }
1133
1134
1135 static int refresh_manifest(AVFormatContext *s)
1136 {
1137
1138     int ret = 0;
1139     DASHContext *c = s->priv_data;
1140
1141     // save current context
1142     struct representation *cur_video =  c->cur_video;
1143     struct representation *cur_audio =  c->cur_audio;
1144     char *base_url = c->base_url;
1145
1146     c->base_url = NULL;
1147     c->cur_video = NULL;
1148     c->cur_audio = NULL;
1149     ret = parse_manifest(s, s->filename, NULL);
1150     if (ret)
1151         goto finish;
1152
1153     if (cur_video && cur_video->timelines || cur_audio && cur_audio->timelines) {
1154         // calc current time
1155         int64_t currentVideoTime = 0;
1156         int64_t currentAudioTime = 0;
1157         if (cur_video && cur_video->timelines)
1158             currentVideoTime = get_segment_start_time_based_on_timeline(cur_video, cur_video->cur_seq_no) / cur_video->fragment_timescale;
1159         if (cur_audio && cur_audio->timelines)
1160             currentAudioTime = get_segment_start_time_based_on_timeline(cur_audio, cur_audio->cur_seq_no) / cur_audio->fragment_timescale;
1161         // update segments
1162         if (cur_video && cur_video->timelines) {
1163             c->cur_video->cur_seq_no = calc_next_seg_no_from_timelines(c->cur_video, currentVideoTime * cur_video->fragment_timescale - 1);
1164             if (c->cur_video->cur_seq_no >= 0) {
1165                 move_timelines(c->cur_video, cur_video, c);
1166             }
1167         }
1168         if (cur_audio && cur_audio->timelines) {
1169             c->cur_audio->cur_seq_no = calc_next_seg_no_from_timelines(c->cur_audio, currentAudioTime * cur_audio->fragment_timescale - 1);
1170             if (c->cur_audio->cur_seq_no >= 0) {
1171                move_timelines(c->cur_audio, cur_audio, c);
1172             }
1173         }
1174     }
1175     if (cur_video && cur_video->fragments) {
1176         move_segments(c->cur_video, cur_video, c);
1177     }
1178     if (cur_audio && cur_audio->fragments) {
1179         move_segments(c->cur_audio, cur_audio, c);
1180     }
1181
1182 finish:
1183     // restore context
1184     if (c->base_url)
1185         av_free(base_url);
1186     else
1187         c->base_url  = base_url;
1188     if (c->cur_audio)
1189         free_representation(c->cur_audio);
1190     if (c->cur_video)
1191         free_representation(c->cur_video);
1192     c->cur_audio = cur_audio;
1193     c->cur_video = cur_video;
1194     return ret;
1195 }
1196
1197 static struct fragment *get_current_fragment(struct representation *pls)
1198 {
1199     int64_t min_seq_no = 0;
1200     int64_t max_seq_no = 0;
1201     struct fragment *seg = NULL;
1202     struct fragment *seg_ptr = NULL;
1203     DASHContext *c = pls->parent->priv_data;
1204
1205     while (( !ff_check_interrupt(c->interrupt_callback)&& pls->n_fragments > 0)) {
1206         if (pls->cur_seq_no < pls->n_fragments) {
1207             seg_ptr = pls->fragments[pls->cur_seq_no];
1208             seg = av_mallocz(sizeof(struct fragment));
1209             if (!seg) {
1210                 return NULL;
1211             }
1212             seg->url = av_strdup(seg_ptr->url);
1213             if (!seg->url) {
1214                 av_free(seg);
1215                 return NULL;
1216             }
1217             seg->size = seg_ptr->size;
1218             seg->url_offset = seg_ptr->url_offset;
1219             return seg;
1220         } else if (c->is_live) {
1221             refresh_manifest(pls->parent);
1222         } else {
1223             break;
1224         }
1225     }
1226     if (c->is_live) {
1227         min_seq_no = calc_min_seg_no(pls->parent, pls);
1228         max_seq_no = calc_max_seg_no(pls, c);
1229
1230         if (pls->timelines || pls->fragments) {
1231             refresh_manifest(pls->parent);
1232         }
1233         if (pls->cur_seq_no <= min_seq_no) {
1234             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);
1235             pls->cur_seq_no = calc_cur_seg_no(pls->parent, pls);
1236         } else if (pls->cur_seq_no > max_seq_no) {
1237             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);
1238         }
1239         seg = av_mallocz(sizeof(struct fragment));
1240         if (!seg) {
1241             return NULL;
1242         }
1243     } else if (pls->cur_seq_no <= pls->last_seq_no) {
1244         seg = av_mallocz(sizeof(struct fragment));
1245         if (!seg) {
1246             return NULL;
1247         }
1248     }
1249     if (seg) {
1250         char tmpfilename[MAX_URL_SIZE];
1251
1252         ff_dash_fill_tmpl_params(tmpfilename, sizeof(tmpfilename), pls->url_template, 0, pls->cur_seq_no, 0, get_segment_start_time_based_on_timeline(pls, pls->cur_seq_no));
1253         seg->url = av_strireplace(pls->url_template, pls->url_template, tmpfilename);
1254         if (!seg->url) {
1255             av_log(pls->parent, AV_LOG_WARNING, "Unable to resolve template url '%s', try to use origin template\n", pls->url_template);
1256             seg->url = av_strdup(pls->url_template);
1257             if (!seg->url) {
1258                 av_log(pls->parent, AV_LOG_ERROR, "Cannot resolve template url '%s'\n", pls->url_template);
1259                 return NULL;
1260             }
1261         }
1262
1263         seg->size = -1;
1264     }
1265
1266     return seg;
1267 }
1268
1269 enum ReadFromURLMode {
1270     READ_NORMAL,
1271     READ_COMPLETE,
1272 };
1273
1274 static int read_from_url(struct representation *pls, struct fragment *seg,
1275                          uint8_t *buf, int buf_size,
1276                          enum ReadFromURLMode mode)
1277 {
1278     int ret;
1279
1280     /* limit read if the fragment was only a part of a file */
1281     if (seg->size >= 0)
1282         buf_size = FFMIN(buf_size, pls->cur_seg_size - pls->cur_seg_offset);
1283
1284     if (mode == READ_COMPLETE) {
1285         ret = avio_read(pls->input, buf, buf_size);
1286         if (ret < buf_size) {
1287             av_log(pls->parent, AV_LOG_WARNING, "Could not read complete fragment.\n");
1288         }
1289     } else {
1290         ret = avio_read(pls->input, buf, buf_size);
1291     }
1292     if (ret > 0)
1293         pls->cur_seg_offset += ret;
1294
1295     return ret;
1296 }
1297
1298 static int open_input(DASHContext *c, struct representation *pls, struct fragment *seg)
1299 {
1300     AVDictionary *opts = NULL;
1301     char url[MAX_URL_SIZE];
1302     int ret;
1303
1304     set_httpheader_options(c, &opts);
1305     if (seg->size >= 0) {
1306         /* try to restrict the HTTP request to the part we want
1307          * (if this is in fact a HTTP request) */
1308         av_dict_set_int(&opts, "offset", seg->url_offset, 0);
1309         av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
1310     }
1311
1312     ff_make_absolute_url(url, MAX_URL_SIZE, c->base_url, seg->url);
1313     av_log(pls->parent, AV_LOG_VERBOSE, "DASH request for url '%s', offset %"PRId64", playlist %d\n",
1314            url, seg->url_offset, pls->rep_idx);
1315     ret = open_url(pls->parent, &pls->input, url, c->avio_opts, opts, NULL);
1316     if (ret < 0) {
1317         goto cleanup;
1318     }
1319
1320     /* Seek to the requested position. If this was a HTTP request, the offset
1321      * should already be where want it to, but this allows e.g. local testing
1322      * without a HTTP server. */
1323     if (!ret && seg->url_offset) {
1324         int64_t seekret = avio_seek(pls->input, seg->url_offset, SEEK_SET);
1325         if (seekret < 0) {
1326             av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of DASH fragment '%s'\n", seg->url_offset, seg->url);
1327             ret = (int) seekret;
1328             ff_format_io_close(pls->parent, &pls->input);
1329         }
1330     }
1331
1332 cleanup:
1333     av_dict_free(&opts);
1334     pls->cur_seg_offset = 0;
1335     pls->cur_seg_size = seg->size;
1336     return ret;
1337 }
1338
1339 static int update_init_section(struct representation *pls)
1340 {
1341     static const int max_init_section_size = 1024 * 1024;
1342     DASHContext *c = pls->parent->priv_data;
1343     int64_t sec_size;
1344     int64_t urlsize;
1345     int ret;
1346
1347     if (!pls->init_section || pls->init_sec_buf)
1348         return 0;
1349
1350     ret = open_input(c, pls, pls->init_section);
1351     if (ret < 0) {
1352         av_log(pls->parent, AV_LOG_WARNING,
1353                "Failed to open an initialization section in playlist %d\n",
1354                pls->rep_idx);
1355         return ret;
1356     }
1357
1358     if (pls->init_section->size >= 0)
1359         sec_size = pls->init_section->size;
1360     else if ((urlsize = avio_size(pls->input)) >= 0)
1361         sec_size = urlsize;
1362     else
1363         sec_size = max_init_section_size;
1364
1365     av_log(pls->parent, AV_LOG_DEBUG,
1366            "Downloading an initialization section of size %"PRId64"\n",
1367            sec_size);
1368
1369     sec_size = FFMIN(sec_size, max_init_section_size);
1370
1371     av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
1372
1373     ret = read_from_url(pls, pls->init_section, pls->init_sec_buf,
1374                         pls->init_sec_buf_size, READ_COMPLETE);
1375     ff_format_io_close(pls->parent, &pls->input);
1376
1377     if (ret < 0)
1378         return ret;
1379
1380     pls->init_sec_data_len = ret;
1381     pls->init_sec_buf_read_offset = 0;
1382
1383     return 0;
1384 }
1385
1386 static int64_t seek_data(void *opaque, int64_t offset, int whence)
1387 {
1388     struct representation *v = opaque;
1389     if (v->n_fragments && !v->init_sec_data_len) {
1390         return avio_seek(v->input, offset, whence);
1391     }
1392
1393     return AVERROR(ENOSYS);
1394 }
1395
1396 static int read_data(void *opaque, uint8_t *buf, int buf_size)
1397 {
1398     int ret = 0;
1399     struct representation *v = opaque;
1400     DASHContext *c = v->parent->priv_data;
1401
1402 restart:
1403     if (!v->input) {
1404         free_fragment(&v->cur_seg);
1405         v->cur_seg = get_current_fragment(v);
1406         if (!v->cur_seg) {
1407             ret = AVERROR_EOF;
1408             goto end;
1409         }
1410
1411         /* load/update Media Initialization Section, if any */
1412         ret = update_init_section(v);
1413         if (ret)
1414             goto end;
1415
1416         ret = open_input(c, v, v->cur_seg);
1417         if (ret < 0) {
1418             if (ff_check_interrupt(c->interrupt_callback)) {
1419                 goto end;
1420                 ret = AVERROR_EXIT;
1421             }
1422             av_log(v->parent, AV_LOG_WARNING, "Failed to open fragment of playlist %d\n", v->rep_idx);
1423             v->cur_seq_no++;
1424             goto restart;
1425         }
1426     }
1427
1428     if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
1429         /* Push init section out first before first actual fragment */
1430         int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
1431         memcpy(buf, v->init_sec_buf, copy_size);
1432         v->init_sec_buf_read_offset += copy_size;
1433         ret = copy_size;
1434         goto end;
1435     }
1436
1437     /* check the v->cur_seg, if it is null, get current and double check if the new v->cur_seg*/
1438     if (!v->cur_seg) {
1439         v->cur_seg = get_current_fragment(v);
1440     }
1441     if (!v->cur_seg) {
1442         ret = AVERROR_EOF;
1443         goto end;
1444     }
1445     ret = read_from_url(v, v->cur_seg, buf, buf_size, READ_NORMAL);
1446     if (ret > 0)
1447         goto end;
1448
1449     if (!v->is_restart_needed)
1450         v->cur_seq_no++;
1451     v->is_restart_needed = 1;
1452
1453 end:
1454     return ret;
1455 }
1456
1457 static int save_avio_options(AVFormatContext *s)
1458 {
1459     DASHContext *c = s->priv_data;
1460     const char *opts[] = { "headers", "user_agent", "user-agent", "cookies", NULL }, **opt = opts;
1461     uint8_t *buf = NULL;
1462     int ret = 0;
1463
1464     while (*opt) {
1465         if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN, &buf) >= 0) {
1466             if (buf[0] != '\0') {
1467                 ret = av_dict_set(&c->avio_opts, *opt, buf, AV_DICT_DONT_STRDUP_VAL);
1468                 if (ret < 0) {
1469                     av_freep(&buf);
1470                     return ret;
1471                 }
1472             } else {
1473                 av_freep(&buf);
1474             }
1475         }
1476         opt++;
1477     }
1478
1479     return ret;
1480 }
1481
1482 static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
1483                           int flags, AVDictionary **opts)
1484 {
1485     av_log(s, AV_LOG_ERROR,
1486            "A DASH playlist item '%s' referred to an external file '%s'. "
1487            "Opening this file was forbidden for security reasons\n",
1488            s->filename, url);
1489     return AVERROR(EPERM);
1490 }
1491
1492 static int reopen_demux_for_component(AVFormatContext *s, struct representation *pls)
1493 {
1494     DASHContext *c = s->priv_data;
1495     AVInputFormat *in_fmt = NULL;
1496     AVDictionary  *in_fmt_opts = NULL;
1497     uint8_t *avio_ctx_buffer  = NULL;
1498     int ret = 0;
1499
1500     if (pls->ctx) {
1501         /* note: the internal buffer could have changed, and be != avio_ctx_buffer */
1502         av_freep(&pls->pb.buffer);
1503         memset(&pls->pb, 0x00, sizeof(AVIOContext));
1504         pls->ctx->pb = NULL;
1505         avformat_close_input(&pls->ctx);
1506         pls->ctx = NULL;
1507     }
1508     if (!(pls->ctx = avformat_alloc_context())) {
1509         ret = AVERROR(ENOMEM);
1510         goto fail;
1511     }
1512
1513     avio_ctx_buffer  = av_malloc(INITIAL_BUFFER_SIZE);
1514     if (!avio_ctx_buffer ) {
1515         ret = AVERROR(ENOMEM);
1516         avformat_free_context(pls->ctx);
1517         pls->ctx = NULL;
1518         goto fail;
1519     }
1520     if (c->is_live) {
1521         ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, NULL);
1522     } else {
1523         ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, seek_data);
1524     }
1525     pls->pb.seekable = 0;
1526
1527     if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
1528         goto fail;
1529
1530     pls->ctx->flags = AVFMT_FLAG_CUSTOM_IO;
1531     pls->ctx->probesize = 1024 * 4;
1532     pls->ctx->max_analyze_duration = 4 * AV_TIME_BASE;
1533     ret = av_probe_input_buffer(&pls->pb, &in_fmt, "", NULL, 0, 0);
1534     if (ret < 0) {
1535         av_log(s, AV_LOG_ERROR, "Error when loading first fragment, playlist %d\n", (int)pls->rep_idx);
1536         avformat_free_context(pls->ctx);
1537         pls->ctx = NULL;
1538         goto fail;
1539     }
1540
1541     pls->ctx->pb = &pls->pb;
1542     pls->ctx->io_open  = nested_io_open;
1543
1544     // provide additional information from mpd if available
1545     ret = avformat_open_input(&pls->ctx, "", in_fmt, &in_fmt_opts); //pls->init_section->url
1546     av_dict_free(&in_fmt_opts);
1547     if (ret < 0)
1548         goto fail;
1549     if (pls->n_fragments) {
1550         ret = avformat_find_stream_info(pls->ctx, NULL);
1551         if (ret < 0)
1552             goto fail;
1553     }
1554
1555 fail:
1556     return ret;
1557 }
1558
1559 static int open_demux_for_component(AVFormatContext *s, struct representation *pls)
1560 {
1561     int ret = 0;
1562     int i;
1563
1564     pls->parent = s;
1565     pls->cur_seq_no  = calc_cur_seg_no(s, pls);
1566     pls->last_seq_no = calc_max_seg_no(pls, s->priv_data);
1567
1568     ret = reopen_demux_for_component(s, pls);
1569     if (ret < 0) {
1570         goto fail;
1571     }
1572     for (i = 0; i < pls->ctx->nb_streams; i++) {
1573         AVStream *st = avformat_new_stream(s, NULL);
1574         AVStream *ist = pls->ctx->streams[i];
1575         if (!st) {
1576             ret = AVERROR(ENOMEM);
1577             goto fail;
1578         }
1579         st->id = i;
1580         avcodec_parameters_copy(st->codecpar, pls->ctx->streams[i]->codecpar);
1581         avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
1582     }
1583
1584     return 0;
1585 fail:
1586     return ret;
1587 }
1588
1589 static int dash_read_header(AVFormatContext *s)
1590 {
1591     void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;
1592     DASHContext *c = s->priv_data;
1593     int ret = 0;
1594     int stream_index = 0;
1595
1596     c->interrupt_callback = &s->interrupt_callback;
1597     // if the URL context is good, read important options we must broker later
1598     if (u) {
1599         update_options(&c->user_agent, "user-agent", u);
1600         update_options(&c->cookies, "cookies", u);
1601         update_options(&c->headers, "headers", u);
1602     }
1603
1604     if ((ret = parse_manifest(s, s->filename, s->pb)) < 0)
1605         goto fail;
1606
1607     if ((ret = save_avio_options(s)) < 0)
1608         goto fail;
1609
1610     /* If this isn't a live stream, fill the total duration of the
1611      * stream. */
1612     if (!c->is_live) {
1613         s->duration = (int64_t) c->media_presentation_duration * AV_TIME_BASE;
1614     }
1615
1616     /* Open the demuxer for curent video and current audio components if available */
1617     if (!ret && c->cur_video) {
1618         ret = open_demux_for_component(s, c->cur_video);
1619         if (!ret) {
1620             c->cur_video->stream_index = stream_index;
1621             ++stream_index;
1622         } else {
1623             free_representation(c->cur_video);
1624             c->cur_video = NULL;
1625         }
1626     }
1627
1628     if (!ret && c->cur_audio) {
1629         ret = open_demux_for_component(s, c->cur_audio);
1630         if (!ret) {
1631             c->cur_audio->stream_index = stream_index;
1632             ++stream_index;
1633         } else {
1634             free_representation(c->cur_audio);
1635             c->cur_audio = NULL;
1636         }
1637     }
1638
1639     if (!stream_index) {
1640         ret = AVERROR_INVALIDDATA;
1641         goto fail;
1642     }
1643
1644     /* Create a program */
1645     if (!ret) {
1646         AVProgram *program;
1647         program = av_new_program(s, 0);
1648         if (!program) {
1649             goto fail;
1650         }
1651
1652         if (c->cur_video) {
1653             av_program_add_stream_index(s, 0, c->cur_video->stream_index);
1654         }
1655         if (c->cur_audio) {
1656             av_program_add_stream_index(s, 0, c->cur_audio->stream_index);
1657         }
1658     }
1659
1660     return 0;
1661 fail:
1662     return ret;
1663 }
1664
1665 static int dash_read_packet(AVFormatContext *s, AVPacket *pkt)
1666 {
1667     DASHContext *c = s->priv_data;
1668     int ret = 0;
1669     struct representation *cur = NULL;
1670
1671     if (!c->cur_audio && !c->cur_video ) {
1672         return AVERROR_INVALIDDATA;
1673     }
1674     if (c->cur_audio && !c->cur_video) {
1675         cur = c->cur_audio;
1676     } else if (!c->cur_audio && c->cur_video) {
1677         cur = c->cur_video;
1678     } else if (c->cur_video->cur_timestamp < c->cur_audio->cur_timestamp) {
1679         cur = c->cur_video;
1680     } else {
1681         cur = c->cur_audio;
1682     }
1683
1684     if (cur->ctx) {
1685         while (!ff_check_interrupt(c->interrupt_callback) && !ret) {
1686             ret = av_read_frame(cur->ctx, pkt);
1687             if (ret >= 0) {
1688                 /* If we got a packet, return it */
1689                 cur->cur_timestamp = av_rescale(pkt->pts, (int64_t)cur->ctx->streams[0]->time_base.num * 90000, cur->ctx->streams[0]->time_base.den);
1690                 pkt->stream_index = cur->stream_index;
1691                 return 0;
1692             }
1693             if (cur->is_restart_needed) {
1694                 cur->cur_seg_offset = 0;
1695                 cur->init_sec_buf_read_offset = 0;
1696                 if (cur->input)
1697                     ff_format_io_close(cur->parent, &cur->input);
1698                 ret = reopen_demux_for_component(s, cur);
1699                 cur->is_restart_needed = 0;
1700             }
1701
1702         }
1703     }
1704     return AVERROR_EOF;
1705 }
1706
1707 static int dash_close(AVFormatContext *s)
1708 {
1709     DASHContext *c = s->priv_data;
1710     if (c->cur_audio) {
1711         free_representation(c->cur_audio);
1712     }
1713     if (c->cur_video) {
1714         free_representation(c->cur_video);
1715     }
1716
1717     av_freep(&c->cookies);
1718     av_freep(&c->user_agent);
1719     av_dict_free(&c->avio_opts);
1720     av_freep(&c->base_url);
1721     return 0;
1722 }
1723
1724 static int dash_seek(AVFormatContext *s, struct representation *pls, int64_t seek_pos_msec, int flags)
1725 {
1726     int ret = 0;
1727     int i = 0;
1728     int j = 0;
1729     int64_t duration = 0;
1730
1731     av_log(pls->parent, AV_LOG_VERBOSE, "DASH seek pos[%"PRId64"ms], playlist %d\n", seek_pos_msec, pls->rep_idx);
1732
1733     // single fragment mode
1734     if (pls->n_fragments == 1) {
1735         pls->cur_timestamp = 0;
1736         pls->cur_seg_offset = 0;
1737         ff_read_frame_flush(pls->ctx);
1738         return av_seek_frame(pls->ctx, -1, seek_pos_msec * 1000, flags);
1739     }
1740
1741     if (pls->input)
1742         ff_format_io_close(pls->parent, &pls->input);
1743
1744     // find the nearest fragment
1745     if (pls->n_timelines > 0 && pls->fragment_timescale > 0) {
1746         int64_t num = pls->first_seq_no;
1747         av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline start n_timelines[%d] "
1748                "last_seq_no[%"PRId64"], playlist %d.\n",
1749                (int)pls->n_timelines, (int64_t)pls->last_seq_no, (int)pls->rep_idx);
1750         for (i = 0; i < pls->n_timelines; i++) {
1751             if (pls->timelines[i]->starttime > 0) {
1752                 duration = pls->timelines[i]->starttime;
1753             }
1754             duration += pls->timelines[i]->duration;
1755             if (seek_pos_msec < ((duration * 1000) /  pls->fragment_timescale)) {
1756                 goto set_seq_num;
1757             }
1758             for (j = 0; j < pls->timelines[i]->repeat; j++) {
1759                 duration += pls->timelines[i]->duration;
1760                 num++;
1761                 if (seek_pos_msec < ((duration * 1000) /  pls->fragment_timescale)) {
1762                     goto set_seq_num;
1763                 }
1764             }
1765             num++;
1766         }
1767
1768 set_seq_num:
1769         pls->cur_seq_no = num > pls->last_seq_no ? pls->last_seq_no : num;
1770         av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline end cur_seq_no[%"PRId64"], playlist %d.\n",
1771                (int64_t)pls->cur_seq_no, (int)pls->rep_idx);
1772     } else if (pls->fragment_duration > 0) {
1773         pls->cur_seq_no = pls->first_seq_no + ((seek_pos_msec * pls->fragment_timescale) / pls->fragment_duration) / 1000;
1774     } else {
1775         av_log(pls->parent, AV_LOG_ERROR, "dash_seek missing fragment_duration\n");
1776         pls->cur_seq_no = pls->first_seq_no;
1777     }
1778     pls->cur_timestamp = 0;
1779     pls->cur_seg_offset = 0;
1780     pls->init_sec_buf_read_offset = 0;
1781     ret = reopen_demux_for_component(s, pls);
1782
1783     return ret;
1784 }
1785
1786 static int dash_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1787 {
1788     int ret = 0;
1789     DASHContext *c = s->priv_data;
1790     int64_t seek_pos_msec = av_rescale_rnd(timestamp, 1000,
1791                                            s->streams[stream_index]->time_base.den,
1792                                            flags & AVSEEK_FLAG_BACKWARD ?
1793                                            AV_ROUND_DOWN : AV_ROUND_UP);
1794     if ((flags & AVSEEK_FLAG_BYTE) || c->is_live)
1795         return AVERROR(ENOSYS);
1796     if (c->cur_audio) {
1797         ret = dash_seek(s, c->cur_audio, seek_pos_msec, flags);
1798     }
1799     if (!ret && c->cur_video) {
1800         ret = dash_seek(s, c->cur_video, seek_pos_msec, flags);
1801     }
1802     return ret;
1803 }
1804
1805 static int dash_probe(AVProbeData *p)
1806 {
1807     if (!av_stristr(p->buf, "<MPD"))
1808         return 0;
1809
1810     if (av_stristr(p->buf, "dash:profile:isoff-on-demand:2011") ||
1811         av_stristr(p->buf, "dash:profile:isoff-live:2011") ||
1812         av_stristr(p->buf, "dash:profile:isoff-live:2012") ||
1813         av_stristr(p->buf, "dash:profile:isoff-main:2011")) {
1814         return AVPROBE_SCORE_MAX;
1815     }
1816     if (av_stristr(p->buf, "dash:profile")) {
1817         return AVPROBE_SCORE_MAX;
1818     }
1819
1820     return 0;
1821 }
1822
1823 #define OFFSET(x) offsetof(DASHContext, x)
1824 #define FLAGS AV_OPT_FLAG_DECODING_PARAM
1825 static const AVOption dash_options[] = {
1826     {"allowed_extensions", "List of file extensions that dash is allowed to access",
1827         OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
1828         {.str = "aac,m4a,m4s,m4v,mov,mp4"},
1829         INT_MIN, INT_MAX, FLAGS},
1830     {NULL}
1831 };
1832
1833 static const AVClass dash_class = {
1834     .class_name = "dash",
1835     .item_name  = av_default_item_name,
1836     .option     = dash_options,
1837     .version    = LIBAVUTIL_VERSION_INT,
1838 };
1839
1840 AVInputFormat ff_dash_demuxer = {
1841     .name           = "dash",
1842     .long_name      = NULL_IF_CONFIG_SMALL("Dynamic Adaptive Streaming over HTTP"),
1843     .priv_class     = &dash_class,
1844     .priv_data_size = sizeof(DASHContext),
1845     .read_probe     = dash_probe,
1846     .read_header    = dash_read_header,
1847     .read_packet    = dash_read_packet,
1848     .read_close     = dash_close,
1849     .read_seek      = dash_read_seek,
1850     .flags          = AVFMT_NO_BYTE_SEEK,
1851 };