]> git.sesse.net Git - ffmpeg/blob - libavformat/hlsenc.c
Merge remote-tracking branch 'qatar/master'
[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 <float.h>
23
24 #include "libavutil/mathematics.h"
25 #include "libavutil/parseutils.h"
26 #include "libavutil/avstring.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/log.h"
29
30 #include "avformat.h"
31 #include "internal.h"
32
33 typedef struct ListEntry {
34     char  name[1024];
35     int   duration;
36     struct ListEntry *next;
37 } ListEntry;
38
39 typedef struct HLSContext {
40     const AVClass *class;  // Class for private options.
41     unsigned number;
42     int64_t sequence;
43     AVOutputFormat *oformat;
44     AVFormatContext *avf;
45     float time;            // Set by a private option.
46     int  size;             // Set by a private option.
47     int  wrap;             // Set by a private option.
48     int64_t recording_time;
49     int has_video;
50     int64_t start_pts;
51     int64_t end_pts;
52     int nb_entries;
53     ListEntry *list;
54     ListEntry *end_list;
55     char *basename;
56     AVIOContext *pb;
57 } HLSContext;
58
59 static int hls_mux_init(AVFormatContext *s)
60 {
61     HLSContext *hls = s->priv_data;
62     AVFormatContext *oc;
63     int i;
64
65     hls->avf = oc = avformat_alloc_context();
66     if (!oc)
67         return AVERROR(ENOMEM);
68
69     oc->oformat            = hls->oformat;
70     oc->interrupt_callback = s->interrupt_callback;
71
72     for (i = 0; i < s->nb_streams; i++) {
73         AVStream *st;
74         if (!(st = avformat_new_stream(oc, NULL)))
75             return AVERROR(ENOMEM);
76         avcodec_copy_context(st->codec, s->streams[i]->codec);
77         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
78     }
79
80     return 0;
81 }
82
83 static int append_entry(HLSContext *hls, uint64_t duration)
84 {
85     ListEntry *en = av_malloc(sizeof(*en));
86
87     if (!en)
88         return AVERROR(ENOMEM);
89
90     av_strlcpy(en->name, av_basename(hls->avf->filename), sizeof(en->name));
91
92     en->duration = duration;
93     en->next     = NULL;
94
95     if (!hls->list)
96         hls->list = en;
97     else
98         hls->end_list->next = en;
99
100     hls->end_list = en;
101
102     if (hls->nb_entries >= hls->size) {
103         en = hls->list;
104         hls->list = en->next;
105         av_free(en);
106     } else
107         hls->nb_entries++;
108
109     hls->sequence++;
110
111     return 0;
112 }
113
114 static void free_entries(HLSContext *hls)
115 {
116     ListEntry *p = hls->list, *en;
117
118     while(p) {
119         en = p;
120         p = p->next;
121         av_free(en);
122     }
123 }
124
125 static int hls_window(AVFormatContext *s, int last)
126 {
127     HLSContext *hls = s->priv_data;
128     ListEntry *en;
129     int target_duration = 0;
130     int ret = 0;
131
132     if ((ret = avio_open2(&hls->pb, s->filename, AVIO_FLAG_WRITE,
133                           &s->interrupt_callback, NULL)) < 0)
134         goto fail;
135
136     for (en = hls->list; en; en = en->next) {
137         if (target_duration < en->duration)
138             target_duration = en->duration;
139     }
140
141     avio_printf(hls->pb, "#EXTM3U\n");
142     avio_printf(hls->pb, "#EXT-X-VERSION:3\n");
143     avio_printf(hls->pb, "#EXT-X-TARGETDURATION:%d\n", target_duration);
144     avio_printf(hls->pb, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
145                 FFMAX(0, hls->sequence - hls->size));
146
147     for (en = hls->list; en; en = en->next) {
148         avio_printf(hls->pb, "#EXTINF:%d,\n", en->duration);
149         avio_printf(hls->pb, "%s\n", en->name);
150     }
151
152     if (last)
153         avio_printf(hls->pb, "#EXT-X-ENDLIST\n");
154
155 fail:
156     avio_closep(&hls->pb);
157     return ret;
158 }
159
160 static int hls_start(AVFormatContext *s)
161 {
162     HLSContext *c = s->priv_data;
163     AVFormatContext *oc = c->avf;
164     int err = 0;
165
166     if (c->wrap)
167         c->number %= c->wrap;
168
169     if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
170                               c->basename, c->number++) < 0) {
171         av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", c->basename);
172         return AVERROR(EINVAL);
173     }
174
175     if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
176                           &s->interrupt_callback, NULL)) < 0)
177         return err;
178
179     if (oc->oformat->priv_class && oc->priv_data)
180         av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
181
182     return 0;
183 }
184
185 static int hls_write_header(AVFormatContext *s)
186 {
187     HLSContext *hls = s->priv_data;
188     int ret, i;
189     char *p;
190     const char *pattern = "%d.ts";
191     int basename_size = strlen(s->filename) + strlen(pattern) + 1;
192
193     hls->number      = 0;
194
195     hls->recording_time = hls->time * AV_TIME_BASE;
196     hls->start_pts      = AV_NOPTS_VALUE;
197
198     for (i = 0; i < s->nb_streams; i++)
199         hls->has_video +=
200             s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO;
201
202     if (hls->has_video > 1)
203         av_log(s, AV_LOG_WARNING,
204                "More than a single video stream present, "
205                "expect issues decoding it.\n");
206
207     hls->oformat = av_guess_format("mpegts", NULL, NULL);
208
209     if (!hls->oformat) {
210         ret = AVERROR_MUXER_NOT_FOUND;
211         goto fail;
212     }
213
214     hls->basename = av_malloc(basename_size);
215
216     if (!hls->basename) {
217         ret = AVERROR(ENOMEM);
218         goto fail;
219     }
220
221     strcpy(hls->basename, s->filename);
222
223     p = strrchr(hls->basename, '.');
224
225     if (p)
226         *p = '\0';
227
228     av_strlcat(hls->basename, pattern, basename_size);
229
230     if ((ret = hls_mux_init(s)) < 0)
231         goto fail;
232
233     if ((ret = hls_start(s)) < 0)
234         goto fail;
235
236     if ((ret = avformat_write_header(hls->avf, NULL)) < 0)
237         return ret;
238
239
240 fail:
241     if (ret) {
242         av_free(hls->basename);
243         if (hls->avf)
244             avformat_free_context(hls->avf);
245     }
246     return ret;
247 }
248
249 static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
250 {
251     HLSContext *hls = s->priv_data;
252     AVFormatContext *oc = hls->avf;
253     AVStream *st = s->streams[pkt->stream_index];
254     int64_t end_pts = hls->recording_time * hls->number;
255     int ret;
256
257     if (hls->start_pts == AV_NOPTS_VALUE) {
258         hls->start_pts = pkt->pts;
259         hls->end_pts   = pkt->pts;
260     }
261
262     if ((hls->has_video && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)      &&
263         av_compare_ts(pkt->pts - hls->start_pts, st->time_base,
264                       end_pts, AV_TIME_BASE_Q) >= 0 &&
265         pkt->flags & AV_PKT_FLAG_KEY) {
266
267         ret = append_entry(hls, av_rescale(pkt->pts - hls->end_pts,
268                                            st->time_base.num,
269                                            st->time_base.den));
270         if (ret)
271             return ret;
272
273         hls->end_pts = pkt->pts;
274
275         av_write_frame(oc, NULL); /* Flush any buffered data */
276         avio_close(oc->pb);
277
278         ret = hls_start(s);
279
280         if (ret)
281             return ret;
282
283         oc = hls->avf;
284
285         if ((ret = hls_window(s, 0)) < 0)
286             return ret;
287     }
288
289     ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
290
291     return ret;
292 }
293
294 static int hls_write_trailer(struct AVFormatContext *s)
295 {
296     HLSContext *hls = s->priv_data;
297     AVFormatContext *oc = hls->avf;
298
299     av_write_trailer(oc);
300     avio_closep(&oc->pb);
301     avformat_free_context(oc);
302     av_free(hls->basename);
303     hls_window(s, 1);
304
305     free_entries(hls);
306     avio_close(hls->pb);
307     return 0;
308 }
309
310 #define OFFSET(x) offsetof(HLSContext, x)
311 #define E AV_OPT_FLAG_ENCODING_PARAM
312 static const AVOption options[] = {
313     {"start_number",  "set first number in the sequence",        OFFSET(sequence),AV_OPT_TYPE_INT64,  {.i64 = 0},     0, INT64_MAX, E},
314     {"hls_time",      "set segment length in seconds",           OFFSET(time),    AV_OPT_TYPE_FLOAT,  {.dbl = 2},     0, FLT_MAX, E},
315     {"hls_list_size", "set maximum number of playlist entries",  OFFSET(size),    AV_OPT_TYPE_INT,    {.i64 = 5},     0, INT_MAX, E},
316     {"hls_wrap",      "set number after which the index wraps",  OFFSET(wrap),    AV_OPT_TYPE_INT,    {.i64 = 0},     0, INT_MAX, E},
317     { NULL },
318 };
319
320 static const AVClass hls_class = {
321     .class_name = "hls muxer",
322     .item_name  = av_default_item_name,
323     .option     = options,
324     .version    = LIBAVUTIL_VERSION_INT,
325 };
326
327
328 AVOutputFormat ff_hls_muxer = {
329     .name           = "hls",
330     .long_name      = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
331     .extensions     = "m3u8",
332     .priv_data_size = sizeof(HLSContext),
333     .audio_codec    = AV_CODEC_ID_MP2,
334     .video_codec    = AV_CODEC_ID_MPEG2VIDEO,
335     .flags          = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
336     .write_header   = hls_write_header,
337     .write_packet   = hls_write_packet,
338     .write_trailer  = hls_write_trailer,
339     .priv_class     = &hls_class,
340 };