]> git.sesse.net Git - ffmpeg/blob - libavformat/hlsenc.c
Merge commit 'd847a40888c064cc8c35b546fc5a0ccb69136a7c'
[ffmpeg] / libavformat / hlsenc.c
1 /*
2  * Apple HTTP Live Streaming segmenter
3  * Copyright (c) 2012, Luca Barbato
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23 #include <float.h>
24 #include <stdint.h>
25 #if HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28
29 #include "libavutil/avassert.h"
30 #include "libavutil/mathematics.h"
31 #include "libavutil/parseutils.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/log.h"
35 #include "libavutil/time_internal.h"
36
37 #include "avformat.h"
38 #include "avio_internal.h"
39 #include "internal.h"
40 #include "os_support.h"
41
42 #define KEYSIZE 16
43 #define LINE_BUFFER_SIZE 1024
44
45 typedef struct HLSSegment {
46     char filename[1024];
47     char sub_filename[1024];
48     double duration; /* in seconds */
49     int64_t pos;
50     int64_t size;
51
52     char key_uri[LINE_BUFFER_SIZE + 1];
53     char iv_string[KEYSIZE*2 + 1];
54
55     struct HLSSegment *next;
56 } HLSSegment;
57
58 typedef enum HLSFlags {
59     // Generate a single media file and use byte ranges in the playlist.
60     HLS_SINGLE_FILE = (1 << 0),
61     HLS_DELETE_SEGMENTS = (1 << 1),
62     HLS_ROUND_DURATIONS = (1 << 2),
63     HLS_DISCONT_START = (1 << 3),
64     HLS_OMIT_ENDLIST = (1 << 4),
65 } HLSFlags;
66
67 typedef struct HLSContext {
68     const AVClass *class;  // Class for private options.
69     unsigned number;
70     int64_t sequence;
71     int64_t start_sequence;
72     AVOutputFormat *oformat;
73     AVOutputFormat *vtt_oformat;
74
75     AVFormatContext *avf;
76     AVFormatContext *vtt_avf;
77
78     float time;            // Set by a private option.
79     int max_nb_segments;   // Set by a private option.
80     int  wrap;             // Set by a private option.
81     uint32_t flags;        // enum HLSFlags
82     char *segment_filename;
83
84     int use_localtime;      ///< flag to expand filename with localtime
85     int use_localtime_mkdir;///< flag to mkdir dirname in timebased filename
86     int allowcache;
87     int64_t recording_time;
88     int has_video;
89     int has_subtitle;
90     int64_t start_pts;
91     int64_t end_pts;
92     double duration;      // last segment duration computed so far, in seconds
93     int64_t start_pos;    // last segment starting position
94     int64_t size;         // last segment size
95     int nb_entries;
96     int discontinuity_set;
97
98     HLSSegment *segments;
99     HLSSegment *last_segment;
100     HLSSegment *old_segments;
101
102     char *basename;
103     char *vtt_basename;
104     char *vtt_m3u8_name;
105     char *baseurl;
106     char *format_options_str;
107     char *vtt_format_options_str;
108     char *subtitle_filename;
109     AVDictionary *format_options;
110
111     char *key_info_file;
112     char key_file[LINE_BUFFER_SIZE + 1];
113     char key_uri[LINE_BUFFER_SIZE + 1];
114     char key_string[KEYSIZE*2 + 1];
115     char iv_string[KEYSIZE*2 + 1];
116     AVDictionary *vtt_format_options;
117
118     char *method;
119
120 } HLSContext;
121
122 static int hls_delete_old_segments(HLSContext *hls) {
123
124     HLSSegment *segment, *previous_segment = NULL;
125     float playlist_duration = 0.0f;
126     int ret = 0, path_size, sub_path_size;
127     char *dirname = NULL, *p, *sub_path;
128     char *path = NULL;
129
130     segment = hls->segments;
131     while (segment) {
132         playlist_duration += segment->duration;
133         segment = segment->next;
134     }
135
136     segment = hls->old_segments;
137     while (segment) {
138         playlist_duration -= segment->duration;
139         previous_segment = segment;
140         segment = previous_segment->next;
141         if (playlist_duration <= -previous_segment->duration) {
142             previous_segment->next = NULL;
143             break;
144         }
145     }
146
147     if (segment) {
148         if (hls->segment_filename) {
149             dirname = av_strdup(hls->segment_filename);
150         } else {
151             dirname = av_strdup(hls->avf->filename);
152         }
153         if (!dirname) {
154             ret = AVERROR(ENOMEM);
155             goto fail;
156         }
157         p = (char *)av_basename(dirname);
158         *p = '\0';
159     }
160
161     while (segment) {
162         av_log(hls, AV_LOG_DEBUG, "deleting old segment %s\n",
163                                   segment->filename);
164         path_size = strlen(dirname) + strlen(segment->filename) + 1;
165         path = av_malloc(path_size);
166         if (!path) {
167             ret = AVERROR(ENOMEM);
168             goto fail;
169         }
170
171         av_strlcpy(path, dirname, path_size);
172         av_strlcat(path, segment->filename, path_size);
173         if (unlink(path) < 0) {
174             av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
175                                      path, strerror(errno));
176         }
177
178         if (segment->sub_filename[0] != '\0') {
179             sub_path_size = strlen(dirname) + strlen(segment->sub_filename) + 1;
180             sub_path = av_malloc(sub_path_size);
181             if (!sub_path) {
182                 ret = AVERROR(ENOMEM);
183                 goto fail;
184             }
185
186             av_strlcpy(sub_path, dirname, sub_path_size);
187             av_strlcat(sub_path, segment->sub_filename, sub_path_size);
188             if (unlink(sub_path) < 0) {
189                 av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
190                                          sub_path, strerror(errno));
191             }
192             av_free(sub_path);
193         }
194         av_freep(&path);
195         previous_segment = segment;
196         segment = previous_segment->next;
197         av_free(previous_segment);
198     }
199
200 fail:
201     av_free(path);
202     av_free(dirname);
203
204     return ret;
205 }
206
207 static int hls_encryption_start(AVFormatContext *s)
208 {
209     HLSContext *hls = s->priv_data;
210     int ret;
211     AVIOContext *pb;
212     uint8_t key[KEYSIZE];
213
214     if ((ret = s->io_open(s, &pb, hls->key_info_file, AVIO_FLAG_READ, NULL)) < 0) {
215         av_log(hls, AV_LOG_ERROR,
216                 "error opening key info file %s\n", hls->key_info_file);
217         return ret;
218     }
219
220     ff_get_line(pb, hls->key_uri, sizeof(hls->key_uri));
221     hls->key_uri[strcspn(hls->key_uri, "\r\n")] = '\0';
222
223     ff_get_line(pb, hls->key_file, sizeof(hls->key_file));
224     hls->key_file[strcspn(hls->key_file, "\r\n")] = '\0';
225
226     ff_get_line(pb, hls->iv_string, sizeof(hls->iv_string));
227     hls->iv_string[strcspn(hls->iv_string, "\r\n")] = '\0';
228
229     ff_format_io_close(s, &pb);
230
231     if (!*hls->key_uri) {
232         av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
233         return AVERROR(EINVAL);
234     }
235
236     if (!*hls->key_file) {
237         av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
238         return AVERROR(EINVAL);
239     }
240
241     if ((ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_READ, NULL)) < 0) {
242         av_log(hls, AV_LOG_ERROR, "error opening key file %s\n", hls->key_file);
243         return ret;
244     }
245
246     ret = avio_read(pb, key, sizeof(key));
247     ff_format_io_close(s, &pb);
248     if (ret != sizeof(key)) {
249         av_log(hls, AV_LOG_ERROR, "error reading key file %s\n", hls->key_file);
250         if (ret >= 0 || ret == AVERROR_EOF)
251             ret = AVERROR(EINVAL);
252         return ret;
253     }
254     ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
255
256     return 0;
257 }
258
259 static int hls_mux_init(AVFormatContext *s)
260 {
261     HLSContext *hls = s->priv_data;
262     AVFormatContext *oc;
263     AVFormatContext *vtt_oc = NULL;
264     int i, ret;
265
266     ret = avformat_alloc_output_context2(&hls->avf, hls->oformat, NULL, NULL);
267     if (ret < 0)
268         return ret;
269     oc = hls->avf;
270
271     oc->oformat            = hls->oformat;
272     oc->interrupt_callback = s->interrupt_callback;
273     oc->max_delay          = s->max_delay;
274     oc->opaque             = s->opaque;
275     oc->io_open            = s->io_open;
276     oc->io_close           = s->io_close;
277     av_dict_copy(&oc->metadata, s->metadata, 0);
278
279     if(hls->vtt_oformat) {
280         ret = avformat_alloc_output_context2(&hls->vtt_avf, hls->vtt_oformat, NULL, NULL);
281         if (ret < 0)
282             return ret;
283         vtt_oc          = hls->vtt_avf;
284         vtt_oc->oformat = hls->vtt_oformat;
285         av_dict_copy(&vtt_oc->metadata, s->metadata, 0);
286     }
287
288     for (i = 0; i < s->nb_streams; i++) {
289         AVStream *st;
290         AVFormatContext *loc;
291         if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
292             loc = vtt_oc;
293         else
294             loc = oc;
295
296         if (!(st = avformat_new_stream(loc, NULL)))
297             return AVERROR(ENOMEM);
298         avcodec_copy_context(st->codec, s->streams[i]->codec);
299         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
300         st->time_base = s->streams[i]->time_base;
301     }
302     hls->start_pos = 0;
303
304     return 0;
305 }
306
307 /* Create a new segment and append it to the segment list */
308 static int hls_append_segment(struct AVFormatContext *s, HLSContext *hls, double duration,
309                               int64_t pos, int64_t size)
310 {
311     HLSSegment *en = av_malloc(sizeof(*en));
312     char *tmp, *p;
313     const char *pl_dir, *filename;
314     int ret;
315
316     if (!en)
317         return AVERROR(ENOMEM);
318
319     filename = av_basename(hls->avf->filename);
320
321     if (hls->use_localtime_mkdir) {
322         /* Possibly prefix with mkdir'ed subdir, if playlist share same
323          * base path. */
324         tmp = av_strdup(s->filename);
325         if (!tmp) {
326             av_free(en);
327             return AVERROR(ENOMEM);
328         }
329
330         pl_dir = av_dirname(tmp);
331         p = hls->avf->filename;
332         if (strstr(p, pl_dir) == p)
333             filename = hls->avf->filename + strlen(pl_dir) + 1;
334         av_free(tmp);
335     }
336     av_strlcpy(en->filename, filename, sizeof(en->filename));
337
338     if(hls->has_subtitle)
339         av_strlcpy(en->sub_filename, av_basename(hls->vtt_avf->filename), sizeof(en->sub_filename));
340     else
341         en->sub_filename[0] = '\0';
342
343     en->duration = duration;
344     en->pos      = pos;
345     en->size     = size;
346     en->next     = NULL;
347
348     if (hls->key_info_file) {
349         av_strlcpy(en->key_uri, hls->key_uri, sizeof(en->key_uri));
350         av_strlcpy(en->iv_string, hls->iv_string, sizeof(en->iv_string));
351     }
352
353     if (!hls->segments)
354         hls->segments = en;
355     else
356         hls->last_segment->next = en;
357
358     hls->last_segment = en;
359
360     if (hls->max_nb_segments && hls->nb_entries >= hls->max_nb_segments) {
361         en = hls->segments;
362         hls->segments = en->next;
363         if (en && hls->flags & HLS_DELETE_SEGMENTS &&
364                 !(hls->flags & HLS_SINGLE_FILE || hls->wrap)) {
365             en->next = hls->old_segments;
366             hls->old_segments = en;
367             if ((ret = hls_delete_old_segments(hls)) < 0)
368                 return ret;
369         } else
370             av_free(en);
371     } else
372         hls->nb_entries++;
373
374     hls->sequence++;
375
376     return 0;
377 }
378
379 static void hls_free_segments(HLSSegment *p)
380 {
381     HLSSegment *en;
382
383     while(p) {
384         en = p;
385         p = p->next;
386         av_free(en);
387     }
388 }
389
390 static void set_http_options(AVDictionary **options, HLSContext *c)
391 {
392     if (c->method)
393         av_dict_set(options, "method", c->method, 0);
394 }
395
396 static int hls_window(AVFormatContext *s, int last)
397 {
398     HLSContext *hls = s->priv_data;
399     HLSSegment *en;
400     int target_duration = 0;
401     int ret = 0;
402     AVIOContext *out = NULL;
403     AVIOContext *sub_out = NULL;
404     char temp_filename[1024];
405     int64_t sequence = FFMAX(hls->start_sequence, hls->sequence - hls->nb_entries);
406     int version = hls->flags & HLS_SINGLE_FILE ? 4 : 3;
407     const char *proto = avio_find_protocol_name(s->filename);
408     int use_rename = proto && !strcmp(proto, "file");
409     static unsigned warned_non_file;
410     char *key_uri = NULL;
411     char *iv_string = NULL;
412     AVDictionary *options = NULL;
413
414     if (!use_rename && !warned_non_file++)
415         av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporarly partial files\n");
416
417     set_http_options(&options, hls);
418     snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename);
419     if ((ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL)) < 0)
420         goto fail;
421
422     for (en = hls->segments; en; en = en->next) {
423         if (target_duration < en->duration)
424             target_duration = ceil(en->duration);
425     }
426
427     hls->discontinuity_set = 0;
428     avio_printf(out, "#EXTM3U\n");
429     avio_printf(out, "#EXT-X-VERSION:%d\n", version);
430     if (hls->allowcache == 0 || hls->allowcache == 1) {
431         avio_printf(out, "#EXT-X-ALLOW-CACHE:%s\n", hls->allowcache == 0 ? "NO" : "YES");
432     }
433     avio_printf(out, "#EXT-X-TARGETDURATION:%d\n", target_duration);
434     avio_printf(out, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
435
436     av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
437            sequence);
438     if((hls->flags & HLS_DISCONT_START) && sequence==hls->start_sequence && hls->discontinuity_set==0 ){
439         avio_printf(out, "#EXT-X-DISCONTINUITY\n");
440         hls->discontinuity_set = 1;
441     }
442     for (en = hls->segments; en; en = en->next) {
443         if (hls->key_info_file && (!key_uri || strcmp(en->key_uri, key_uri) ||
444                                     av_strcasecmp(en->iv_string, iv_string))) {
445             avio_printf(out, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"", en->key_uri);
446             if (*en->iv_string)
447                 avio_printf(out, ",IV=0x%s", en->iv_string);
448             avio_printf(out, "\n");
449             key_uri = en->key_uri;
450             iv_string = en->iv_string;
451         }
452
453         if (hls->flags & HLS_ROUND_DURATIONS)
454             avio_printf(out, "#EXTINF:%ld,\n",  lrint(en->duration));
455         else
456             avio_printf(out, "#EXTINF:%f,\n", en->duration);
457         if (hls->flags & HLS_SINGLE_FILE)
458              avio_printf(out, "#EXT-X-BYTERANGE:%"PRIi64"@%"PRIi64"\n",
459                          en->size, en->pos);
460         if (hls->baseurl)
461             avio_printf(out, "%s", hls->baseurl);
462         avio_printf(out, "%s\n", en->filename);
463     }
464
465     if (last && (hls->flags & HLS_OMIT_ENDLIST)==0)
466         avio_printf(out, "#EXT-X-ENDLIST\n");
467
468     if( hls->vtt_m3u8_name ) {
469         if ((ret = s->io_open(s, &sub_out, hls->vtt_m3u8_name, AVIO_FLAG_WRITE, &options)) < 0)
470             goto fail;
471         avio_printf(sub_out, "#EXTM3U\n");
472         avio_printf(sub_out, "#EXT-X-VERSION:%d\n", version);
473         if (hls->allowcache == 0 || hls->allowcache == 1) {
474             avio_printf(sub_out, "#EXT-X-ALLOW-CACHE:%s\n", hls->allowcache == 0 ? "NO" : "YES");
475         }
476         avio_printf(sub_out, "#EXT-X-TARGETDURATION:%d\n", target_duration);
477         avio_printf(sub_out, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
478
479         av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
480                sequence);
481
482         for (en = hls->segments; en; en = en->next) {
483             avio_printf(sub_out, "#EXTINF:%f,\n", en->duration);
484             if (hls->flags & HLS_SINGLE_FILE)
485                  avio_printf(sub_out, "#EXT-X-BYTERANGE:%"PRIi64"@%"PRIi64"\n",
486                          en->size, en->pos);
487             if (hls->baseurl)
488                 avio_printf(sub_out, "%s", hls->baseurl);
489             avio_printf(sub_out, "%s\n", en->sub_filename);
490         }
491
492         if (last)
493             avio_printf(sub_out, "#EXT-X-ENDLIST\n");
494
495     }
496
497 fail:
498     av_dict_free(&options);
499     ff_format_io_close(s, &out);
500     ff_format_io_close(s, &sub_out);
501     if (ret >= 0 && use_rename)
502         ff_rename(temp_filename, s->filename, s);
503     return ret;
504 }
505
506 static int hls_start(AVFormatContext *s)
507 {
508     HLSContext *c = s->priv_data;
509     AVFormatContext *oc = c->avf;
510     AVFormatContext *vtt_oc = c->vtt_avf;
511     AVDictionary *options = NULL;
512     char *filename, iv_string[KEYSIZE*2 + 1];
513     int err = 0;
514
515     if (c->flags & HLS_SINGLE_FILE) {
516         av_strlcpy(oc->filename, c->basename,
517                    sizeof(oc->filename));
518         if (c->vtt_basename)
519             av_strlcpy(vtt_oc->filename, c->vtt_basename,
520                   sizeof(vtt_oc->filename));
521     } else {
522         if (c->use_localtime) {
523             time_t now0;
524             struct tm *tm, tmpbuf;
525             time(&now0);
526             tm = localtime_r(&now0, &tmpbuf);
527             if (!strftime(oc->filename, sizeof(oc->filename), c->basename, tm)) {
528                 av_log(oc, AV_LOG_ERROR, "Could not get segment filename with use_localtime\n");
529                 return AVERROR(EINVAL);
530             }
531
532             if (c->use_localtime_mkdir) {
533                 const char *dir;
534                 char *fn_copy = av_strdup(oc->filename);
535                 if (!fn_copy) {
536                     return AVERROR(ENOMEM);
537                 }
538                 dir = av_dirname(fn_copy);
539                 if (mkdir(dir, 0777) == -1 && errno != EEXIST) {
540                     av_log(oc, AV_LOG_ERROR, "Could not create directory %s with use_localtime_mkdir\n", dir);
541                     av_free(fn_copy);
542                     return AVERROR(errno);
543                 }
544                 av_free(fn_copy);
545             }
546         } else if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
547                                   c->basename, c->wrap ? c->sequence % c->wrap : c->sequence) < 0) {
548             av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s' you can try use -use_localtime 1 with it\n", c->basename);
549             return AVERROR(EINVAL);
550         }
551         if( c->vtt_basename) {
552             if (av_get_frame_filename(vtt_oc->filename, sizeof(vtt_oc->filename),
553                               c->vtt_basename, c->wrap ? c->sequence % c->wrap : c->sequence) < 0) {
554                 av_log(vtt_oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", c->vtt_basename);
555                 return AVERROR(EINVAL);
556             }
557        }
558     }
559     c->number++;
560
561     set_http_options(&options, c);
562
563     if (c->key_info_file) {
564         if ((err = hls_encryption_start(s)) < 0)
565             goto fail;
566         if ((err = av_dict_set(&options, "encryption_key", c->key_string, 0))
567                 < 0)
568             goto fail;
569         err = av_strlcpy(iv_string, c->iv_string, sizeof(iv_string));
570         if (!err)
571             snprintf(iv_string, sizeof(iv_string), "%032"PRIx64, c->sequence);
572         if ((err = av_dict_set(&options, "encryption_iv", iv_string, 0)) < 0)
573            goto fail;
574
575         filename = av_asprintf("crypto:%s", oc->filename);
576         if (!filename) {
577             err = AVERROR(ENOMEM);
578             goto fail;
579         }
580         err = s->io_open(s, &oc->pb, filename, AVIO_FLAG_WRITE, &options);
581         av_free(filename);
582         av_dict_free(&options);
583         if (err < 0)
584             return err;
585     } else
586         if ((err = s->io_open(s, &oc->pb, oc->filename, AVIO_FLAG_WRITE, &options)) < 0)
587             goto fail;
588     if (c->vtt_basename) {
589         set_http_options(&options, c);
590         if ((err = s->io_open(s, &vtt_oc->pb, vtt_oc->filename, AVIO_FLAG_WRITE, &options)) < 0)
591             goto fail;
592     }
593     av_dict_free(&options);
594
595     /* We only require one PAT/PMT per segment. */
596     if (oc->oformat->priv_class && oc->priv_data) {
597         char period[21];
598
599         snprintf(period, sizeof(period), "%d", (INT_MAX / 2) - 1);
600
601         av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
602         av_opt_set(oc->priv_data, "sdt_period", period, 0);
603         av_opt_set(oc->priv_data, "pat_period", period, 0);
604     }
605
606     if (c->vtt_basename) {
607         err = avformat_write_header(vtt_oc,NULL);
608         if (err < 0)
609             return err;
610     }
611
612     return 0;
613 fail:
614     av_dict_free(&options);
615
616     return err;
617 }
618
619 static int hls_write_header(AVFormatContext *s)
620 {
621     HLSContext *hls = s->priv_data;
622     int ret, i;
623     char *p;
624     const char *pattern = "%d.ts";
625     const char *pattern_localtime_fmt = "-%s.ts";
626     const char *vtt_pattern = "%d.vtt";
627     AVDictionary *options = NULL;
628     int basename_size;
629     int vtt_basename_size;
630
631     hls->sequence       = hls->start_sequence;
632     hls->recording_time = hls->time * AV_TIME_BASE;
633     hls->start_pts      = AV_NOPTS_VALUE;
634
635     if (hls->format_options_str) {
636         ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
637         if (ret < 0) {
638             av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n", hls->format_options_str);
639             goto fail;
640         }
641     }
642
643     for (i = 0; i < s->nb_streams; i++) {
644         hls->has_video +=
645             s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO;
646         hls->has_subtitle +=
647             s->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE;
648     }
649
650     if (hls->has_video > 1)
651         av_log(s, AV_LOG_WARNING,
652                "More than a single video stream present, "
653                "expect issues decoding it.\n");
654
655     hls->oformat = av_guess_format("mpegts", NULL, NULL);
656
657     if (!hls->oformat) {
658         ret = AVERROR_MUXER_NOT_FOUND;
659         goto fail;
660     }
661
662     if(hls->has_subtitle) {
663         hls->vtt_oformat = av_guess_format("webvtt", NULL, NULL);
664         if (!hls->oformat) {
665             ret = AVERROR_MUXER_NOT_FOUND;
666             goto fail;
667         }
668     }
669
670     if (hls->segment_filename) {
671         hls->basename = av_strdup(hls->segment_filename);
672         if (!hls->basename) {
673             ret = AVERROR(ENOMEM);
674             goto fail;
675         }
676     } else {
677         if (hls->flags & HLS_SINGLE_FILE)
678             pattern = ".ts";
679
680         if (hls->use_localtime) {
681             basename_size = strlen(s->filename) + strlen(pattern_localtime_fmt) + 1;
682         } else {
683             basename_size = strlen(s->filename) + strlen(pattern) + 1;
684         }
685         hls->basename = av_malloc(basename_size);
686         if (!hls->basename) {
687             ret = AVERROR(ENOMEM);
688             goto fail;
689         }
690
691         av_strlcpy(hls->basename, s->filename, basename_size);
692
693         p = strrchr(hls->basename, '.');
694         if (p)
695             *p = '\0';
696         if (hls->use_localtime) {
697             av_strlcat(hls->basename, pattern_localtime_fmt, basename_size);
698         } else {
699             av_strlcat(hls->basename, pattern, basename_size);
700         }
701     }
702
703     if(hls->has_subtitle) {
704
705         if (hls->flags & HLS_SINGLE_FILE)
706             vtt_pattern = ".vtt";
707         vtt_basename_size = strlen(s->filename) + strlen(vtt_pattern) + 1;
708         hls->vtt_basename = av_malloc(vtt_basename_size);
709         if (!hls->vtt_basename) {
710             ret = AVERROR(ENOMEM);
711             goto fail;
712         }
713         hls->vtt_m3u8_name = av_malloc(vtt_basename_size);
714         if (!hls->vtt_m3u8_name ) {
715             ret = AVERROR(ENOMEM);
716             goto fail;
717         }
718         av_strlcpy(hls->vtt_basename, s->filename, vtt_basename_size);
719         p = strrchr(hls->vtt_basename, '.');
720         if (p)
721             *p = '\0';
722
723         if( hls->subtitle_filename ) {
724             strcpy(hls->vtt_m3u8_name, hls->subtitle_filename);
725         } else {
726             strcpy(hls->vtt_m3u8_name, hls->vtt_basename);
727             av_strlcat(hls->vtt_m3u8_name, "_vtt.m3u8", vtt_basename_size);
728         }
729         av_strlcat(hls->vtt_basename, vtt_pattern, vtt_basename_size);
730     }
731
732     if ((ret = hls_mux_init(s)) < 0)
733         goto fail;
734
735     if ((ret = hls_start(s)) < 0)
736         goto fail;
737
738     av_dict_copy(&options, hls->format_options, 0);
739     ret = avformat_write_header(hls->avf, &options);
740     if (av_dict_count(options)) {
741         av_log(s, AV_LOG_ERROR, "Some of provided format options in '%s' are not recognized\n", hls->format_options_str);
742         ret = AVERROR(EINVAL);
743         goto fail;
744     }
745     //av_assert0(s->nb_streams == hls->avf->nb_streams);
746     for (i = 0; i < s->nb_streams; i++) {
747         AVStream *inner_st;
748         AVStream *outer_st = s->streams[i];
749         if (outer_st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
750             inner_st = hls->avf->streams[i];
751         else if (hls->vtt_avf)
752             inner_st = hls->vtt_avf->streams[0];
753         else {
754             /* We have a subtitle stream, when the user does not want one */
755             inner_st = NULL;
756             continue;
757         }
758         avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
759     }
760 fail:
761
762     av_dict_free(&options);
763     if (ret < 0) {
764         av_freep(&hls->basename);
765         av_freep(&hls->vtt_basename);
766         if (hls->avf)
767             avformat_free_context(hls->avf);
768         if (hls->vtt_avf)
769             avformat_free_context(hls->vtt_avf);
770
771     }
772     return ret;
773 }
774
775 static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
776 {
777     HLSContext *hls = s->priv_data;
778     AVFormatContext *oc = NULL;
779     AVStream *st = s->streams[pkt->stream_index];
780     int64_t end_pts = hls->recording_time * hls->number;
781     int is_ref_pkt = 1;
782     int ret, can_split = 1;
783     int stream_index = 0;
784
785     if( st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE ) {
786         oc = hls->vtt_avf;
787         stream_index = 0;
788     } else {
789         oc = hls->avf;
790         stream_index = pkt->stream_index;
791     }
792     if (hls->start_pts == AV_NOPTS_VALUE) {
793         hls->start_pts = pkt->pts;
794         hls->end_pts   = pkt->pts;
795     }
796
797     if (hls->has_video) {
798         can_split = st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
799                     pkt->flags & AV_PKT_FLAG_KEY;
800         is_ref_pkt = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
801     }
802     if (pkt->pts == AV_NOPTS_VALUE)
803         is_ref_pkt = can_split = 0;
804
805     if (is_ref_pkt)
806         hls->duration = (double)(pkt->pts - hls->end_pts)
807                                    * st->time_base.num / st->time_base.den;
808
809     if (can_split && av_compare_ts(pkt->pts - hls->start_pts, st->time_base,
810                                    end_pts, AV_TIME_BASE_Q) >= 0) {
811         int64_t new_start_pos;
812         av_write_frame(oc, NULL); /* Flush any buffered data */
813
814         new_start_pos = avio_tell(hls->avf->pb);
815         hls->size = new_start_pos - hls->start_pos;
816         ret = hls_append_segment(s, hls, hls->duration, hls->start_pos, hls->size);
817         hls->start_pos = new_start_pos;
818         if (ret < 0)
819             return ret;
820
821         hls->end_pts = pkt->pts;
822         hls->duration = 0;
823
824         if (hls->flags & HLS_SINGLE_FILE) {
825             if (hls->avf->oformat->priv_class && hls->avf->priv_data)
826                 av_opt_set(hls->avf->priv_data, "mpegts_flags", "resend_headers", 0);
827             hls->number++;
828         } else {
829             ff_format_io_close(s, &oc->pb);
830             if (hls->vtt_avf)
831                 ff_format_io_close(s, &hls->vtt_avf->pb);
832
833             ret = hls_start(s);
834         }
835
836         if (ret < 0)
837             return ret;
838
839         if( st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE )
840             oc = hls->vtt_avf;
841         else
842         oc = hls->avf;
843
844         if ((ret = hls_window(s, 0)) < 0)
845             return ret;
846     }
847
848     ret = ff_write_chained(oc, stream_index, pkt, s, 0);
849
850     return ret;
851 }
852
853 static int hls_write_trailer(struct AVFormatContext *s)
854 {
855     HLSContext *hls = s->priv_data;
856     AVFormatContext *oc = hls->avf;
857     AVFormatContext *vtt_oc = hls->vtt_avf;
858
859     av_write_trailer(oc);
860     if (oc->pb) {
861         hls->size = avio_tell(hls->avf->pb) - hls->start_pos;
862         ff_format_io_close(s, &oc->pb);
863         hls_append_segment(s, hls, hls->duration, hls->start_pos, hls->size);
864     }
865
866     if (vtt_oc) {
867         if (vtt_oc->pb)
868             av_write_trailer(vtt_oc);
869         hls->size = avio_tell(hls->vtt_avf->pb) - hls->start_pos;
870         ff_format_io_close(s, &vtt_oc->pb);
871     }
872     av_freep(&hls->basename);
873     avformat_free_context(oc);
874
875     if (vtt_oc) {
876         av_freep(&hls->vtt_basename);
877         av_freep(&hls->vtt_m3u8_name);
878         avformat_free_context(vtt_oc);
879     }
880
881     hls->avf = NULL;
882     hls_window(s, 1);
883
884     hls_free_segments(hls->segments);
885     hls_free_segments(hls->old_segments);
886     return 0;
887 }
888
889 #define OFFSET(x) offsetof(HLSContext, x)
890 #define E AV_OPT_FLAG_ENCODING_PARAM
891 static const AVOption options[] = {
892     {"start_number",  "set first number in the sequence",        OFFSET(start_sequence),AV_OPT_TYPE_INT64,  {.i64 = 0},     0, INT64_MAX, E},
893     {"hls_time",      "set segment length in seconds",           OFFSET(time),    AV_OPT_TYPE_FLOAT,  {.dbl = 2},     0, FLT_MAX, E},
894     {"hls_list_size", "set maximum number of playlist entries",  OFFSET(max_nb_segments),    AV_OPT_TYPE_INT,    {.i64 = 5},     0, INT_MAX, E},
895     {"hls_ts_options","set hls mpegts list of options for the container format used for hls", OFFSET(format_options_str), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
896     {"hls_vtt_options","set hls vtt list of options for the container format used for hls", OFFSET(vtt_format_options_str), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
897     {"hls_wrap",      "set number after which the index wraps",  OFFSET(wrap),    AV_OPT_TYPE_INT,    {.i64 = 0},     0, INT_MAX, E},
898     {"hls_allow_cache", "explicitly set whether the client MAY (1) or MUST NOT (0) cache media segments", OFFSET(allowcache), AV_OPT_TYPE_INT, {.i64 = -1}, INT_MIN, INT_MAX, E},
899     {"hls_base_url",  "url to prepend to each playlist entry",   OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E},
900     {"hls_segment_filename", "filename template for segment files", OFFSET(segment_filename),   AV_OPT_TYPE_STRING, {.str = NULL},            0,       0,         E},
901     {"hls_key_info_file",    "file with key URI and key file path", OFFSET(key_info_file),      AV_OPT_TYPE_STRING, {.str = NULL},            0,       0,         E},
902     {"hls_subtitle_path",     "set path of hls subtitles", OFFSET(subtitle_filename), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
903     {"hls_flags",     "set flags affecting HLS playlist and media file generation", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0 }, 0, UINT_MAX, E, "flags"},
904     {"single_file",   "generate a single media file indexed with byte ranges", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SINGLE_FILE }, 0, UINT_MAX,   E, "flags"},
905     {"delete_segments", "delete segment files that are no longer part of the playlist", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_DELETE_SEGMENTS }, 0, UINT_MAX,   E, "flags"},
906     {"round_durations", "round durations in m3u8 to whole numbers", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_ROUND_DURATIONS }, 0, UINT_MAX,   E, "flags"},
907     {"discont_start", "start the playlist with a discontinuity tag", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_DISCONT_START }, 0, UINT_MAX,   E, "flags"},
908     {"omit_endlist", "Do not append an endlist when ending stream", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_OMIT_ENDLIST }, 0, UINT_MAX,   E, "flags"},
909     {"use_localtime", "set filename expansion with strftime at segment creation", OFFSET(use_localtime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
910     {"use_localtime_mkdir", "create last directory component in strftime-generated filename", OFFSET(use_localtime_mkdir), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
911     {"method", "set the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
912
913     { NULL },
914 };
915
916 static const AVClass hls_class = {
917     .class_name = "hls muxer",
918     .item_name  = av_default_item_name,
919     .option     = options,
920     .version    = LIBAVUTIL_VERSION_INT,
921 };
922
923
924 AVOutputFormat ff_hls_muxer = {
925     .name           = "hls",
926     .long_name      = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
927     .extensions     = "m3u8",
928     .priv_data_size = sizeof(HLSContext),
929     .audio_codec    = AV_CODEC_ID_AAC,
930     .video_codec    = AV_CODEC_ID_H264,
931     .subtitle_codec = AV_CODEC_ID_WEBVTT,
932     .flags          = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
933     .write_header   = hls_write_header,
934     .write_packet   = hls_write_packet,
935     .write_trailer  = hls_write_trailer,
936     .priv_class     = &hls_class,
937 };