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;
46  float time; // Set by a private option.
47  int size; // Set by a private option.
48  int wrap; // Set by a private option.
49  int64_t recording_time;
50  int has_video;
51  int64_t start_pts;
52  int64_t end_pts;
53  int64_t duration; // last segment duration computed so far, in seconds
57  char *basename;
59 } HLSContext;
60 
62 {
63  HLSContext *hls = s->priv_data;
64  AVFormatContext *oc;
65  int i;
66 
67  hls->avf = oc = avformat_alloc_context();
68  if (!oc)
69  return AVERROR(ENOMEM);
70 
71  oc->oformat = hls->oformat;
73 
74  for (i = 0; i < s->nb_streams; i++) {
75  AVStream *st;
76  if (!(st = avformat_new_stream(oc, NULL)))
77  return AVERROR(ENOMEM);
80  }
81 
82  return 0;
83 }
84 
85 static int append_entry(HLSContext *hls, uint64_t duration)
86 {
87  ListEntry *en = av_malloc(sizeof(*en));
88 
89  if (!en)
90  return AVERROR(ENOMEM);
91 
92  av_strlcpy(en->name, av_basename(hls->avf->filename), sizeof(en->name));
93 
94  en->duration = duration;
95  en->next = NULL;
96 
97  if (!hls->list)
98  hls->list = en;
99  else
100  hls->end_list->next = en;
101 
102  hls->end_list = en;
103 
104  if (hls->nb_entries >= hls->size) {
105  en = hls->list;
106  hls->list = en->next;
107  av_free(en);
108  } else
109  hls->nb_entries++;
110 
111  hls->sequence++;
112 
113  return 0;
114 }
115 
116 static void free_entries(HLSContext *hls)
117 {
118  ListEntry *p = hls->list, *en;
119 
120  while(p) {
121  en = p;
122  p = p->next;
123  av_free(en);
124  }
125 }
126 
127 static int hls_window(AVFormatContext *s, int last)
128 {
129  HLSContext *hls = s->priv_data;
130  ListEntry *en;
131  int target_duration = 0;
132  int ret = 0;
133 
134  if ((ret = avio_open2(&hls->pb, s->filename, AVIO_FLAG_WRITE,
135  &s->interrupt_callback, NULL)) < 0)
136  goto fail;
137 
138  for (en = hls->list; en; en = en->next) {
139  if (target_duration < en->duration)
140  target_duration = en->duration;
141  }
142 
143  avio_printf(hls->pb, "#EXTM3U\n");
144  avio_printf(hls->pb, "#EXT-X-VERSION:3\n");
145  avio_printf(hls->pb, "#EXT-X-TARGETDURATION:%d\n", target_duration);
146  avio_printf(hls->pb, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
147  FFMAX(0, hls->sequence - hls->size));
148 
149  for (en = hls->list; en; en = en->next) {
150  avio_printf(hls->pb, "#EXTINF:%d,\n", en->duration);
151  avio_printf(hls->pb, "%s\n", en->name);
152  }
153 
154  if (last)
155  avio_printf(hls->pb, "#EXT-X-ENDLIST\n");
156 
157 fail:
158  avio_closep(&hls->pb);
159  return ret;
160 }
161 
163 {
164  HLSContext *c = s->priv_data;
165  AVFormatContext *oc = c->avf;
166  int err = 0;
167 
168  if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
169  c->basename, c->wrap ? c->number % c->wrap : c->number) < 0)
170  return AVERROR(EINVAL);
171  c->number++;
172 
173  if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
174  &s->interrupt_callback, NULL)) < 0)
175  return err;
176 
177  if (oc->oformat->priv_class && oc->priv_data)
178  av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
179 
180  return 0;
181 }
182 
184 {
185  HLSContext *hls = s->priv_data;
186  int ret, i;
187  char *p;
188  const char *pattern = "%d.ts";
189  int basename_size = strlen(s->filename) + strlen(pattern) + 1;
190 
191  hls->number = 0;
192 
193  hls->recording_time = hls->time * AV_TIME_BASE;
194  hls->start_pts = AV_NOPTS_VALUE;
195 
196  for (i = 0; i < s->nb_streams; i++)
197  hls->has_video +=
199 
200  if (hls->has_video > 1)
202  "More than a single video stream present, "
203  "expect issues decoding it.\n");
204 
205  hls->oformat = av_guess_format("mpegts", NULL, NULL);
206 
207  if (!hls->oformat) {
209  goto fail;
210  }
211 
212  hls->basename = av_malloc(basename_size);
213 
214  if (!hls->basename) {
215  ret = AVERROR(ENOMEM);
216  goto fail;
217  }
218 
219  strcpy(hls->basename, s->filename);
220 
221  p = strrchr(hls->basename, '.');
222 
223  if (p)
224  *p = '\0';
225 
226  av_strlcat(hls->basename, pattern, basename_size);
227 
228  if ((ret = hls_mux_init(s)) < 0)
229  goto fail;
230 
231  if ((ret = hls_start(s)) < 0)
232  goto fail;
233 
234  if ((ret = avformat_write_header(hls->avf, NULL)) < 0)
235  return ret;
236 
237 
238 fail:
239  if (ret) {
240  av_free(hls->basename);
241  if (hls->avf)
243  }
244  return ret;
245 }
246 
248 {
249  HLSContext *hls = s->priv_data;
250  AVFormatContext *oc = hls->avf;
251  AVStream *st = s->streams[pkt->stream_index];
252  int64_t end_pts = hls->recording_time * hls->number;
253  int ret, can_split = 1;
254 
255  if (hls->start_pts == AV_NOPTS_VALUE) {
256  hls->start_pts = pkt->pts;
257  hls->end_pts = pkt->pts;
258  }
259 
260  if (hls->has_video) {
261  can_split = st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
262  pkt->flags & AV_PKT_FLAG_KEY;
263  }
264  if (pkt->pts == AV_NOPTS_VALUE)
265  can_split = 0;
266  else
267  hls->duration = av_rescale(pkt->pts - hls->end_pts,
268  st->time_base.num, st->time_base.den);
269 
270  if (can_split && av_compare_ts(pkt->pts - hls->start_pts, st->time_base,
271  end_pts, AV_TIME_BASE_Q) >= 0) {
272  ret = append_entry(hls, hls->duration);
273  if (ret)
274  return ret;
275 
276  hls->end_pts = pkt->pts;
277  hls->duration = 0;
278 
279  av_write_frame(oc, NULL); /* Flush any buffered data */
280  avio_close(oc->pb);
281 
282  ret = hls_start(s);
283 
284  if (ret)
285  return ret;
286 
287  oc = hls->avf;
288 
289  if ((ret = hls_window(s, 0)) < 0)
290  return ret;
291  }
292 
293  ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
294 
295  return ret;
296 }
297 
298 static int hls_write_trailer(struct AVFormatContext *s)
299 {
300  HLSContext *hls = s->priv_data;
301  AVFormatContext *oc = hls->avf;
302 
303  av_write_trailer(oc);
304  avio_closep(&oc->pb);
306  av_free(hls->basename);
307  append_entry(hls, hls->duration);
308  hls_window(s, 1);
309 
310  free_entries(hls);
311  avio_close(hls->pb);
312  return 0;
313 }
314 
315 #define OFFSET(x) offsetof(HLSContext, x)
316 #define E AV_OPT_FLAG_ENCODING_PARAM
317 static const AVOption options[] = {
318  {"start_number", "first number in the sequence", OFFSET(sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
319  {"hls_time", "segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
320  {"hls_list_size", "maximum number of playlist entries", OFFSET(size), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
321  {"hls_wrap", "number after which the index wraps", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
322  { NULL },
323 };
324 
325 static const AVClass hls_class = {
326  .class_name = "hls muxer",
327  .item_name = av_default_item_name,
328  .option = options,
329  .version = LIBAVUTIL_VERSION_INT,
330 };
331 
332 
334  .name = "hls",
335  .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
336  .extensions = "m3u8",
337  .priv_data_size = sizeof(HLSContext),
338  .audio_codec = AV_CODEC_ID_MP2,
339  .video_codec = AV_CODEC_ID_MPEG2VIDEO,
344  .priv_class = &hls_class,
345 };
float time
Definition: hlsenc.c:46
int wrap
Definition: hlsenc.c:48
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:57
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1097
AVOption.
Definition: opt.h:233
struct ListEntry * next
Definition: hlsenc.c:37
static int hls_write_trailer(struct AVFormatContext *s)
Definition: hlsenc.c:298
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:302
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file.
Definition: mux.c:454
#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:747
int num
numerator
Definition: rational.h:44
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:293
#define AVFMT_ALLOW_FLUSH
Format allows flushing.
Definition: avformat.h:416
static int append_entry(HLSContext *hls, uint64_t duration)
Definition: hlsenc.c:85
int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src)
Copy the settings of the source AVCodecContext into the destination AVCodecContext.
Definition: options.c:138
static int hls_window(AVFormatContext *s, int last)
Definition: hlsenc.c:127
static int64_t duration
Definition: avplay.c:246
Format I/O context.
Definition: avformat.h:871
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:55
const char * av_basename(const char *path)
Thread safe basename.
Definition: avstring.c:177
AVOptions.
int64_t end_pts
Definition: hlsenc.c:52
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:935
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition: options.c:98
static int flags
Definition: log.c:44
static int write_trailer(AVFormatContext *s)
Definition: assenc.c:64
struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:890
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1023
static const AVOption options[]
Definition: hlsenc.c:317
static int hls_write_header(AVFormatContext *s)
Definition: hlsenc.c:183
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:315
#define AVERROR(e)
Definition: error.h:43
AVIOContext * pb
Definition: hlsenc.c:58
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:142
int avio_close(AVIOContext *s)
Close the resource accessed by the AVIOContext s and free it.
Definition: aviobuf.c:794
#define wrap(func)
Definition: neontest.h:62
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:148
AVStream * avformat_new_stream(AVFormatContext *s, AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:2662
int has_video
Definition: hlsenc.c:50
int64_t recording_time
Definition: hlsenc.c:49
#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:127
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:702
int size
Definition: hlsenc.c:47
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:923
unsigned number
Definition: hlsenc.c:42
static void free_entries(HLSContext *hls)
Definition: hlsenc.c:116
char filename[1024]
input or output filename
Definition: avformat.h:943
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:110
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:234
int64_t start_pts
Definition: hlsenc.c:51
Definition: hls.c:96
static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: hlsenc.c:247
const char * name
Definition: avformat.h:437
#define E
Definition: hlsenc.c:316
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:118
const AVClass * priv_class
AVClass for the private context.
Definition: avformat.h:465
preferred ID for MPEG-1/2 video decoding
Definition: avcodec.h:110
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:2959
if(ac->has_optimized_func)
Stream structure.
Definition: avformat.h:683
NULL
Definition: eval.c:55
enum AVMediaType codec_type
Definition: avcodec.h:1062
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:240
int64_t duration
Definition: hlsenc.c:53
AVIOContext * pb
I/O context.
Definition: avformat.h:913
av_default_item_name
Definition: dnxhdenc.c:45
AVOutputFormat * oformat
Definition: hlsenc.c:44
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:777
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:2595
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:61
int nb_entries
Definition: hlsenc.c:54
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:400
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:723
int den
denominator
Definition: rational.h:45
ListEntry * end_list
Definition: hlsenc.c:56
static int hls_start(AVFormatContext *s)
Definition: hlsenc.c:162
void * priv_data
Format private data.
Definition: avformat.h:899
static void write_header(FFV1Context *f)
Definition: ffv1enc.c:380
AVFormatContext * avf
Definition: hlsenc.c:45
AVOutputFormat ff_hls_muxer
Definition: hlsenc.c:333
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition: mux.c:684
#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:719
static const AVClass hls_class
Definition: hlsenc.c:325
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:808
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:210
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