Libav
hlsenc.c
Go to the documentation of this file.
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;
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
58  char *basename;
59  char *baseurl;
61 } HLSContext;
62 
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;
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);
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 
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 
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 +=
205 
206  if (hls->has_video > 1)
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) {
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)
249  }
250  return ret;
251 }
252 
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);
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 
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_AAC,
346  .video_codec = AV_CODEC_ID_H264,
351  .priv_class = &hls_class,
352 };
float time
Definition: hlsenc.c:47
int wrap
Definition: hlsenc.c:49
void * av_malloc(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:62
Bytestream IO Context.
Definition: avio.h:68
int size
char * basename
Definition: hlsenc.c:58
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1163
AVOption.
Definition: opt.h:234
struct ListEntry * next
Definition: hlsenc.c:37
static int hls_write_trailer(struct AVFormatContext *s)
Definition: hlsenc.c:304
int avformat_write_header(AVFormatContext *s, AVDictionary **options)
Allocate the stream private data and write the stream header to an output media file.
Definition: mux.c:238
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file.
Definition: mux.c:365
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:129
static int write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: assenc.c:58
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:769
int num
numerator
Definition: rational.h:44
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:295
#define AVFMT_ALLOW_FLUSH
Format allows flushing.
Definition: avformat.h:425
static int append_entry(HLSContext *hls, uint64_t duration)
Definition: hlsenc.c:87
int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src)
Copy the settings of the source AVCodecContext into the destination AVCodecContext.
Definition: options.c:154
static int hls_window(AVFormatContext *s, int last)
Definition: hlsenc.c:129
static int64_t duration
Definition: avplay.c:246
Format I/O context.
Definition: avformat.h:922
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:38
ListEntry * list
Definition: hlsenc.c:56
const char * av_basename(const char *path)
Thread safe basename.
Definition: avstring.c:177
AVOptions.
int64_t end_pts
Definition: hlsenc.c:53
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:2521
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:990
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition: options.c:98
static int flags
Definition: log.c:44
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:139
static int write_trailer(AVFormatContext *s)
Definition: assenc.c:64
struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:941
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1019
static const AVOption options[]
Definition: hlsenc.c:323
static int hls_write_header(AVFormatContext *s)
Definition: hlsenc.c:190
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:186
#define OFFSET(x)
Definition: hlsenc.c:321
#define AVERROR(e)
Definition: error.h:43
AVIOContext * pb
Definition: hlsenc.c:60
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:145
int avio_close(AVIOContext *s)
Close the resource accessed by the AVIOContext s and free it.
Definition: aviobuf.c:811
#define wrap(func)
Definition: neontest.h:62
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:169
int has_video
Definition: hlsenc.c:51
int64_t recording_time
Definition: hlsenc.c:50
#define FFMAX(a, b)
Definition: common.h:55
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition: avstring.c:81
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:979
int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b)
Compare 2 timestamps each in its own timebases.
Definition: mathematics.c:134
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:718
char * baseurl
Definition: hlsenc.c:59
int size
Definition: hlsenc.c:48
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:978
unsigned number
Definition: hlsenc.c:42
static void free_entries(HLSContext *hls)
Definition: hlsenc.c:118
char filename[1024]
input or output filename
Definition: avformat.h:998
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
Definition: mathematics.c:116
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:234
int64_t start_pts
Definition: hlsenc.c:52
Definition: hls.c:96
static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: hlsenc.c:253
const char * name
Definition: avformat.h:446
#define E
Definition: hlsenc.c:322
AVOutputFormat * av_guess_format(const char *short_name, const char *filename, const char *mime_type)
Return the output format in the list of registered output formats which best matches the provided par...
Definition: format.c:104
const AVClass * priv_class
AVClass for the private context.
Definition: avformat.h:474
LIBAVUTIL_VERSION_INT
Definition: eval.c:55
int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
Return in 'buf' the path with 'd' replaced by a number.
Definition: utils.c:2660
if(ac->has_optimized_func)
Stream structure.
Definition: avformat.h:699
NULL
Definition: eval.c:55
int64_t start_sequence
Definition: hlsenc.c:44
enum AVMediaType codec_type
Definition: avcodec.h:1058
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:240
int64_t duration
Definition: hlsenc.c:54
AVIOContext * pb
I/O context.
Definition: avformat.h:964
av_default_item_name
Definition: dnxhdenc.c:52
AVOutputFormat * oformat
Definition: hlsenc.c:45
Describe the class of an AVClass context structure.
Definition: log.h:33
int avio_open2(AVIOContext **s, const char *url, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options)
Create and initialize a AVIOContext for accessing the resource indicated by url.
Definition: aviobuf.c:794
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:2445
int64_t sequence
Definition: hlsenc.c:43
char name[1024]
Definition: hlsenc.c:35
misc parsing utilities
size_t av_strlcat(char *dst, const char *src, size_t size)
Append the string src to the string dst, but to a total length of no more than size - 1 bytes...
Definition: avstring.c:91
static int hls_mux_init(AVFormatContext *s)
Definition: hlsenc.c:63
int nb_entries
Definition: hlsenc.c:55
Main libavformat public API header.
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition: avformat.h:409
int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt, AVFormatContext *src)
Write a packet to another muxer than the one the user originally intended.
Definition: mux.c:628
int den
denominator
Definition: rational.h:45
ListEntry * end_list
Definition: hlsenc.c:57
static int hls_start(AVFormatContext *s)
Definition: hlsenc.c:169
void * priv_data
Format private data.
Definition: avformat.h:950
static const uint8_t start_sequence[]
Definition: rtpdec_h264.c:65
static void write_header(FFV1Context *f)
Definition: ffv1enc.c:380
AVFormatContext * avf
Definition: hlsenc.c:46
AVOutputFormat ff_hls_muxer
Definition: hlsenc.c:340
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition: mux.c:589
#define AVERROR_MUXER_NOT_FOUND
Muxer not found.
Definition: error.h:55
int stream_index
Definition: avcodec.h:975
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:741
static const AVClass hls_class
Definition: hlsenc.c:332
This structure stores compressed data.
Definition: avcodec.h:950
int avio_closep(AVIOContext **s)
Close the resource accessed by the AVIOContext *s, free it and set the pointer pointing to it to NULL...
Definition: aviobuf.c:825
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:212
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:966
int duration
Definition: hlsenc.c:36
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:228
int avio_printf(AVIOContext *s, const char *fmt,...) av_printf_format(2