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