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