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