FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
segment.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2011, Luca Barbato
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 /**
22  * @file generic segmenter
23  * M3U8 specification can be find here:
24  * @url{http://tools.ietf.org/id/draft-pantos-http-live-streaming}
25  */
26 
27 /* #define DEBUG */
28 
29 #include <float.h>
30 #include <time.h>
31 
32 #include "avformat.h"
33 #include "internal.h"
34 
35 #include "libavutil/avassert.h"
36 #include "libavutil/log.h"
37 #include "libavutil/opt.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/parseutils.h"
40 #include "libavutil/mathematics.h"
41 #include "libavutil/time.h"
43 #include "libavutil/timestamp.h"
44 
45 typedef struct SegmentListEntry {
46  int index;
48  int64_t start_pts;
49  int64_t offset_pts;
50  char *filename;
52  int64_t last_duration;
54 
55 typedef enum {
60  LIST_TYPE_EXT, ///< deprecated
63 } ListType;
64 
65 #define SEGMENT_LIST_FLAG_CACHE 1
66 #define SEGMENT_LIST_FLAG_LIVE 2
67 
68 typedef struct SegmentContext {
69  const AVClass *class; /**< Class for private options. */
70  int segment_idx; ///< index of the segment file to write, starting from 0
71  int segment_idx_wrap; ///< number after which the index wraps
72  int segment_idx_wrap_nb; ///< number of time the index has wraped
73  int segment_count; ///< number of segment files already written
76  char *format; ///< format to use for output segment files
77  char *format_options_str; ///< format options to use for output segment files
79  char *list; ///< filename for the segment list file
80  int list_flags; ///< flags affecting list generation
81  int list_size; ///< number of entries for the segment list file
82 
83  int use_clocktime; ///< flag to cut segments at regular clock time
84  int64_t last_val; ///< remember last time for wrap around detection
85  int64_t last_cut; ///< remember last cut
87 
88  char *entry_prefix; ///< prefix to add to list entry filenames
89  int list_type; ///< set the list type
90  AVIOContext *list_pb; ///< list file put-byte context
91  char *time_str; ///< segment duration specification string
92  int64_t time; ///< segment duration
93  int use_strftime; ///< flag to expand filename with strftime
94 
95  char *times_str; ///< segment times specification string
96  int64_t *times; ///< list of segment interval specification
97  int nb_times; ///< number of elments in the times array
98 
99  char *frames_str; ///< segment frame numbers specification string
100  int *frames; ///< list of frame number specification
101  int nb_frames; ///< number of elments in the frames array
102  int frame_count; ///< total number of reference frames
103  int segment_frame_count; ///< number of reference frames in the segment
104 
105  int64_t time_delta;
106  int individual_header_trailer; /**< Set by a private option. */
107  int write_header_trailer; /**< Set by a private option. */
108  char *header_filename; ///< filename to write the output header to
109 
110  int reset_timestamps; ///< reset timestamps at the begin of each segment
111  int64_t initial_offset; ///< initial timestamps offset, expressed in microseconds
112  char *reference_stream_specifier; ///< reference stream specifier
115 
120 
121 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
122 {
123  int needs_quoting = !!str[strcspn(str, "\",\n\r")];
124 
125  if (needs_quoting)
126  avio_w8(ctx, '"');
127 
128  for (; *str; str++) {
129  if (*str == '"')
130  avio_w8(ctx, '"');
131  avio_w8(ctx, *str);
132  }
133  if (needs_quoting)
134  avio_w8(ctx, '"');
135 }
136 
138 {
139  SegmentContext *seg = s->priv_data;
140  AVFormatContext *oc;
141  int i;
142  int ret;
143 
144  ret = avformat_alloc_output_context2(&seg->avf, seg->oformat, NULL, NULL);
145  if (ret < 0)
146  return ret;
147  oc = seg->avf;
148 
150  oc->max_delay = s->max_delay;
151  av_dict_copy(&oc->metadata, s->metadata, 0);
152 
153  for (i = 0; i < s->nb_streams; i++) {
154  AVStream *st;
155  AVCodecContext *icodec, *ocodec;
156 
157  if (!(st = avformat_new_stream(oc, NULL)))
158  return AVERROR(ENOMEM);
159  icodec = s->streams[i]->codec;
160  ocodec = st->codec;
161  avcodec_copy_context(ocodec, icodec);
162  if (!oc->oformat->codec_tag ||
163  av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == ocodec->codec_id ||
164  av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0) {
165  ocodec->codec_tag = icodec->codec_tag;
166  } else {
167  ocodec->codec_tag = 0;
168  }
170  st->time_base = s->streams[i]->time_base;
171  av_dict_copy(&st->metadata, s->streams[i]->metadata, 0);
172  }
173 
174  return 0;
175 }
176 
178 {
179  SegmentContext *seg = s->priv_data;
180  AVFormatContext *oc = seg->avf;
181  size_t size;
182 
183  if (seg->segment_idx_wrap)
184  seg->segment_idx %= seg->segment_idx_wrap;
185  if (seg->use_strftime) {
186  time_t now0;
187  struct tm *tm, tmpbuf;
188  time(&now0);
189  tm = localtime_r(&now0, &tmpbuf);
190  if (!strftime(oc->filename, sizeof(oc->filename), s->filename, tm)) {
191  av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
192  return AVERROR(EINVAL);
193  }
194  } else if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
195  s->filename, seg->segment_idx) < 0) {
196  av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
197  return AVERROR(EINVAL);
198  }
199 
200  /* copy modified name in list entry */
201  size = strlen(av_basename(oc->filename)) + 1;
202  if (seg->entry_prefix)
203  size += strlen(seg->entry_prefix);
204 
205  seg->cur_entry.filename = av_mallocz(size);
206  if (!seg->cur_entry.filename)
207  return AVERROR(ENOMEM);
208  snprintf(seg->cur_entry.filename, size, "%s%s",
209  seg->entry_prefix ? seg->entry_prefix : "",
210  av_basename(oc->filename));
211 
212  return 0;
213 }
214 
216 {
217  SegmentContext *seg = s->priv_data;
218  AVFormatContext *oc = seg->avf;
219  int err = 0;
220 
221  if (write_header) {
223  seg->avf = NULL;
224  if ((err = segment_mux_init(s)) < 0)
225  return err;
226  oc = seg->avf;
227  }
228 
229  seg->segment_idx++;
230  if ((seg->segment_idx_wrap) && (seg->segment_idx % seg->segment_idx_wrap == 0))
231  seg->segment_idx_wrap_nb++;
232 
233  if ((err = set_segment_filename(s)) < 0)
234  return err;
235 
236  if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
237  &s->interrupt_callback, NULL)) < 0) {
238  av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
239  return err;
240  }
241  if (!seg->individual_header_trailer)
242  oc->pb->seekable = 0;
243 
244  if (oc->oformat->priv_class && oc->priv_data)
245  av_opt_set(oc->priv_data, "mpegts_flags", "+resend_headers", 0);
246 
247  if (write_header) {
248  if ((err = avformat_write_header(oc, NULL)) < 0)
249  return err;
250  }
251 
252  seg->segment_frame_count = 0;
253  return 0;
254 }
255 
257 {
258  SegmentContext *seg = s->priv_data;
259  int ret;
260 
261  ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
262  &s->interrupt_callback, NULL);
263  if (ret < 0) {
264  av_log(s, AV_LOG_ERROR, "Failed to open segment list '%s'\n", seg->list);
265  return ret;
266  }
267 
268  if (seg->list_type == LIST_TYPE_M3U8 && seg->segment_list_entries) {
269  SegmentListEntry *entry;
270  double max_duration = 0;
271 
272  avio_printf(seg->list_pb, "#EXTM3U\n");
273  avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
274  avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_list_entries->index);
275  avio_printf(seg->list_pb, "#EXT-X-ALLOW-CACHE:%s\n",
276  seg->list_flags & SEGMENT_LIST_FLAG_CACHE ? "YES" : "NO");
277 
278  av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n",
280 
281  for (entry = seg->segment_list_entries; entry; entry = entry->next)
282  max_duration = FFMAX(max_duration, entry->end_time - entry->start_time);
283  avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%"PRId64"\n", (int64_t)ceil(max_duration));
284  } else if (seg->list_type == LIST_TYPE_FFCONCAT) {
285  avio_printf(seg->list_pb, "ffconcat version 1.0\n");
286  }
287 
288  return ret;
289 }
290 
291 static void segment_list_print_entry(AVIOContext *list_ioctx,
292  ListType list_type,
293  const SegmentListEntry *list_entry,
294  void *log_ctx)
295 {
296  switch (list_type) {
297  case LIST_TYPE_FLAT:
298  avio_printf(list_ioctx, "%s\n", list_entry->filename);
299  break;
300  case LIST_TYPE_CSV:
301  case LIST_TYPE_EXT:
302  print_csv_escaped_str(list_ioctx, list_entry->filename);
303  avio_printf(list_ioctx, ",%f,%f\n", list_entry->start_time, list_entry->end_time);
304  break;
305  case LIST_TYPE_M3U8:
306  avio_printf(list_ioctx, "#EXTINF:%f,\n%s\n",
307  list_entry->end_time - list_entry->start_time, list_entry->filename);
308  break;
309  case LIST_TYPE_FFCONCAT:
310  {
311  char *buf;
312  if (av_escape(&buf, list_entry->filename, NULL, AV_ESCAPE_MODE_AUTO, AV_ESCAPE_FLAG_WHITESPACE) < 0) {
313  av_log(log_ctx, AV_LOG_WARNING,
314  "Error writing list entry '%s' in list file\n", list_entry->filename);
315  return;
316  }
317  avio_printf(list_ioctx, "file %s\n", buf);
318  av_free(buf);
319  break;
320  }
321  default:
322  av_assert0(!"Invalid list type");
323  }
324 }
325 
326 static int segment_end(AVFormatContext *s, int write_trailer, int is_last)
327 {
328  SegmentContext *seg = s->priv_data;
329  AVFormatContext *oc = seg->avf;
330  int ret = 0;
331 
332  av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
333  if (write_trailer)
334  ret = av_write_trailer(oc);
335 
336  if (ret < 0)
337  av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
338  oc->filename);
339 
340  if (seg->list) {
341  if (seg->list_size || seg->list_type == LIST_TYPE_M3U8) {
342  SegmentListEntry *entry = av_mallocz(sizeof(*entry));
343  if (!entry) {
344  ret = AVERROR(ENOMEM);
345  goto end;
346  }
347 
348  /* append new element */
349  memcpy(entry, &seg->cur_entry, sizeof(*entry));
350  if (!seg->segment_list_entries)
352  else
353  seg->segment_list_entries_end->next = entry;
354  seg->segment_list_entries_end = entry;
355 
356  /* drop first item */
357  if (seg->list_size && seg->segment_count >= seg->list_size) {
358  entry = seg->segment_list_entries;
360  av_freep(&entry->filename);
361  av_freep(&entry);
362  }
363 
364  if ((ret = segment_list_open(s)) < 0)
365  goto end;
366  for (entry = seg->segment_list_entries; entry; entry = entry->next)
367  segment_list_print_entry(seg->list_pb, seg->list_type, entry, s);
368  if (seg->list_type == LIST_TYPE_M3U8 && is_last)
369  avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
370  avio_closep(&seg->list_pb);
371  } else {
372  segment_list_print_entry(seg->list_pb, seg->list_type, &seg->cur_entry, s);
373  avio_flush(seg->list_pb);
374  }
375  }
376 
377  av_log(s, AV_LOG_VERBOSE, "segment:'%s' count:%d ended\n",
378  seg->avf->filename, seg->segment_count);
379  seg->segment_count++;
380 
381 end:
382  avio_closep(&oc->pb);
383 
384  return ret;
385 }
386 
387 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
388  const char *times_str)
389 {
390  char *p;
391  int i, ret = 0;
392  char *times_str1 = av_strdup(times_str);
393  char *saveptr = NULL;
394 
395  if (!times_str1)
396  return AVERROR(ENOMEM);
397 
398 #define FAIL(err) ret = err; goto end
399 
400  *nb_times = 1;
401  for (p = times_str1; *p; p++)
402  if (*p == ',')
403  (*nb_times)++;
404 
405  *times = av_malloc_array(*nb_times, sizeof(**times));
406  if (!*times) {
407  av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
408  FAIL(AVERROR(ENOMEM));
409  }
410 
411  p = times_str1;
412  for (i = 0; i < *nb_times; i++) {
413  int64_t t;
414  char *tstr = av_strtok(p, ",", &saveptr);
415  p = NULL;
416 
417  if (!tstr || !tstr[0]) {
418  av_log(log_ctx, AV_LOG_ERROR, "Empty time specification in times list %s\n",
419  times_str);
420  FAIL(AVERROR(EINVAL));
421  }
422 
423  ret = av_parse_time(&t, tstr, 1);
424  if (ret < 0) {
425  av_log(log_ctx, AV_LOG_ERROR,
426  "Invalid time duration specification '%s' in times list %s\n", tstr, times_str);
427  FAIL(AVERROR(EINVAL));
428  }
429  (*times)[i] = t;
430 
431  /* check on monotonicity */
432  if (i && (*times)[i-1] > (*times)[i]) {
433  av_log(log_ctx, AV_LOG_ERROR,
434  "Specified time %f is greater than the following time %f\n",
435  (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
436  FAIL(AVERROR(EINVAL));
437  }
438  }
439 
440 end:
441  av_free(times_str1);
442  return ret;
443 }
444 
445 static int parse_frames(void *log_ctx, int **frames, int *nb_frames,
446  const char *frames_str)
447 {
448  char *p;
449  int i, ret = 0;
450  char *frames_str1 = av_strdup(frames_str);
451  char *saveptr = NULL;
452 
453  if (!frames_str1)
454  return AVERROR(ENOMEM);
455 
456 #define FAIL(err) ret = err; goto end
457 
458  *nb_frames = 1;
459  for (p = frames_str1; *p; p++)
460  if (*p == ',')
461  (*nb_frames)++;
462 
463  *frames = av_malloc_array(*nb_frames, sizeof(**frames));
464  if (!*frames) {
465  av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced frames array\n");
466  FAIL(AVERROR(ENOMEM));
467  }
468 
469  p = frames_str1;
470  for (i = 0; i < *nb_frames; i++) {
471  long int f;
472  char *tailptr;
473  char *fstr = av_strtok(p, ",", &saveptr);
474 
475  p = NULL;
476  if (!fstr) {
477  av_log(log_ctx, AV_LOG_ERROR, "Empty frame specification in frame list %s\n",
478  frames_str);
479  FAIL(AVERROR(EINVAL));
480  }
481  f = strtol(fstr, &tailptr, 10);
482  if (*tailptr || f <= 0 || f >= INT_MAX) {
483  av_log(log_ctx, AV_LOG_ERROR,
484  "Invalid argument '%s', must be a positive integer <= INT64_MAX\n",
485  fstr);
486  FAIL(AVERROR(EINVAL));
487  }
488  (*frames)[i] = f;
489 
490  /* check on monotonicity */
491  if (i && (*frames)[i-1] > (*frames)[i]) {
492  av_log(log_ctx, AV_LOG_ERROR,
493  "Specified frame %d is greater than the following frame %d\n",
494  (*frames)[i], (*frames)[i-1]);
495  FAIL(AVERROR(EINVAL));
496  }
497  }
498 
499 end:
500  av_free(frames_str1);
501  return ret;
502 }
503 
504 static int open_null_ctx(AVIOContext **ctx)
505 {
506  int buf_size = 32768;
507  uint8_t *buf = av_malloc(buf_size);
508  if (!buf)
509  return AVERROR(ENOMEM);
510  *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
511  if (!*ctx) {
512  av_free(buf);
513  return AVERROR(ENOMEM);
514  }
515  return 0;
516 }
517 
518 static void close_null_ctxp(AVIOContext **pb)
519 {
520  av_freep(&(*pb)->buffer);
521  av_freep(pb);
522 }
523 
525 {
526  SegmentContext *seg = s->priv_data;
527  int ret, i;
528 
529  seg->reference_stream_index = -1;
530  if (!strcmp(seg->reference_stream_specifier, "auto")) {
531  /* select first index of type with highest priority */
532  int type_index_map[AVMEDIA_TYPE_NB];
533  static const enum AVMediaType type_priority_list[] = {
539  };
540  enum AVMediaType type;
541 
542  for (i = 0; i < AVMEDIA_TYPE_NB; i++)
543  type_index_map[i] = -1;
544 
545  /* select first index for each type */
546  for (i = 0; i < s->nb_streams; i++) {
547  type = s->streams[i]->codec->codec_type;
548  if ((unsigned)type < AVMEDIA_TYPE_NB && type_index_map[type] == -1
549  /* ignore attached pictures/cover art streams */
551  type_index_map[type] = i;
552  }
553 
554  for (i = 0; i < FF_ARRAY_ELEMS(type_priority_list); i++) {
555  type = type_priority_list[i];
556  if ((seg->reference_stream_index = type_index_map[type]) >= 0)
557  break;
558  }
559  } else {
560  for (i = 0; i < s->nb_streams; i++) {
563  if (ret < 0)
564  return ret;
565  if (ret > 0) {
566  seg->reference_stream_index = i;
567  break;
568  }
569  }
570  }
571 
572  if (seg->reference_stream_index < 0) {
573  av_log(s, AV_LOG_ERROR, "Could not select stream matching identifier '%s'\n",
575  return AVERROR(EINVAL);
576  }
577 
578  return 0;
579 }
580 
582 {
583  avio_closep(&seg->list_pb);
585  seg->avf = NULL;
586 }
587 
589 {
590  SegmentContext *seg = s->priv_data;
591  AVFormatContext *oc = NULL;
593  int ret;
594  int i;
595 
596  seg->segment_count = 0;
597  if (!seg->write_header_trailer)
598  seg->individual_header_trailer = 0;
599 
600  if (seg->header_filename) {
601  seg->write_header_trailer = 1;
602  seg->individual_header_trailer = 0;
603  }
604 
605  if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) {
606  av_log(s, AV_LOG_ERROR,
607  "segment_time, segment_times, and segment_frames options "
608  "are mutually exclusive, select just one of them\n");
609  return AVERROR(EINVAL);
610  }
611 
612  if (seg->times_str) {
613  if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
614  return ret;
615  } else if (seg->frames_str) {
616  if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
617  return ret;
618  } else {
619  /* set default value if not specified */
620  if (!seg->time_str)
621  seg->time_str = av_strdup("2");
622  if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
623  av_log(s, AV_LOG_ERROR,
624  "Invalid time duration specification '%s' for segment_time option\n",
625  seg->time_str);
626  return ret;
627  }
628  }
629 
630  if (seg->format_options_str) {
631  ret = av_dict_parse_string(&seg->format_options, seg->format_options_str, "=", ":", 0);
632  if (ret < 0) {
633  av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
634  seg->format_options_str);
635  goto fail;
636  }
637  }
638 
639  if (seg->list) {
640  if (seg->list_type == LIST_TYPE_UNDEFINED) {
641  if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
642  else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
643  else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
644  else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
645  else seg->list_type = LIST_TYPE_FLAT;
646  }
647  if (!seg->list_size && seg->list_type != LIST_TYPE_M3U8)
648  if ((ret = segment_list_open(s)) < 0)
649  goto fail;
650  }
651  if (seg->list_type == LIST_TYPE_EXT)
652  av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
653 
654  if ((ret = select_reference_stream(s)) < 0)
655  goto fail;
656  av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
659 
660  seg->oformat = av_guess_format(seg->format, s->filename, NULL);
661 
662  if (!seg->oformat) {
664  goto fail;
665  }
666  if (seg->oformat->flags & AVFMT_NOFILE) {
667  av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
668  seg->oformat->name);
669  ret = AVERROR(EINVAL);
670  goto fail;
671  }
672 
673  if ((ret = segment_mux_init(s)) < 0)
674  goto fail;
675  oc = seg->avf;
676 
677  if ((ret = set_segment_filename(s)) < 0)
678  goto fail;
679 
680  if (seg->write_header_trailer) {
681  if ((ret = avio_open2(&oc->pb, seg->header_filename ? seg->header_filename : oc->filename, AVIO_FLAG_WRITE,
682  &s->interrupt_callback, NULL)) < 0) {
683  av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
684  goto fail;
685  }
686  if (!seg->individual_header_trailer)
687  oc->pb->seekable = 0;
688  } else {
689  if ((ret = open_null_ctx(&oc->pb)) < 0)
690  goto fail;
691  }
692 
693  av_dict_copy(&options, seg->format_options, 0);
694  ret = avformat_write_header(oc, &options);
695  if (av_dict_count(options)) {
696  av_log(s, AV_LOG_ERROR,
697  "Some of the provided format options in '%s' are not recognized\n", seg->format_options_str);
698  ret = AVERROR(EINVAL);
699  goto fail;
700  }
701 
702  if (ret < 0) {
703  avio_closep(&oc->pb);
704  goto fail;
705  }
706  seg->segment_frame_count = 0;
707 
708  av_assert0(s->nb_streams == oc->nb_streams);
709  for (i = 0; i < s->nb_streams; i++) {
710  AVStream *inner_st = oc->streams[i];
711  AVStream *outer_st = s->streams[i];
712  avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
713  }
714 
715  if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
716  s->avoid_negative_ts = 1;
717 
718  if (!seg->write_header_trailer || seg->header_filename) {
719  if (seg->header_filename) {
720  av_write_frame(oc, NULL);
721  avio_closep(&oc->pb);
722  } else {
723  close_null_ctxp(&oc->pb);
724  }
725  if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
726  &s->interrupt_callback, NULL)) < 0)
727  goto fail;
728  if (!seg->individual_header_trailer)
729  oc->pb->seekable = 0;
730  }
731 
732 fail:
733  av_dict_free(&options);
734  if (ret < 0)
735  seg_free_context(seg);
736 
737  return ret;
738 }
739 
741 {
742  SegmentContext *seg = s->priv_data;
743  AVStream *st = s->streams[pkt->stream_index];
744  int64_t end_pts = INT64_MAX, offset;
745  int start_frame = INT_MAX;
746  int ret;
747  struct tm ti;
748  int64_t usecs;
749  int64_t wrapped_val;
750 
751  if (!seg->avf)
752  return AVERROR(EINVAL);
753 
754  if (seg->times) {
755  end_pts = seg->segment_count < seg->nb_times ?
756  seg->times[seg->segment_count] : INT64_MAX;
757  } else if (seg->frames) {
758  start_frame = seg->segment_count < seg->nb_frames ?
759  seg->frames[seg->segment_count] : INT_MAX;
760  } else {
761  if (seg->use_clocktime) {
762  int64_t avgt = av_gettime();
763  time_t sec = avgt / 1000000;
764  localtime_r(&sec, &ti);
765  usecs = (int64_t)(ti.tm_hour * 3600 + ti.tm_min * 60 + ti.tm_sec) * 1000000 + (avgt % 1000000);
766  wrapped_val = usecs % seg->time;
767  if (seg->last_cut != usecs && wrapped_val < seg->last_val) {
768  seg->cut_pending = 1;
769  seg->last_cut = usecs;
770  }
771  seg->last_val = wrapped_val;
772  } else {
773  end_pts = seg->time * (seg->segment_count + 1);
774  }
775  }
776 
777  av_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",
778  pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
779  av_ts2timestr(pkt->duration, &st->time_base),
780  pkt->flags & AV_PKT_FLAG_KEY,
781  pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);
782 
783  if (pkt->stream_index == seg->reference_stream_index &&
784  (pkt->flags & AV_PKT_FLAG_KEY || seg->break_non_keyframes) &&
785  seg->segment_frame_count > 0 &&
786  (seg->cut_pending || seg->frame_count >= start_frame ||
787  (pkt->pts != AV_NOPTS_VALUE &&
788  av_compare_ts(pkt->pts, st->time_base,
789  end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0))) {
790  /* sanitize end time in case last packet didn't have a defined duration */
791  if (seg->cur_entry.last_duration == 0)
792  seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);
793 
794  if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)
795  goto fail;
796 
797  if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)
798  goto fail;
799 
800  seg->cut_pending = 0;
802  seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);
804  seg->cur_entry.end_time = seg->cur_entry.start_time +
805  pkt->pts != AV_NOPTS_VALUE ? (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base) : 0;
806  } else if (pkt->pts != AV_NOPTS_VALUE && pkt->stream_index == seg->reference_stream_index) {
807  seg->cur_entry.end_time =
808  FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
809  seg->cur_entry.last_duration = pkt->duration;
810  }
811 
812  if (seg->segment_frame_count == 0) {
813  av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",
814  seg->avf->filename, pkt->stream_index,
815  av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);
816  }
817 
818  av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",
819  pkt->stream_index,
821  av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
822  av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
823 
824  /* compute new timestamps */
825  offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),
827  if (pkt->pts != AV_NOPTS_VALUE)
828  pkt->pts += offset;
829  if (pkt->dts != AV_NOPTS_VALUE)
830  pkt->dts += offset;
831 
832  av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
833  av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
834  av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
835 
836  ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s, seg->initial_offset || seg->reset_timestamps);
837 
838 fail:
839  if (pkt->stream_index == seg->reference_stream_index) {
840  seg->frame_count++;
841  seg->segment_frame_count++;
842  }
843 
844  if (ret < 0)
845  seg_free_context(seg);
846 
847  return ret;
848 }
849 
851 {
852  SegmentContext *seg = s->priv_data;
853  AVFormatContext *oc = seg->avf;
854  SegmentListEntry *cur, *next;
855  int ret = 0;
856 
857  if (!oc)
858  goto fail;
859 
860  if (!seg->write_header_trailer) {
861  if ((ret = segment_end(s, 0, 1)) < 0)
862  goto fail;
863  open_null_ctx(&oc->pb);
864  ret = av_write_trailer(oc);
865  close_null_ctxp(&oc->pb);
866  } else {
867  ret = segment_end(s, 1, 1);
868  }
869 fail:
870  if (seg->list)
871  avio_closep(&seg->list_pb);
872 
874  av_opt_free(seg);
875  av_freep(&seg->times);
876  av_freep(&seg->frames);
877 
878  cur = seg->segment_list_entries;
879  while (cur) {
880  next = cur->next;
881  av_freep(&cur->filename);
882  av_free(cur);
883  cur = next;
884  }
885 
887  seg->avf = NULL;
888  return ret;
889 }
890 
891 #define OFFSET(x) offsetof(SegmentContext, x)
892 #define E AV_OPT_FLAG_ENCODING_PARAM
893 static const AVOption options[] = {
894  { "reference_stream", "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, CHAR_MIN, CHAR_MAX, E },
895  { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
896  { "segment_format_options", "set list of options for the container format used for the segments", OFFSET(format_options_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
897  { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
898  { "segment_header_filename", "write a single file containing the header", OFFSET(header_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
899 
900  { "segment_list_flags","set flags affecting segment list generation", OFFSET(list_flags), AV_OPT_TYPE_FLAGS, {.i64 = SEGMENT_LIST_FLAG_CACHE }, 0, UINT_MAX, E, "list_flags"},
901  { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
902  { "live", "enable live-friendly list generation (useful for HLS)", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_LIVE }, INT_MIN, INT_MAX, E, "list_flags"},
903 
904  { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
905 
906  { "segment_list_type", "set the segment list type", OFFSET(list_type), AV_OPT_TYPE_INT, {.i64 = LIST_TYPE_UNDEFINED}, -1, LIST_TYPE_NB-1, E, "list_type" },
907  { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" },
908  { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, E, "list_type" },
909  { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, E, "list_type" },
910  { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" },
911  { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
912  { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
913 
914  { "segment_atclocktime", "set segment to be cut at clocktime", OFFSET(use_clocktime), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E},
915  { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
916  { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 0, E },
917  { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
918  { "segment_frames", "set segment split frame numbers", OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
919  { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
920  { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
921  { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
922  { "segment_wrap_number", "set the number of wrap before the first segment", OFFSET(segment_idx_wrap_nb), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
923  { "strftime", "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, E },
924  { "break_non_keyframes", "allow breaking segments on non-keyframes", OFFSET(break_non_keyframes), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
925 
926  { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
927  { "write_header_trailer", "write a header to the first segment and a trailer to the last one", OFFSET(write_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
928  { "reset_timestamps", "reset timestamps at the begin of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
929  { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
930  { NULL },
931 };
932 
933 static const AVClass seg_class = {
934  .class_name = "segment muxer",
935  .item_name = av_default_item_name,
936  .option = options,
937  .version = LIBAVUTIL_VERSION_INT,
938 };
939 
941  .name = "segment",
942  .long_name = NULL_IF_CONFIG_SMALL("segment"),
943  .priv_data_size = sizeof(SegmentContext),
948  .priv_class = &seg_class,
949 };
950 
951 static const AVClass sseg_class = {
952  .class_name = "stream_segment muxer",
953  .item_name = av_default_item_name,
954  .option = options,
955  .version = LIBAVUTIL_VERSION_INT,
956 };
957 
959  .name = "stream_segment,ssegment",
960  .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
961  .priv_data_size = sizeof(SegmentContext),
962  .flags = AVFMT_NOFILE,
966  .priv_class = &sseg_class,
967 };
struct SegmentListEntry * next
Definition: segment.c:51
#define NULL
Definition: coverity.c:32
AVFormatContext * avf
Definition: segment.c:75
const char * s
Definition: avisynth_c.h:631
Bytestream IO Context.
Definition: avio.h:111
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1520
char * header_filename
filename to write the output header to
Definition: segment.c:108
AVOption.
Definition: opt.h:255
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:428
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file.
Definition: mux.c:672
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
int av_escape(char **dst, const char *src, const char *special_chars, enum AVEscapeMode mode, int flags)
Escape string in src, and put the escaped string in an allocated string in *dst, which must be freed ...
Definition: avstring.c:303
#define LIBAVUTIL_VERSION_INT
Definition: version.h:62
char * entry_prefix
prefix to add to list entry filenames
Definition: segment.c:88
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:4006
int av_parse_time(int64_t *timeval, const char *timestr, int duration)
Parse timestr and return in *time a corresponding number of microseconds.
Definition: parseutils.c:554
AVDictionary * format_options
Definition: segment.c:78
static int segment_start(AVFormatContext *s, int write_header)
Definition: segment.c:215
int segment_idx_wrap
number after which the index wraps
Definition: segment.c:71
int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt, AVFormatContext *src, int interleave)
Write a packet to another muxer than the one the user originally intended.
Definition: mux.c:1022
#define FAIL(err)
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:914
int num
numerator
Definition: rational.h:44
int av_dict_count(const AVDictionary *m)
Get number of entries in dictionary.
Definition: dict.c:34
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:461
#define FF_ARRAY_ELEMS(a)
static AVPacket pkt
int segment_frame_count
number of reference frames in the segment
Definition: segment.c:103
char * filename
Definition: segment.c:50
int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src)
Copy the settings of the source AVCodecContext into the destination AVCodecContext.
Definition: options.c:180
static int parse_frames(void *log_ctx, int **frames, int *nb_frames, const char *frames_str)
Definition: segment.c:445
static int seg_write_header(AVFormatContext *s)
Definition: segment.c:588
static int segment_end(AVFormatContext *s, int write_trailer, int is_last)
Definition: segment.c:326
int list_flags
flags affecting list generation
Definition: segment.c:80
static int segment_mux_init(AVFormatContext *s)
Definition: segment.c:137
Format I/O context.
Definition: avformat.h:1272
int64_t last_duration
Definition: segment.c:52
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:72
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
static void close_null_ctxp(AVIOContext **pb)
Definition: segment.c:518
const char * av_basename(const char *path)
Thread safe basename.
Definition: avstring.c:234
int flags
can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_RAWPICTURE, AVFMT_GLOBALHEADER, AVFMT_NOTIMESTAMPS, AVFMT_VARIABLE_FPS, AVFMT_NODIMENSIONS, AVFMT_NOSTREAMS, AVFMT_ALLOW_FLUSH, AVFMT_TS_NONSTRICT
Definition: avformat.h:532
uint8_t
#define av_malloc(s)
Opaque data information usually continuous.
Definition: avutil.h:196
AVOptions.
enum AVCodecID av_codec_get_id(const struct AVCodecTag *const *tags, unsigned int tag)
Get the AVCodecID for the given codec tag tag.
timestamp utils, mostly useful for debugging/logging purposes
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:67
int avformat_match_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
Check if the stream st contained in s is matched by the stream specifier spec.
Definition: utils.c:4232
static int seg_write_trailer(struct AVFormatContext *s)
Definition: segment.c:850
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:3672
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1340
static double av_q2d(AVRational a)
Convert rational to double.
Definition: rational.h:80
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:192
int av_match_ext(const char *filename, const char *extensions)
Return a positive value if the given filename has one of the given extensions, 0 otherwise.
Definition: format.c:81
ptrdiff_t size
Definition: opengl_enc.c:101
int duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: avcodec.h:1180
void av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags)
Copy entries from one AVDictionary struct into another.
Definition: dict.c:213
char * format
format to use for output segment files
Definition: segment.c:76
static int select_reference_stream(AVFormatContext *s)
Definition: segment.c:524
#define av_log(a,...)
int break_non_keyframes
Definition: segment.c:114
struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:1291
int64_t time_delta
Definition: segment.c:105
int64_t initial_offset
initial timestamps offset, expressed in microseconds
Definition: segment.c:111
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1208
int avformat_alloc_output_context2(AVFormatContext **ctx, AVOutputFormat *oformat, const char *format_name, const char *filename)
Allocate an AVFormatContext for an output format.
Definition: mux.c:148
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:140
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:111
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1482
int individual_header_trailer
Set by a private option.
Definition: segment.c:106
av_default_item_name
#define AVERROR(e)
Definition: error.h:43
#define av_ts2timestr(ts, tb)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: timestamp.h:76
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:175
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values. ...
Definition: dict.c:199
simple assert() macros that are a bit more flexible than ISO C assert().
int64_t * times
list of segment interval specification
Definition: segment.c:96
static const uint8_t offset[127][2]
Definition: vf_spp.c:92
char * reference_stream_specifier
reference stream specifier
Definition: segment.c:112
#define FFMAX(a, b)
Definition: common.h:64
static int set_segment_filename(AVFormatContext *s)
Definition: segment.c:177
int64_t offset_pts
Definition: segment.c:49
int reference_stream_index
Definition: segment.c:113
int nb_times
number of elments in the times array
Definition: segment.c:97
#define OFFSET(x)
Definition: segment.c:891
static int segment_list_open(AVFormatContext *s)
Definition: segment.c:256
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1168
int64_t last_val
remember last time for wrap around detection
Definition: segment.c:84
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:145
Use auto-selected escaping mode.
Definition: avstring.h:290
AVIOContext * list_pb
list file put-byte context
Definition: segment.c:90
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:861
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1328
static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
Definition: segment.c:121
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:160
int void avio_flush(AVIOContext *s)
Force flushing of buffered data.
Definition: aviobuf.c:197
char filename[1024]
input or output filename
Definition: avformat.h:1348
int cut_pending
Definition: segment.c:86
static struct tm * localtime_r(const time_t *clock, struct tm *result)
Definition: time_internal.h:37
ret
Definition: avfilter.c:974
static int write_trailer(AVFormatContext *s1)
Definition: v4l2enc.c:94
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition: avformat.h:471
static const AVClass sseg_class
Definition: segment.c:951
int use_strftime
flag to expand filename with strftime
Definition: segment.c:93
const char * name
Definition: avformat.h:513
int reset_timestamps
reset timestamps at the begin of each segment
Definition: segment.c:110
int use_clocktime
flag to cut segments at regular clock time
Definition: segment.c:83
ListType
Definition: segment.c:55
int avoid_negative_ts
Avoid negative timestamps during muxing.
Definition: avformat.h:1573
AVDictionary * metadata
Definition: avformat.h:916
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:94
Opaque data information usually sparse.
Definition: avutil.h:198
const AVClass * priv_class
AVClass for the private context.
Definition: avformat.h:541
#define AV_DISPOSITION_ATTACHED_PIC
The stream is stored in the file as an attached picture/"cover art" (e.g.
Definition: avformat.h:819
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:3831
static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: segment.c:740
int64_t av_gettime(void)
Get the current time in microseconds.
Definition: time.c:39
Stream structure.
Definition: avformat.h:842
#define av_dlog(pctx,...)
av_dlog macros
Definition: log.h:330
char * list
filename for the segment list file
Definition: segment.c:79
int av_dict_parse_string(AVDictionary **pm, const char *str, const char *key_val_sep, const char *pairs_sep, int flags)
Parse the key/value pairs list and add the parsed entries to a dictionary.
Definition: dict.c:176
char * frames_str
segment frame numbers specification string
Definition: segment.c:99
enum AVMediaType codec_type
Definition: avcodec.h:1249
enum AVCodecID codec_id
Definition: avcodec.h:1258
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:253
char * av_strdup(const char *s)
Duplicate the string s.
Definition: mem.c:265
AVIOContext * pb
I/O context.
Definition: avformat.h:1314
const struct AVCodecTag *const * codec_tag
List of supported codec_id-codec_tag pairs, ordered by "better choice first".
Definition: avformat.h:538
void avio_w8(AVIOContext *s, int b)
Definition: aviobuf.c:155
main external API structure.
Definition: avcodec.h:1241
int64_t time
segment duration
Definition: segment.c:92
unsigned int codec_tag
fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
Definition: avcodec.h:1273
void * buf
Definition: avisynth_c.h:553
GLint GLenum type
Definition: opengl_enc.c:105
int list_type
set the list type
Definition: segment.c:89
AVOutputFormat ff_segment_muxer
Definition: segment.c:940
int segment_idx
index of the segment file to write, starting from 0
Definition: segment.c:70
Describe the class of an AVClass context structure.
Definition: log.h:67
int * frames
list of frame number specification
Definition: segment.c:100
int64_t start_pts
Definition: segment.c:48
char * time_str
segment duration specification string
Definition: segment.c:91
AVMediaType
Definition: avutil.h:192
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:914
#define snprintf
Definition: snprintf.h:34
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:3609
misc parsing utilities
SegmentListEntry * segment_list_entries
Definition: segment.c:117
const char * av_get_media_type_string(enum AVMediaType media_type)
Return a string describing the media_type enum, NULL if media_type is unknown.
Definition: utils.c:72
int nb_frames
number of elments in the frames array
Definition: segment.c:101
static int flags
Definition: cpu.c:47
int write_header_trailer
Set by a private option.
Definition: segment.c:107
char * format_options_str
format options to use for output segment files
Definition: segment.c:77
char * av_strtok(char *s, const char *delim, char **saveptr)
Split the string into several tokens which can be accessed by successive calls to av_strtok()...
Definition: avstring.c:184
static void segment_list_print_entry(AVIOContext *list_ioctx, ListType list_type, const SegmentListEntry *list_entry, void *log_ctx)
Definition: segment.c:291
double end_time
Definition: segment.c:47
static const AVClass seg_class
Definition: segment.c:933
Main libavformat public API header.
void av_opt_free(void *obj)
Free all allocated objects in obj.
Definition: opt.c:1435
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition: avformat.h:465
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:905
#define SEGMENT_LIST_FLAG_CACHE
Definition: segment.c:65
#define E
Definition: segment.c:892
int pts_wrap_bits
number of bits in pts (used for wrapping control)
Definition: avformat.h:1008
static int parse_times(void *log_ctx, int64_t **times, int *nb_times, const char *times_str)
Definition: segment.c:387
int den
denominator
Definition: rational.h:45
double start_time
Definition: segment.c:47
#define av_free(p)
int segment_idx_wrap_nb
number of time the index has wraped
Definition: segment.c:72
#define av_ts2str(ts)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: timestamp.h:54
void * priv_data
Format private data.
Definition: avformat.h:1300
static const AVOption options[]
Definition: segment.c:893
int64_t last_cut
remember last cut
Definition: segment.c:85
#define AV_ESCAPE_FLAG_WHITESPACE
Consider spaces special and escape them even in the middle of the string.
Definition: avstring.h:303
static void write_header(FFV1Context *f)
Definition: ffv1enc.c:493
AVOutputFormat ff_stream_segment_muxer
Definition: segment.c:958
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1161
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition: mux.c:967
static int open_null_ctx(AVIOContext **ctx)
Definition: segment.c:504
#define av_freep(p)
#define AVERROR_MUXER_NOT_FOUND
Muxer not found.
Definition: error.h:60
int segment_count
number of segment files already written
Definition: segment.c:73
static void seg_free_context(SegmentContext *seg)
Definition: segment.c:581
char * times_str
segment times specification string
Definition: segment.c:95
#define av_malloc_array(a, b)
int stream_index
Definition: avcodec.h:1164
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:884
SegmentListEntry cur_entry
Definition: segment.c:116
unsigned int av_codec_get_tag(const struct AVCodecTag *const *tags, enum AVCodecID id)
Get the codec tag for the given codec id id.
int list_size
number of entries for the segment list file
Definition: segment.c:81
deprecated
Definition: segment.c:60
This structure stores compressed data.
Definition: avcodec.h:1139
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:955
int frame_count
total number of reference frames
Definition: segment.c:102
static int write_packet(AVFormatContext *s1, AVPacket *pkt)
Definition: v4l2enc.c:86
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:369
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:250
#define SEGMENT_LIST_FLAG_LIVE
Definition: segment.c:66
SegmentListEntry * segment_list_entries_end
Definition: segment.c:118
AVOutputFormat * oformat
Definition: segment.c:74
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1155
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:241
int avio_printf(AVIOContext *s, const char *fmt,...) av_printf_format(2