Libav
smoothstreamingenc.c
Go to the documentation of this file.
1 /*
2  * Live smooth streaming fragmenter
3  * Copyright (c) 2012 Martin Storsjo
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 "config.h"
23 #include <float.h>
24 #if HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27 
28 #include "avformat.h"
29 #include "internal.h"
30 #include "os_support.h"
31 #include "avc.h"
32 #include "url.h"
33 #include "isom.h"
34 
35 #include "libavutil/opt.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/file.h"
38 #include "libavutil/mathematics.h"
39 #include "libavutil/intreadwrite.h"
40 
41 typedef struct Fragment {
42  char file[1024];
43  char infofile[1024];
44  int64_t start_time, duration;
45  int n;
46  int64_t start_pos, size;
47 } Fragment;
48 
49 typedef struct OutputStream {
51  int ctx_inited;
52  char dirname[1024];
53  uint8_t iobuf[32768];
54  URLContext *out; // Current output stream where all output is written
55  URLContext *out2; // Auxiliary output stream where all output is also written
56  URLContext *tail_out; // The actual main output stream, if we're currently seeked back to write elsewhere
57  int64_t tail_pos, cur_pos, cur_start_pos;
58  int packets_written;
59  const char *stream_type_tag;
60  int nb_fragments, fragments_size, fragment_index;
61  Fragment **fragments;
62 
63  const char *fourcc;
64  char *private_str;
66  int audio_tag;
67 
69 } OutputStream;
70 
71 typedef struct SmoothStreamingContext {
72  const AVClass *class; /* Class for private options. */
79  int has_video, has_audio;
81 
84 
85 static int ism_write(void *opaque, uint8_t *buf, int buf_size)
86 {
87  OutputStream *os = opaque;
88  if (os->out)
89  ffurl_write(os->out, buf, buf_size);
90  if (os->out2)
91  ffurl_write(os->out2, buf, buf_size);
92  os->cur_pos += buf_size;
93  if (os->cur_pos >= os->tail_pos)
94  os->tail_pos = os->cur_pos;
95  return buf_size;
96 }
97 
98 static int64_t ism_seek(void *opaque, int64_t offset, int whence)
99 {
100  OutputStream *os = opaque;
101  int i;
102  if (whence != SEEK_SET)
103  return AVERROR(ENOSYS);
104  if (os->tail_out) {
105  if (os->out) {
106  ffurl_close(os->out);
107  }
108  if (os->out2) {
109  ffurl_close(os->out2);
110  }
111  os->out = os->tail_out;
112  os->out2 = NULL;
113  os->tail_out = NULL;
114  }
115  if (offset >= os->cur_start_pos) {
116  if (os->out)
117  ffurl_seek(os->out, offset - os->cur_start_pos, SEEK_SET);
118  os->cur_pos = offset;
119  return offset;
120  }
121  for (i = os->nb_fragments - 1; i >= 0; i--) {
122  Fragment *frag = os->fragments[i];
123  if (offset >= frag->start_pos && offset < frag->start_pos + frag->size) {
124  int ret;
126  os->tail_out = os->out;
127  av_dict_set(&opts, "truncate", "0", 0);
128  ret = ffurl_open(&os->out, frag->file, AVIO_FLAG_WRITE, &os->ctx->interrupt_callback, &opts,
129  os->protocols, NULL);
130  av_dict_free(&opts);
131  if (ret < 0) {
132  os->out = os->tail_out;
133  os->tail_out = NULL;
134  return ret;
135  }
136  av_dict_set(&opts, "truncate", "0", 0);
137  ffurl_open(&os->out2, frag->infofile, AVIO_FLAG_WRITE, &os->ctx->interrupt_callback, &opts,
138  os->protocols, NULL);
139  av_dict_free(&opts);
140  ffurl_seek(os->out, offset - frag->start_pos, SEEK_SET);
141  if (os->out2)
142  ffurl_seek(os->out2, offset - frag->start_pos, SEEK_SET);
143  os->cur_pos = offset;
144  return offset;
145  }
146  }
147  return AVERROR(EIO);
148 }
149 
151 {
152  AVCodecParameters *par = os->ctx->streams[0]->codecpar;
153  uint8_t *ptr = par->extradata;
154  int size = par->extradata_size;
155  int i;
156  if (par->codec_id == AV_CODEC_ID_H264) {
157  ff_avc_write_annexb_extradata(ptr, &ptr, &size);
158  if (!ptr)
159  ptr = par->extradata;
160  }
161  if (!ptr)
162  return;
163  os->private_str = av_mallocz(2*size + 1);
164  if (!os->private_str)
165  goto fail;
166  for (i = 0; i < size; i++)
167  snprintf(&os->private_str[2*i], 3, "%02x", ptr[i]);
168 fail:
169  if (ptr != par->extradata)
170  av_free(ptr);
171 }
172 
173 static void ism_free(AVFormatContext *s)
174 {
176  int i, j;
177 
178  av_freep(&c->protocols);
179 
180  if (!c->streams)
181  return;
182  for (i = 0; i < s->nb_streams; i++) {
183  OutputStream *os = &c->streams[i];
184  ffurl_close(os->out);
185  ffurl_close(os->out2);
186  ffurl_close(os->tail_out);
187  os->out = os->out2 = os->tail_out = NULL;
188  if (os->ctx && os->ctx_inited)
189  av_write_trailer(os->ctx);
190  if (os->ctx && os->ctx->pb)
191  av_free(os->ctx->pb);
192  if (os->ctx)
194  av_free(os->private_str);
195  for (j = 0; j < os->nb_fragments; j++)
196  av_free(os->fragments[j]);
197  av_free(os->fragments);
198  }
199  av_freep(&c->streams);
200 }
201 
202 static void output_chunk_list(OutputStream *os, AVIOContext *out, int final, int skip, int window_size)
203 {
204  int removed = 0, i, start = 0;
205  if (os->nb_fragments <= 0)
206  return;
207  if (os->fragments[0]->n > 0)
208  removed = 1;
209  if (final)
210  skip = 0;
211  if (window_size)
212  start = FFMAX(os->nb_fragments - skip - window_size, 0);
213  for (i = start; i < os->nb_fragments - skip; i++) {
214  Fragment *frag = os->fragments[i];
215  if (!final || removed)
216  avio_printf(out, "<c t=\"%"PRIu64"\" d=\"%"PRIu64"\" />\n", frag->start_time, frag->duration);
217  else
218  avio_printf(out, "<c n=\"%d\" d=\"%"PRIu64"\" />\n", frag->n, frag->duration);
219  }
220 }
221 
222 static int write_manifest(AVFormatContext *s, int final)
223 {
225  AVIOContext *out;
226  char filename[1024], temp_filename[1024];
227  int ret, i, video_chunks = 0, audio_chunks = 0, video_streams = 0, audio_streams = 0;
228  int64_t duration = 0;
229 
230  snprintf(filename, sizeof(filename), "%s/Manifest", s->filename);
231  snprintf(temp_filename, sizeof(temp_filename), "%s/Manifest.tmp", s->filename);
232  ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL);
233  if (ret < 0) {
234  av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
235  return ret;
236  }
237  avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
238  for (i = 0; i < s->nb_streams; i++) {
239  OutputStream *os = &c->streams[i];
240  if (os->nb_fragments > 0) {
241  Fragment *last = os->fragments[os->nb_fragments - 1];
242  duration = last->start_time + last->duration;
243  }
245  video_chunks = os->nb_fragments;
246  video_streams++;
247  } else {
248  audio_chunks = os->nb_fragments;
249  audio_streams++;
250  }
251  }
252  if (!final) {
253  duration = 0;
254  video_chunks = audio_chunks = 0;
255  }
256  if (c->window_size) {
257  video_chunks = FFMIN(video_chunks, c->window_size);
258  audio_chunks = FFMIN(audio_chunks, c->window_size);
259  }
260  avio_printf(out, "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" Duration=\"%"PRIu64"\"", duration);
261  if (!final)
262  avio_printf(out, " IsLive=\"true\" LookAheadFragmentCount=\"%d\" DVRWindowLength=\"0\"", c->lookahead_count);
263  avio_printf(out, ">\n");
264  if (c->has_video) {
265  int last = -1, index = 0;
266  avio_printf(out, "<StreamIndex Type=\"video\" QualityLevels=\"%d\" Chunks=\"%d\" Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n", video_streams, video_chunks);
267  for (i = 0; i < s->nb_streams; i++) {
268  OutputStream *os = &c->streams[i];
270  continue;
271  last = i;
272  avio_printf(out, "<QualityLevel Index=\"%d\" Bitrate=\"%d\" FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" CodecPrivateData=\"%s\" />\n", index, s->streams[i]->codecpar->bit_rate, os->fourcc, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height, os->private_str);
273  index++;
274  }
275  output_chunk_list(&c->streams[last], out, final, c->lookahead_count, c->window_size);
276  avio_printf(out, "</StreamIndex>\n");
277  }
278  if (c->has_audio) {
279  int last = -1, index = 0;
280  avio_printf(out, "<StreamIndex Type=\"audio\" QualityLevels=\"%d\" Chunks=\"%d\" Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n", audio_streams, audio_chunks);
281  for (i = 0; i < s->nb_streams; i++) {
282  OutputStream *os = &c->streams[i];
284  continue;
285  last = i;
286  avio_printf(out, "<QualityLevel Index=\"%d\" Bitrate=\"%d\" FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" BitsPerSample=\"16\" PacketSize=\"%d\" AudioTag=\"%d\" CodecPrivateData=\"%s\" />\n", index, s->streams[i]->codecpar->bit_rate, os->fourcc, s->streams[i]->codecpar->sample_rate, s->streams[i]->codecpar->channels, os->packet_size, os->audio_tag, os->private_str);
287  index++;
288  }
289  output_chunk_list(&c->streams[last], out, final, c->lookahead_count, c->window_size);
290  avio_printf(out, "</StreamIndex>\n");
291  }
292  avio_printf(out, "</SmoothStreamingMedia>\n");
293  avio_flush(out);
294  ff_format_io_close(s, &out);
295  return ff_rename(temp_filename, filename);
296 }
297 
299 {
301  int ret = 0, i;
302  AVOutputFormat *oformat;
303 
304  if (mkdir(s->filename, 0777) == -1 && errno != EEXIST) {
305  ret = AVERROR(errno);
306  goto fail;
307  }
308 
309  oformat = av_guess_format("ismv", NULL, NULL);
310  if (!oformat) {
312  goto fail;
313  }
314 
316  if (!c->protocols) {
317  ret = AVERROR(ENOMEM);
318  goto fail;
319  }
320 
321  c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
322  if (!c->streams) {
323  ret = AVERROR(ENOMEM);
324  goto fail;
325  }
326 
327  for (i = 0; i < s->nb_streams; i++) {
328  OutputStream *os = &c->streams[i];
330  AVStream *st;
332  char buf[10];
333 
334  if (!s->streams[i]->codecpar->bit_rate) {
335  av_log(s, AV_LOG_ERROR, "No bit rate set for stream %d\n", i);
336  ret = AVERROR(EINVAL);
337  goto fail;
338  }
339  snprintf(os->dirname, sizeof(os->dirname), "%s/QualityLevels(%d)", s->filename, s->streams[i]->codecpar->bit_rate);
340  if (mkdir(os->dirname, 0777) == -1 && errno != EEXIST) {
341  ret = AVERROR(errno);
342  goto fail;
343  }
344 
345  os->protocols = c->protocols;
346 
347  ctx = avformat_alloc_context();
348  if (!ctx) {
349  ret = AVERROR(ENOMEM);
350  goto fail;
351  }
352  os->ctx = ctx;
353  ctx->oformat = oformat;
355 
356  if (!(st = avformat_new_stream(ctx, NULL))) {
357  ret = AVERROR(ENOMEM);
358  goto fail;
359  }
362  st->time_base = s->streams[i]->time_base;
363 
364  ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, ism_write, ism_seek);
365  if (!ctx->pb) {
366  ret = AVERROR(ENOMEM);
367  goto fail;
368  }
369 
370  snprintf(buf, sizeof(buf), "%d", c->lookahead_count);
371  av_dict_set(&opts, "ism_lookahead", buf, 0);
372  av_dict_set(&opts, "movflags", "frag_custom", 0);
373  if ((ret = avformat_write_header(ctx, &opts)) < 0) {
374  goto fail;
375  }
376  os->ctx_inited = 1;
377  avio_flush(ctx->pb);
378  av_dict_free(&opts);
379  s->streams[i]->time_base = st->time_base;
380  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
381  c->has_video = 1;
382  os->stream_type_tag = "video";
383  if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
384  os->fourcc = "H264";
385  } else if (st->codecpar->codec_id == AV_CODEC_ID_VC1) {
386  os->fourcc = "WVC1";
387  } else {
388  av_log(s, AV_LOG_ERROR, "Unsupported video codec\n");
389  ret = AVERROR(EINVAL);
390  goto fail;
391  }
392  } else {
393  c->has_audio = 1;
394  os->stream_type_tag = "audio";
395  if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
396  os->fourcc = "AACL";
397  os->audio_tag = 0xff;
398  } else if (st->codecpar->codec_id == AV_CODEC_ID_WMAPRO) {
399  os->fourcc = "WMAP";
400  os->audio_tag = 0x0162;
401  } else {
402  av_log(s, AV_LOG_ERROR, "Unsupported audio codec\n");
403  ret = AVERROR(EINVAL);
404  goto fail;
405  }
406  os->packet_size = st->codecpar->block_align ? st->codecpar->block_align : 4;
407  }
408  get_private_data(os);
409  }
410 
411  if (!c->has_video && c->min_frag_duration <= 0) {
412  av_log(s, AV_LOG_WARNING, "no video stream and no min frag duration set\n");
413  ret = AVERROR(EINVAL);
414  goto fail;
415  }
416  ret = write_manifest(s, 0);
417 
418 fail:
419  if (ret)
420  ism_free(s);
421  return ret;
422 }
423 
424 static int parse_fragment(AVFormatContext *s, const char *filename, int64_t *start_ts, int64_t *duration, int64_t *moof_size, int64_t size)
425 {
426  AVIOContext *in;
427  int ret;
428  uint32_t len;
429  if ((ret = s->io_open(s, &in, filename, AVIO_FLAG_READ, NULL)) < 0)
430  return ret;
431  ret = AVERROR(EIO);
432  *moof_size = avio_rb32(in);
433  if (*moof_size < 8 || *moof_size > size)
434  goto fail;
435  if (avio_rl32(in) != MKTAG('m','o','o','f'))
436  goto fail;
437  len = avio_rb32(in);
438  if (len > *moof_size)
439  goto fail;
440  if (avio_rl32(in) != MKTAG('m','f','h','d'))
441  goto fail;
442  avio_seek(in, len - 8, SEEK_CUR);
443  avio_rb32(in); /* traf size */
444  if (avio_rl32(in) != MKTAG('t','r','a','f'))
445  goto fail;
446  while (avio_tell(in) < *moof_size) {
447  uint32_t len = avio_rb32(in);
448  uint32_t tag = avio_rl32(in);
449  int64_t end = avio_tell(in) + len - 8;
450  if (len < 8 || len >= *moof_size)
451  goto fail;
452  if (tag == MKTAG('u','u','i','d')) {
453  static const uint8_t tfxd[] = {
454  0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
455  0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
456  };
457  uint8_t uuid[16];
458  avio_read(in, uuid, 16);
459  if (!memcmp(uuid, tfxd, 16) && len >= 8 + 16 + 4 + 16) {
460  avio_seek(in, 4, SEEK_CUR);
461  *start_ts = avio_rb64(in);
462  *duration = avio_rb64(in);
463  ret = 0;
464  break;
465  }
466  }
467  avio_seek(in, end, SEEK_SET);
468  }
469 fail:
470  ff_format_io_close(s, &in);
471  return ret;
472 }
473 
474 static int add_fragment(OutputStream *os, const char *file, const char *infofile, int64_t start_time, int64_t duration, int64_t start_pos, int64_t size)
475 {
476  int err;
477  Fragment *frag;
478  if (os->nb_fragments >= os->fragments_size) {
479  os->fragments_size = (os->fragments_size + 1) * 2;
480  if ((err = av_reallocp(&os->fragments, sizeof(*os->fragments) *
481  os->fragments_size)) < 0) {
482  os->fragments_size = 0;
483  os->nb_fragments = 0;
484  return err;
485  }
486  }
487  frag = av_mallocz(sizeof(*frag));
488  if (!frag)
489  return AVERROR(ENOMEM);
490  av_strlcpy(frag->file, file, sizeof(frag->file));
491  av_strlcpy(frag->infofile, infofile, sizeof(frag->infofile));
492  frag->start_time = start_time;
493  frag->duration = duration;
494  frag->start_pos = start_pos;
495  frag->size = size;
496  frag->n = os->fragment_index;
497  os->fragments[os->nb_fragments++] = frag;
498  os->fragment_index++;
499  return 0;
500 }
501 
502 static int copy_moof(AVFormatContext *s, const char* infile, const char *outfile, int64_t size)
503 {
504  AVIOContext *in, *out;
505  int ret = 0;
506  if ((ret = s->io_open(s, &in, infile, AVIO_FLAG_READ, NULL)) < 0)
507  return ret;
508  if ((ret = s->io_open(s, &out, outfile, AVIO_FLAG_WRITE, NULL)) < 0) {
509  ff_format_io_close(s, &in);
510  return ret;
511  }
512  while (size > 0) {
513  uint8_t buf[8192];
514  int n = FFMIN(size, sizeof(buf));
515  n = avio_read(in, buf, n);
516  if (n <= 0) {
517  ret = AVERROR(EIO);
518  break;
519  }
520  avio_write(out, buf, n);
521  size -= n;
522  }
523  avio_flush(out);
524  ff_format_io_close(s, &out);
525  ff_format_io_close(s, &in);
526  return ret;
527 }
528 
529 static int ism_flush(AVFormatContext *s, int final)
530 {
532  int i, ret = 0;
533 
534  for (i = 0; i < s->nb_streams; i++) {
535  OutputStream *os = &c->streams[i];
536  char filename[1024], target_filename[1024], header_filename[1024];
537  int64_t size;
538  int64_t start_ts, duration, moof_size;
539  if (!os->packets_written)
540  continue;
541 
542  snprintf(filename, sizeof(filename), "%s/temp", os->dirname);
543  ret = ffurl_open(&os->out, filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL,
544  c->protocols, NULL);
545  if (ret < 0)
546  break;
547  os->cur_start_pos = os->tail_pos;
548  av_write_frame(os->ctx, NULL);
549  avio_flush(os->ctx->pb);
550  os->packets_written = 0;
551  if (!os->out || os->tail_out)
552  return AVERROR(EIO);
553 
554  ffurl_close(os->out);
555  os->out = NULL;
556  size = os->tail_pos - os->cur_start_pos;
557  if ((ret = parse_fragment(s, filename, &start_ts, &duration, &moof_size, size)) < 0)
558  break;
559  snprintf(header_filename, sizeof(header_filename), "%s/FragmentInfo(%s=%"PRIu64")", os->dirname, os->stream_type_tag, start_ts);
560  snprintf(target_filename, sizeof(target_filename), "%s/Fragments(%s=%"PRIu64")", os->dirname, os->stream_type_tag, start_ts);
561  copy_moof(s, filename, header_filename, moof_size);
562  ret = ff_rename(filename, target_filename);
563  if (ret < 0)
564  break;
565  add_fragment(os, target_filename, header_filename, start_ts, duration,
566  os->cur_start_pos, size);
567  }
568 
569  if (c->window_size || (final && c->remove_at_exit)) {
570  for (i = 0; i < s->nb_streams; i++) {
571  OutputStream *os = &c->streams[i];
572  int j;
573  int remove = os->nb_fragments - c->window_size - c->extra_window_size - c->lookahead_count;
574  if (final && c->remove_at_exit)
575  remove = os->nb_fragments;
576  if (remove > 0) {
577  for (j = 0; j < remove; j++) {
578  unlink(os->fragments[j]->file);
579  unlink(os->fragments[j]->infofile);
580  av_free(os->fragments[j]);
581  }
582  os->nb_fragments -= remove;
583  memmove(os->fragments, os->fragments + remove, os->nb_fragments * sizeof(*os->fragments));
584  }
585  if (final && c->remove_at_exit)
586  rmdir(os->dirname);
587  }
588  }
589 
590  if (ret >= 0)
591  ret = write_manifest(s, final);
592  return ret;
593 }
594 
596 {
598  AVStream *st = s->streams[pkt->stream_index];
599  OutputStream *os = &c->streams[pkt->stream_index];
600  int64_t end_dts = (c->nb_fragments + 1) * (int64_t) c->min_frag_duration;
601  int ret;
602 
603  if (st->first_dts == AV_NOPTS_VALUE)
604  st->first_dts = pkt->dts;
605 
606  if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
607  av_compare_ts(pkt->dts - st->first_dts, st->time_base,
608  end_dts, AV_TIME_BASE_Q) >= 0 &&
609  pkt->flags & AV_PKT_FLAG_KEY && os->packets_written) {
610 
611  if ((ret = ism_flush(s, 0)) < 0)
612  return ret;
613  c->nb_fragments++;
614  }
615 
616  os->packets_written++;
617  return ff_write_chained(os->ctx, 0, pkt, s);
618 }
619 
621 {
623  ism_flush(s, 1);
624 
625  if (c->remove_at_exit) {
626  char filename[1024];
627  snprintf(filename, sizeof(filename), "%s/Manifest", s->filename);
628  unlink(filename);
629  rmdir(s->filename);
630  }
631 
632  ism_free(s);
633  return 0;
634 }
635 
636 #define OFFSET(x) offsetof(SmoothStreamingContext, x)
637 #define E AV_OPT_FLAG_ENCODING_PARAM
638 static const AVOption options[] = {
639  { "window_size", "number of fragments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
640  { "extra_window_size", "number of fragments kept outside of the manifest before removing from disk", OFFSET(extra_window_size), AV_OPT_TYPE_INT, { .i64 = 5 }, 0, INT_MAX, E },
641  { "lookahead_count", "number of lookahead fragments", OFFSET(lookahead_count), AV_OPT_TYPE_INT, { .i64 = 2 }, 0, INT_MAX, E },
642  { "min_frag_duration", "minimum fragment duration (in microseconds)", OFFSET(min_frag_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
643  { "remove_at_exit", "remove all fragments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
644  { NULL },
645 };
646 
647 static const AVClass ism_class = {
648  .class_name = "smooth streaming muxer",
649  .item_name = av_default_item_name,
650  .option = options,
651  .version = LIBAVUTIL_VERSION_INT,
652 };
653 
654 
656  .name = "smoothstreaming",
657  .long_name = NULL_IF_CONFIG_SMALL("Smooth Streaming Muxer"),
658  .priv_data_size = sizeof(SmoothStreamingContext),
659  .audio_codec = AV_CODEC_ID_AAC,
660  .video_codec = AV_CODEC_ID_H264,
665  .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
666  .priv_class = &ism_class,
667 };
static int write_manifest(AVFormatContext *s, int final)
int nb_fragments
Definition: hdsenc.c:54
static int ism_flush(AVFormatContext *s, int final)
int(* io_open)(struct AVFormatContext *s, AVIOContext **pb, const char *url, int flags, AVDictionary **options)
A callback for opening new IO streams.
Definition: avformat.h:1270
char infofile[1024]
int64_t first_dts
Definition: avformat.h:862
Bytestream IO Context.
Definition: avio.h:104
URLContext * tail_out
int64_t start_time
Definition: hdsenc.c:40
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1181
AVOption.
Definition: opt.h:234
static int ism_write(void *opaque, uint8_t *buf, int buf_size)
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:252
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file.
Definition: mux.c:470
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:130
#define OFFSET(x)
static int ism_write_header(AVFormatContext *s)
int ffurl_write(URLContext *h, const unsigned char *buf, int size)
Write size bytes from buf to the resource accessed by h.
Definition: avio.c:257
static void output_chunk_list(OutputStream *os, AVIOContext *out, int final, int skip, int window_size)
int n
Definition: hdsenc.c:41
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: avcodec.h:3483
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:770
static int ism_write_packet(AVFormatContext *s, AVPacket *pkt)
av_log(ac->avr, AV_LOG_TRACE, "%d samples - audio_convert: %s to %s (%s)\, len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt), use_generic ? ac->func_descr_generic :ac->func_descr)
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:242
#define AVIO_FLAG_READ
read-only
Definition: avio.h:368
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:369
URLContext * out
AVFormatContext * ctx
Definition: dashenc.c:61
static void ism_free(AVFormatContext *s)
uint64_t packets_written
Definition: avconv.h:415
This struct describes the properties of an encoded stream.
Definition: avcodec.h:3475
void av_freep(void *arg)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
Definition: mem.c:202
Format I/O context.
Definition: avformat.h:940
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:39
uint8_t
int fragment_index
Definition: hdsenc.c:54
int width
Video only.
Definition: avcodec.h:3525
AVOptions.
miscellaneous OS support macros and functions.
unsigned int avio_rb32(AVIOContext *s)
Definition: aviobuf.c:696
static int add_fragment(OutputStream *os, const char *file, const char *infofile, int64_t start_time, int64_t duration, int64_t start_pos, int64_t size)
char dirname[1024]
void ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
A wrapper around AVFormatContext.io_close that should be used instead of calling the pointer directly...
Definition: utils.c:3317
int ctx_inited
Definition: dashenc.c:62
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:2648
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1008
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition: options.c:136
Misc file utilities.
uint8_t iobuf[32768]
Definition: dashenc.c:63
int ff_avc_write_annexb_extradata(const uint8_t *in, uint8_t **buf, int *size)
Definition: avc.c:164
int av_reallocp(void *ptr, size_t size)
Allocate or reallocate a block of memory.
Definition: mem.c:140
char * protocol_whitelist
A comma-separated list of protocol names that can be used internally by libavformat.
Definition: avformat.h:1294
static int flags
Definition: log.c:50
uint32_t tag
Definition: movenc.c:854
int ffurl_open(URLContext **puc, const char *filename, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options, const URLProtocol **protocols, URLContext *parent)
Create an URLContext for accessing to the resource indicated by url, and open it. ...
Definition: avio.c:175
uint64_t avio_rb64(AVIOContext *s)
Definition: aviobuf.c:761
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:295
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:221
static int write_trailer(AVFormatContext *s)
Definition: assenc.c:64
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:545
struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:959
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1378
#define E
static int ff_rename(const char *oldpath, const char *newpath)
Wrap errno on rename() error.
Definition: internal.h:431
uint8_t iobuf[32768]
Definition: movenc.c:49
AVIOContext * avio_alloc_context(unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int(*read_packet)(void *opaque, uint8_t *buf, int buf_size), int(*write_packet)(void *opaque, uint8_t *buf, int buf_size), int64_t(*seek)(void *opaque, int64_t offset, int whence))
Allocate and initialize an AVIOContext for buffered I/O.
Definition: aviobuf.c:151
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
Copy the contents of src to dst.
Definition: utils.c:2819
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:124
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:190
unsigned int avio_rl32(AVIOContext *s)
Definition: aviobuf.c:665
#define AVERROR(e)
Definition: error.h:43
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:148
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values. ...
Definition: dict.c:175
enum AVMediaType codec_type
General type of the encoded data.
Definition: avcodec.h:3479
static const AVOption options[]
URLContext * out2
static const AVClass ism_class
static int parse_fragment(AVFormatContext *s, const char *filename, int64_t *start_ts, int64_t *duration, int64_t *moof_size, int64_t size)
#define FFMAX(a, b)
Definition: common.h:64
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
#define fail()
Definition: checkasm.h:80
const AVCodecTag ff_mp4_obj_type[]
Definition: isom.c:34
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1352
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:104
int extradata_size
Size of the extradata content in bytes.
Definition: avcodec.h:3501
int bit_rate
The average bitrate of the encoded data (in bits per second).
Definition: avcodec.h:3512
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:996
AVDictionary * opts
Definition: movenc.c:50
int block_align
Audio only.
Definition: avcodec.h:3571
int void avio_flush(AVIOContext *s)
Definition: aviobuf.c:236
int64_t start_pos
char filename[1024]
input or output filename
Definition: avformat.h:1016
#define FFMIN(a, b)
Definition: common.h:66
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition: avformat.h:419
const char * name
Definition: avformat.h:450
AVFormatContext * ctx
Definition: movenc.c:48
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
LIBAVUTIL_VERSION_INT
Definition: eval.c:55
Stream structure.
Definition: avformat.h:705
const char * fourcc
int fragments_size
Definition: hdsenc.c:54
NULL
Definition: eval.c:55
const char * stream_type_tag
Fragment ** fragments
Definition: hdsenc.c:55
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:247
AVIOContext * pb
I/O context.
Definition: avformat.h:982
av_default_item_name
Definition: dnxhdenc.c:55
static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost)
Definition: avconv.c:278
static int64_t ism_seek(void *opaque, int64_t offset, int whence)
int64_t duration
Definition: hdsenc.c:40
const URLProtocol ** protocols
Definition: url.h:38
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:68
uint8_t pi<< 24) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_U8, uint8_t,(*(const uint8_t *) pi - 0x80) *(1.0f/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_U8, uint8_t,(*(const uint8_t *) pi - 0x80) *(1.0/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S16, int16_t,(*(const int16_t *) pi >> 8)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S16, int16_t, *(const int16_t *) pi *(1.0f/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S16, int16_t, *(const int16_t *) pi *(1.0/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S32, int32_t,(*(const int32_t *) pi >> 24)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S32, int32_t, *(const int32_t *) pi *(1.0f/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S32, int32_t, *(const int32_t *) pi *(1.0/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_FLT, float, av_clip_uint8(lrintf(*(const float *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_FLT, float, av_clip_int16(lrintf(*(const float *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_FLT, float, av_clipl_int32(llrintf(*(const float *) pi *(1U<< 31)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_DBL, double, av_clip_uint8(lrint(*(const double *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_DBL, double, av_clip_int16(lrint(*(const double *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_DBL, double, av_clipl_int32(llrint(*(const double *) pi *(1U<< 31)))) #define SET_CONV_FUNC_GROUP(ofmt, ifmt) static void set_generic_function(AudioConvert *ac) { } void ff_audio_convert_free(AudioConvert **ac) { if(! *ac) return;ff_dither_free(&(*ac) ->dc);av_freep(ac);} AudioConvert *ff_audio_convert_alloc(AVAudioResampleContext *avr, enum AVSampleFormat out_fmt, enum AVSampleFormat in_fmt, int channels, int sample_rate, int apply_map) { AudioConvert *ac;int in_planar, out_planar;ac=av_mallocz(sizeof(*ac));if(!ac) return NULL;ac->avr=avr;ac->out_fmt=out_fmt;ac->in_fmt=in_fmt;ac->channels=channels;ac->apply_map=apply_map;if(avr->dither_method !=AV_RESAMPLE_DITHER_NONE &&av_get_packed_sample_fmt(out_fmt)==AV_SAMPLE_FMT_S16 &&av_get_bytes_per_sample(in_fmt) > 2) { ac->dc=ff_dither_alloc(avr, out_fmt, in_fmt, channels, sample_rate, apply_map);if(!ac->dc) { av_free(ac);return NULL;} return ac;} in_planar=ff_sample_fmt_is_planar(in_fmt, channels);out_planar=ff_sample_fmt_is_planar(out_fmt, channels);if(in_planar==out_planar) { ac->func_type=CONV_FUNC_TYPE_FLAT;ac->planes=in_planar ? ac->channels :1;} else if(in_planar) ac->func_type=CONV_FUNC_TYPE_INTERLEAVE;else ac->func_type=CONV_FUNC_TYPE_DEINTERLEAVE;set_generic_function(ac);if(ARCH_AARCH64) ff_audio_convert_init_aarch64(ac);if(ARCH_ARM) ff_audio_convert_init_arm(ac);if(ARCH_X86) ff_audio_convert_init_x86(ac);return ac;} int ff_audio_convert(AudioConvert *ac, AudioData *out, AudioData *in) { int use_generic=1;int len=in->nb_samples;int p;if(ac->dc) { av_log(ac->avr, AV_LOG_TRACE, "%d samples - audio_convert: %s to %s (dithered)\", len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt));return ff_convert_dither(ac-> in
Describe the class of an AVClass context structure.
Definition: log.h:34
int index
Definition: gxfenc.c:72
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:2594
static int ism_write_trailer(AVFormatContext *s)
AVOutputFormat ff_smoothstreaming_muxer
int ffurl_close(URLContext *h)
Close the resource accessed by the URLContext h, and free the memory used by it.
Definition: avio.c:280
int sample_rate
Audio only.
Definition: avcodec.h:3564
static int copy_moof(AVFormatContext *s, const char *infile, const char *outfile, int64_t size)
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:412
int64_t ffurl_seek(URLContext *h, int64_t pos, int whence)
Change the position that will be used by the next read/write operation on the resource accessed by h...
Definition: avio.c:270
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:755
int len
void * priv_data
Format private data.
Definition: avformat.h:968
static void write_header(FFV1Context *f)
Definition: ffv1enc.c:373
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: avcodec.h:3497
int channels
Audio only.
Definition: avcodec.h:3560
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1345
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition: mux.c:714
char * protocol_blacklist
A comma-separated list of protocol names that will not be used internally by libavformat.
Definition: avformat.h:1285
FILE * out
Definition: movenc.c:54
const URLProtocol ** protocols
unbuffered private I/O API
#define AVERROR_MUXER_NOT_FOUND
Muxer not found.
Definition: error.h:55
static void get_private_data(OutputStream *os)
AVCodecParameters * codecpar
Definition: avformat.h:831
AVIOContext * out
Definition: dashenc.c:64
int stream_index
Definition: avcodec.h:1348
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:742
#define MKTAG(a, b, c, d)
Definition: common.h:256
const URLProtocol ** ffurl_get_protocols(const char *whitelist, const char *blacklist)
Construct a list of protocols matching a given whitelist and/or blacklist.
Definition: protocols.c:98
This structure stores compressed data.
Definition: avcodec.h:1323
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:211
char file[1024]
Definition: hdsenc.c:39
FILE * outfile
Definition: audiogen.c:96
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:235
int avio_printf(AVIOContext *s, const char *fmt,...) av_printf_format(2