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/internal.h"
37 #include "libavutil/log.h"
38 #include "libavutil/opt.h"
39 #include "libavutil/avstring.h"
40 #include "libavutil/parseutils.h"
41 #include "libavutil/mathematics.h"
42 #include "libavutil/time.h"
44 #include "libavutil/timestamp.h"
45 
46 typedef struct SegmentListEntry {
47  int index;
49  int64_t start_pts;
50  int64_t offset_pts;
51  char *filename;
53  int64_t last_duration;
55 
56 typedef enum {
61  LIST_TYPE_EXT, ///< deprecated
64 } ListType;
65 
66 #define SEGMENT_LIST_FLAG_CACHE 1
67 #define SEGMENT_LIST_FLAG_LIVE 2
68 
69 typedef struct SegmentContext {
70  const AVClass *class; /**< Class for private options. */
71  int segment_idx; ///< index of the segment file to write, starting from 0
72  int segment_idx_wrap; ///< number after which the index wraps
73  int segment_idx_wrap_nb; ///< number of time the index has wraped
74  int segment_count; ///< number of segment files already written
77  char *format; ///< format to use for output segment files
78  char *format_options_str; ///< format options to use for output segment files
80  char *list; ///< filename for the segment list file
81  int list_flags; ///< flags affecting list generation
82  int list_size; ///< number of entries for the segment list file
83 
84  int use_clocktime; ///< flag to cut segments at regular clock time
85  int64_t last_val; ///< remember last time for wrap around detection
86  int64_t last_cut; ///< remember last cut
88 
89  char *entry_prefix; ///< prefix to add to list entry filenames
90  int list_type; ///< set the list type
91  AVIOContext *list_pb; ///< list file put-byte context
92  char *time_str; ///< segment duration specification string
93  int64_t time; ///< segment duration
94  int use_strftime; ///< flag to expand filename with strftime
95 
96  char *times_str; ///< segment times specification string
97  int64_t *times; ///< list of segment interval specification
98  int nb_times; ///< number of elments in the times array
99 
100  char *frames_str; ///< segment frame numbers specification string
101  int *frames; ///< list of frame number specification
102  int nb_frames; ///< number of elments in the frames array
103  int frame_count; ///< total number of reference frames
104  int segment_frame_count; ///< number of reference frames in the segment
105 
106  int64_t time_delta;
107  int individual_header_trailer; /**< Set by a private option. */
108  int write_header_trailer; /**< Set by a private option. */
109  char *header_filename; ///< filename to write the output header to
110 
111  int reset_timestamps; ///< reset timestamps at the begin of each segment
112  int64_t initial_offset; ///< initial timestamps offset, expressed in microseconds
113  char *reference_stream_specifier; ///< reference stream specifier
116 
118  char temp_list_filename[1024];
119 
124 
125 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
126 {
127  int needs_quoting = !!str[strcspn(str, "\",\n\r")];
128 
129  if (needs_quoting)
130  avio_w8(ctx, '"');
131 
132  for (; *str; str++) {
133  if (*str == '"')
134  avio_w8(ctx, '"');
135  avio_w8(ctx, *str);
136  }
137  if (needs_quoting)
138  avio_w8(ctx, '"');
139 }
140 
142 {
143  SegmentContext *seg = s->priv_data;
144  AVFormatContext *oc;
145  int i;
146  int ret;
147 
148  ret = avformat_alloc_output_context2(&seg->avf, seg->oformat, NULL, NULL);
149  if (ret < 0)
150  return ret;
151  oc = seg->avf;
152 
154  oc->max_delay = s->max_delay;
155  av_dict_copy(&oc->metadata, s->metadata, 0);
156 
157  for (i = 0; i < s->nb_streams; i++) {
158  AVStream *st;
159  AVCodecContext *icodec, *ocodec;
160 
161  if (!(st = avformat_new_stream(oc, NULL)))
162  return AVERROR(ENOMEM);
163  icodec = s->streams[i]->codec;
164  ocodec = st->codec;
165  avcodec_copy_context(ocodec, icodec);
166  if (!oc->oformat->codec_tag ||
167  av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == ocodec->codec_id ||
168  av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0) {
169  ocodec->codec_tag = icodec->codec_tag;
170  } else {
171  ocodec->codec_tag = 0;
172  }
174  st->time_base = s->streams[i]->time_base;
175  av_dict_copy(&st->metadata, s->streams[i]->metadata, 0);
176  }
177 
178  return 0;
179 }
180 
182 {
183  SegmentContext *seg = s->priv_data;
184  AVFormatContext *oc = seg->avf;
185  size_t size;
186 
187  if (seg->segment_idx_wrap)
188  seg->segment_idx %= seg->segment_idx_wrap;
189  if (seg->use_strftime) {
190  time_t now0;
191  struct tm *tm, tmpbuf;
192  time(&now0);
193  tm = localtime_r(&now0, &tmpbuf);
194  if (!strftime(oc->filename, sizeof(oc->filename), s->filename, tm)) {
195  av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
196  return AVERROR(EINVAL);
197  }
198  } else if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
199  s->filename, seg->segment_idx) < 0) {
200  av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
201  return AVERROR(EINVAL);
202  }
203 
204  /* copy modified name in list entry */
205  size = strlen(av_basename(oc->filename)) + 1;
206  if (seg->entry_prefix)
207  size += strlen(seg->entry_prefix);
208 
209  seg->cur_entry.filename = av_mallocz(size);
210  if (!seg->cur_entry.filename)
211  return AVERROR(ENOMEM);
212  snprintf(seg->cur_entry.filename, size, "%s%s",
213  seg->entry_prefix ? seg->entry_prefix : "",
214  av_basename(oc->filename));
215 
216  return 0;
217 }
218 
220 {
221  SegmentContext *seg = s->priv_data;
222  AVFormatContext *oc = seg->avf;
223  int err = 0;
224 
225  if (write_header) {
227  seg->avf = NULL;
228  if ((err = segment_mux_init(s)) < 0)
229  return err;
230  oc = seg->avf;
231  }
232 
233  seg->segment_idx++;
234  if ((seg->segment_idx_wrap) && (seg->segment_idx % seg->segment_idx_wrap == 0))
235  seg->segment_idx_wrap_nb++;
236 
237  if ((err = set_segment_filename(s)) < 0)
238  return err;
239 
240  if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
241  &s->interrupt_callback, NULL)) < 0) {
242  av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
243  return err;
244  }
245  if (!seg->individual_header_trailer)
246  oc->pb->seekable = 0;
247 
248  if (oc->oformat->priv_class && oc->priv_data)
249  av_opt_set(oc->priv_data, "mpegts_flags", "+resend_headers", 0);
250 
251  if (write_header) {
252  if ((err = avformat_write_header(oc, NULL)) < 0)
253  return err;
254  }
255 
256  seg->segment_frame_count = 0;
257  return 0;
258 }
259 
261 {
262  SegmentContext *seg = s->priv_data;
263  int ret;
264 
265  snprintf(seg->temp_list_filename, sizeof(seg->temp_list_filename), seg->use_rename ? "%s.tmp" : "%s", seg->list);
267  &s->interrupt_callback, NULL);
268  if (ret < 0) {
269  av_log(s, AV_LOG_ERROR, "Failed to open segment list '%s'\n", seg->list);
270  return ret;
271  }
272 
273  if (seg->list_type == LIST_TYPE_M3U8 && seg->segment_list_entries) {
274  SegmentListEntry *entry;
275  double max_duration = 0;
276 
277  avio_printf(seg->list_pb, "#EXTM3U\n");
278  avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
279  avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_list_entries->index);
280  avio_printf(seg->list_pb, "#EXT-X-ALLOW-CACHE:%s\n",
281  seg->list_flags & SEGMENT_LIST_FLAG_CACHE ? "YES" : "NO");
282 
283  av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n",
285 
286  for (entry = seg->segment_list_entries; entry; entry = entry->next)
287  max_duration = FFMAX(max_duration, entry->end_time - entry->start_time);
288  avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%"PRId64"\n", (int64_t)ceil(max_duration));
289  } else if (seg->list_type == LIST_TYPE_FFCONCAT) {
290  avio_printf(seg->list_pb, "ffconcat version 1.0\n");
291  }
292 
293  return ret;
294 }
295 
296 static void segment_list_print_entry(AVIOContext *list_ioctx,
297  ListType list_type,
298  const SegmentListEntry *list_entry,
299  void *log_ctx)
300 {
301  switch (list_type) {
302  case LIST_TYPE_FLAT:
303  avio_printf(list_ioctx, "%s\n", list_entry->filename);
304  break;
305  case LIST_TYPE_CSV:
306  case LIST_TYPE_EXT:
307  print_csv_escaped_str(list_ioctx, list_entry->filename);
308  avio_printf(list_ioctx, ",%f,%f\n", list_entry->start_time, list_entry->end_time);
309  break;
310  case LIST_TYPE_M3U8:
311  avio_printf(list_ioctx, "#EXTINF:%f,\n%s\n",
312  list_entry->end_time - list_entry->start_time, list_entry->filename);
313  break;
314  case LIST_TYPE_FFCONCAT:
315  {
316  char *buf;
317  if (av_escape(&buf, list_entry->filename, NULL, AV_ESCAPE_MODE_AUTO, AV_ESCAPE_FLAG_WHITESPACE) < 0) {
318  av_log(log_ctx, AV_LOG_WARNING,
319  "Error writing list entry '%s' in list file\n", list_entry->filename);
320  return;
321  }
322  avio_printf(list_ioctx, "file %s\n", buf);
323  av_free(buf);
324  break;
325  }
326  default:
327  av_assert0(!"Invalid list type");
328  }
329 }
330 
331 static int segment_end(AVFormatContext *s, int write_trailer, int is_last)
332 {
333  SegmentContext *seg = s->priv_data;
334  AVFormatContext *oc = seg->avf;
335  int ret = 0;
336 
337  av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
338  if (write_trailer)
339  ret = av_write_trailer(oc);
340 
341  if (ret < 0)
342  av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
343  oc->filename);
344 
345  if (seg->list) {
346  if (seg->list_size || seg->list_type == LIST_TYPE_M3U8) {
347  SegmentListEntry *entry = av_mallocz(sizeof(*entry));
348  if (!entry) {
349  ret = AVERROR(ENOMEM);
350  goto end;
351  }
352 
353  /* append new element */
354  memcpy(entry, &seg->cur_entry, sizeof(*entry));
355  entry->filename = av_strdup(entry->filename);
356  if (!seg->segment_list_entries)
358  else
359  seg->segment_list_entries_end->next = entry;
360  seg->segment_list_entries_end = entry;
361 
362  /* drop first item */
363  if (seg->list_size && seg->segment_count >= seg->list_size) {
364  entry = seg->segment_list_entries;
366  av_freep(&entry->filename);
367  av_freep(&entry);
368  }
369 
370  if ((ret = segment_list_open(s)) < 0)
371  goto end;
372  for (entry = seg->segment_list_entries; entry; entry = entry->next)
373  segment_list_print_entry(seg->list_pb, seg->list_type, entry, s);
374  if (seg->list_type == LIST_TYPE_M3U8 && is_last)
375  avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
376  avio_closep(&seg->list_pb);
377  if (seg->use_rename)
378  ff_rename(seg->temp_list_filename, seg->list, s);
379  } else {
380  segment_list_print_entry(seg->list_pb, seg->list_type, &seg->cur_entry, s);
381  avio_flush(seg->list_pb);
382  }
383  }
384 
385  av_log(s, AV_LOG_VERBOSE, "segment:'%s' count:%d ended\n",
386  seg->avf->filename, seg->segment_count);
387  seg->segment_count++;
388 
389 end:
390  avio_closep(&oc->pb);
391 
392  return ret;
393 }
394 
395 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
396  const char *times_str)
397 {
398  char *p;
399  int i, ret = 0;
400  char *times_str1 = av_strdup(times_str);
401  char *saveptr = NULL;
402 
403  if (!times_str1)
404  return AVERROR(ENOMEM);
405 
406 #define FAIL(err) ret = err; goto end
407 
408  *nb_times = 1;
409  for (p = times_str1; *p; p++)
410  if (*p == ',')
411  (*nb_times)++;
412 
413  *times = av_malloc_array(*nb_times, sizeof(**times));
414  if (!*times) {
415  av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
416  FAIL(AVERROR(ENOMEM));
417  }
418 
419  p = times_str1;
420  for (i = 0; i < *nb_times; i++) {
421  int64_t t;
422  char *tstr = av_strtok(p, ",", &saveptr);
423  p = NULL;
424 
425  if (!tstr || !tstr[0]) {
426  av_log(log_ctx, AV_LOG_ERROR, "Empty time specification in times list %s\n",
427  times_str);
428  FAIL(AVERROR(EINVAL));
429  }
430 
431  ret = av_parse_time(&t, tstr, 1);
432  if (ret < 0) {
433  av_log(log_ctx, AV_LOG_ERROR,
434  "Invalid time duration specification '%s' in times list %s\n", tstr, times_str);
435  FAIL(AVERROR(EINVAL));
436  }
437  (*times)[i] = t;
438 
439  /* check on monotonicity */
440  if (i && (*times)[i-1] > (*times)[i]) {
441  av_log(log_ctx, AV_LOG_ERROR,
442  "Specified time %f is greater than the following time %f\n",
443  (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
444  FAIL(AVERROR(EINVAL));
445  }
446  }
447 
448 end:
449  av_free(times_str1);
450  return ret;
451 }
452 
453 static int parse_frames(void *log_ctx, int **frames, int *nb_frames,
454  const char *frames_str)
455 {
456  char *p;
457  int i, ret = 0;
458  char *frames_str1 = av_strdup(frames_str);
459  char *saveptr = NULL;
460 
461  if (!frames_str1)
462  return AVERROR(ENOMEM);
463 
464 #define FAIL(err) ret = err; goto end
465 
466  *nb_frames = 1;
467  for (p = frames_str1; *p; p++)
468  if (*p == ',')
469  (*nb_frames)++;
470 
471  *frames = av_malloc_array(*nb_frames, sizeof(**frames));
472  if (!*frames) {
473  av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced frames array\n");
474  FAIL(AVERROR(ENOMEM));
475  }
476 
477  p = frames_str1;
478  for (i = 0; i < *nb_frames; i++) {
479  long int f;
480  char *tailptr;
481  char *fstr = av_strtok(p, ",", &saveptr);
482 
483  p = NULL;
484  if (!fstr) {
485  av_log(log_ctx, AV_LOG_ERROR, "Empty frame specification in frame list %s\n",
486  frames_str);
487  FAIL(AVERROR(EINVAL));
488  }
489  f = strtol(fstr, &tailptr, 10);
490  if (*tailptr || f <= 0 || f >= INT_MAX) {
491  av_log(log_ctx, AV_LOG_ERROR,
492  "Invalid argument '%s', must be a positive integer <= INT64_MAX\n",
493  fstr);
494  FAIL(AVERROR(EINVAL));
495  }
496  (*frames)[i] = f;
497 
498  /* check on monotonicity */
499  if (i && (*frames)[i-1] > (*frames)[i]) {
500  av_log(log_ctx, AV_LOG_ERROR,
501  "Specified frame %d is greater than the following frame %d\n",
502  (*frames)[i], (*frames)[i-1]);
503  FAIL(AVERROR(EINVAL));
504  }
505  }
506 
507 end:
508  av_free(frames_str1);
509  return ret;
510 }
511 
512 static int open_null_ctx(AVIOContext **ctx)
513 {
514  int buf_size = 32768;
515  uint8_t *buf = av_malloc(buf_size);
516  if (!buf)
517  return AVERROR(ENOMEM);
518  *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
519  if (!*ctx) {
520  av_free(buf);
521  return AVERROR(ENOMEM);
522  }
523  return 0;
524 }
525 
526 static void close_null_ctxp(AVIOContext **pb)
527 {
528  av_freep(&(*pb)->buffer);
529  av_freep(pb);
530 }
531 
533 {
534  SegmentContext *seg = s->priv_data;
535  int ret, i;
536 
537  seg->reference_stream_index = -1;
538  if (!strcmp(seg->reference_stream_specifier, "auto")) {
539  /* select first index of type with highest priority */
540  int type_index_map[AVMEDIA_TYPE_NB];
541  static const enum AVMediaType type_priority_list[] = {
547  };
548  enum AVMediaType type;
549 
550  for (i = 0; i < AVMEDIA_TYPE_NB; i++)
551  type_index_map[i] = -1;
552 
553  /* select first index for each type */
554  for (i = 0; i < s->nb_streams; i++) {
555  type = s->streams[i]->codec->codec_type;
556  if ((unsigned)type < AVMEDIA_TYPE_NB && type_index_map[type] == -1
557  /* ignore attached pictures/cover art streams */
559  type_index_map[type] = i;
560  }
561 
562  for (i = 0; i < FF_ARRAY_ELEMS(type_priority_list); i++) {
563  type = type_priority_list[i];
564  if ((seg->reference_stream_index = type_index_map[type]) >= 0)
565  break;
566  }
567  } else {
568  for (i = 0; i < s->nb_streams; i++) {
571  if (ret < 0)
572  return ret;
573  if (ret > 0) {
574  seg->reference_stream_index = i;
575  break;
576  }
577  }
578  }
579 
580  if (seg->reference_stream_index < 0) {
581  av_log(s, AV_LOG_ERROR, "Could not select stream matching identifier '%s'\n",
583  return AVERROR(EINVAL);
584  }
585 
586  return 0;
587 }
588 
590 {
591  avio_closep(&seg->list_pb);
593  seg->avf = NULL;
594 }
595 
597 {
598  SegmentContext *seg = s->priv_data;
599  AVFormatContext *oc = NULL;
601  int ret;
602  int i;
603 
604  seg->segment_count = 0;
605  if (!seg->write_header_trailer)
606  seg->individual_header_trailer = 0;
607 
608  if (seg->header_filename) {
609  seg->write_header_trailer = 1;
610  seg->individual_header_trailer = 0;
611  }
612 
613  if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) {
614  av_log(s, AV_LOG_ERROR,
615  "segment_time, segment_times, and segment_frames options "
616  "are mutually exclusive, select just one of them\n");
617  return AVERROR(EINVAL);
618  }
619 
620  if (seg->times_str) {
621  if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
622  return ret;
623  } else if (seg->frames_str) {
624  if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
625  return ret;
626  } else {
627  /* set default value if not specified */
628  if (!seg->time_str)
629  seg->time_str = av_strdup("2");
630  if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
631  av_log(s, AV_LOG_ERROR,
632  "Invalid time duration specification '%s' for segment_time option\n",
633  seg->time_str);
634  return ret;
635  }
636  }
637 
638  if (seg->format_options_str) {
639  ret = av_dict_parse_string(&seg->format_options, seg->format_options_str, "=", ":", 0);
640  if (ret < 0) {
641  av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
642  seg->format_options_str);
643  goto fail;
644  }
645  }
646 
647  if (seg->list) {
648  if (seg->list_type == LIST_TYPE_UNDEFINED) {
649  if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
650  else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
651  else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
652  else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
653  else seg->list_type = LIST_TYPE_FLAT;
654  }
655  if (!seg->list_size && seg->list_type != LIST_TYPE_M3U8) {
656  if ((ret = segment_list_open(s)) < 0)
657  goto fail;
658  } else {
659  const char *proto = avio_find_protocol_name(s->filename);
660  seg->use_rename = proto && !strcmp(proto, "file");
661  }
662  }
663  if (seg->list_type == LIST_TYPE_EXT)
664  av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
665 
666  if ((ret = select_reference_stream(s)) < 0)
667  goto fail;
668  av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
671 
672  seg->oformat = av_guess_format(seg->format, s->filename, NULL);
673 
674  if (!seg->oformat) {
676  goto fail;
677  }
678  if (seg->oformat->flags & AVFMT_NOFILE) {
679  av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
680  seg->oformat->name);
681  ret = AVERROR(EINVAL);
682  goto fail;
683  }
684 
685  if ((ret = segment_mux_init(s)) < 0)
686  goto fail;
687  oc = seg->avf;
688 
689  if ((ret = set_segment_filename(s)) < 0)
690  goto fail;
691 
692  if (seg->write_header_trailer) {
693  if ((ret = avio_open2(&oc->pb, seg->header_filename ? seg->header_filename : oc->filename, AVIO_FLAG_WRITE,
694  &s->interrupt_callback, NULL)) < 0) {
695  av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
696  goto fail;
697  }
698  if (!seg->individual_header_trailer)
699  oc->pb->seekable = 0;
700  } else {
701  if ((ret = open_null_ctx(&oc->pb)) < 0)
702  goto fail;
703  }
704 
705  av_dict_copy(&options, seg->format_options, 0);
706  ret = avformat_write_header(oc, &options);
707  if (av_dict_count(options)) {
708  av_log(s, AV_LOG_ERROR,
709  "Some of the provided format options in '%s' are not recognized\n", seg->format_options_str);
710  ret = AVERROR(EINVAL);
711  goto fail;
712  }
713 
714  if (ret < 0) {
715  avio_closep(&oc->pb);
716  goto fail;
717  }
718  seg->segment_frame_count = 0;
719 
720  av_assert0(s->nb_streams == oc->nb_streams);
721  for (i = 0; i < s->nb_streams; i++) {
722  AVStream *inner_st = oc->streams[i];
723  AVStream *outer_st = s->streams[i];
724  avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
725  }
726 
727  if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
728  s->avoid_negative_ts = 1;
729 
730  if (!seg->write_header_trailer || seg->header_filename) {
731  if (seg->header_filename) {
732  av_write_frame(oc, NULL);
733  avio_closep(&oc->pb);
734  } else {
735  close_null_ctxp(&oc->pb);
736  }
737  if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
738  &s->interrupt_callback, NULL)) < 0)
739  goto fail;
740  if (!seg->individual_header_trailer)
741  oc->pb->seekable = 0;
742  }
743 
744 fail:
745  av_dict_free(&options);
746  if (ret < 0)
747  seg_free_context(seg);
748 
749  return ret;
750 }
751 
753 {
754  SegmentContext *seg = s->priv_data;
755  AVStream *st = s->streams[pkt->stream_index];
756  int64_t end_pts = INT64_MAX, offset;
757  int start_frame = INT_MAX;
758  int ret;
759  struct tm ti;
760  int64_t usecs;
761  int64_t wrapped_val;
762 
763  if (!seg->avf)
764  return AVERROR(EINVAL);
765 
766  if (seg->times) {
767  end_pts = seg->segment_count < seg->nb_times ?
768  seg->times[seg->segment_count] : INT64_MAX;
769  } else if (seg->frames) {
770  start_frame = seg->segment_count < seg->nb_frames ?
771  seg->frames[seg->segment_count] : INT_MAX;
772  } else {
773  if (seg->use_clocktime) {
774  int64_t avgt = av_gettime();
775  time_t sec = avgt / 1000000;
776  localtime_r(&sec, &ti);
777  usecs = (int64_t)(ti.tm_hour * 3600 + ti.tm_min * 60 + ti.tm_sec) * 1000000 + (avgt % 1000000);
778  wrapped_val = usecs % seg->time;
779  if (seg->last_cut != usecs && wrapped_val < seg->last_val) {
780  seg->cut_pending = 1;
781  seg->last_cut = usecs;
782  }
783  seg->last_val = wrapped_val;
784  } else {
785  end_pts = seg->time * (seg->segment_count + 1);
786  }
787  }
788 
789  ff_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",
790  pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
791  av_ts2timestr(pkt->duration, &st->time_base),
792  pkt->flags & AV_PKT_FLAG_KEY,
793  pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);
794 
795  if (pkt->stream_index == seg->reference_stream_index &&
796  (pkt->flags & AV_PKT_FLAG_KEY || seg->break_non_keyframes) &&
797  seg->segment_frame_count > 0 &&
798  (seg->cut_pending || seg->frame_count >= start_frame ||
799  (pkt->pts != AV_NOPTS_VALUE &&
800  av_compare_ts(pkt->pts, st->time_base,
801  end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0))) {
802  /* sanitize end time in case last packet didn't have a defined duration */
803  if (seg->cur_entry.last_duration == 0)
804  seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);
805 
806  if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)
807  goto fail;
808 
809  if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)
810  goto fail;
811 
812  seg->cut_pending = 0;
814  seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);
816  seg->cur_entry.end_time = seg->cur_entry.start_time +
817  pkt->pts != AV_NOPTS_VALUE ? (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base) : 0;
818  } else if (pkt->pts != AV_NOPTS_VALUE && pkt->stream_index == seg->reference_stream_index) {
819  seg->cur_entry.end_time =
820  FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
821  seg->cur_entry.last_duration = pkt->duration;
822  }
823 
824  if (seg->segment_frame_count == 0) {
825  av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",
826  seg->avf->filename, pkt->stream_index,
827  av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);
828  }
829 
830  av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",
831  pkt->stream_index,
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  /* compute new timestamps */
837  offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),
839  if (pkt->pts != AV_NOPTS_VALUE)
840  pkt->pts += offset;
841  if (pkt->dts != AV_NOPTS_VALUE)
842  pkt->dts += offset;
843 
844  av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
845  av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
846  av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
847 
848  ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s, seg->initial_offset || seg->reset_timestamps);
849 
850 fail:
851  if (pkt->stream_index == seg->reference_stream_index) {
852  seg->frame_count++;
853  seg->segment_frame_count++;
854  }
855 
856  if (ret < 0)
857  seg_free_context(seg);
858 
859  return ret;
860 }
861 
863 {
864  SegmentContext *seg = s->priv_data;
865  AVFormatContext *oc = seg->avf;
866  SegmentListEntry *cur, *next;
867  int ret = 0;
868 
869  if (!oc)
870  goto fail;
871 
872  if (!seg->write_header_trailer) {
873  if ((ret = segment_end(s, 0, 1)) < 0)
874  goto fail;
875  if ((ret = open_null_ctx(&oc->pb)) < 0)
876  goto fail;
877  ret = av_write_trailer(oc);
878  close_null_ctxp(&oc->pb);
879  } else {
880  ret = segment_end(s, 1, 1);
881  }
882 fail:
883  if (seg->list)
884  avio_closep(&seg->list_pb);
885 
887  av_opt_free(seg);
888  av_freep(&seg->times);
889  av_freep(&seg->frames);
890  av_freep(&seg->cur_entry.filename);
891 
892  cur = seg->segment_list_entries;
893  while (cur) {
894  next = cur->next;
895  av_freep(&cur->filename);
896  av_free(cur);
897  cur = next;
898  }
899 
901  seg->avf = NULL;
902  return ret;
903 }
904 
905 #define OFFSET(x) offsetof(SegmentContext, x)
906 #define E AV_OPT_FLAG_ENCODING_PARAM
907 static const AVOption options[] = {
908  { "reference_stream", "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, CHAR_MIN, CHAR_MAX, E },
909  { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
910  { "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 },
911  { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
912  { "segment_header_filename", "write a single file containing the header", OFFSET(header_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
913 
914  { "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"},
915  { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
916  { "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"},
917 
918  { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
919 
920  { "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" },
921  { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" },
922  { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, E, "list_type" },
923  { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, E, "list_type" },
924  { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" },
925  { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
926  { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
927 
928  { "segment_atclocktime", "set segment to be cut at clocktime", OFFSET(use_clocktime), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E},
929  { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
930  { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 0, E },
931  { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
932  { "segment_frames", "set segment split frame numbers", OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
933  { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
934  { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
935  { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
936  { "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 },
937  { "strftime", "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, E },
938  { "break_non_keyframes", "allow breaking segments on non-keyframes", OFFSET(break_non_keyframes), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
939 
940  { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
941  { "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 },
942  { "reset_timestamps", "reset timestamps at the begin of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
943  { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
944  { NULL },
945 };
946 
947 static const AVClass seg_class = {
948  .class_name = "segment muxer",
949  .item_name = av_default_item_name,
950  .option = options,
951  .version = LIBAVUTIL_VERSION_INT,
952 };
953 
955  .name = "segment",
956  .long_name = NULL_IF_CONFIG_SMALL("segment"),
957  .priv_data_size = sizeof(SegmentContext),
962  .priv_class = &seg_class,
963 };
964 
965 static const AVClass sseg_class = {
966  .class_name = "stream_segment muxer",
967  .item_name = av_default_item_name,
968  .option = options,
969  .version = LIBAVUTIL_VERSION_INT,
970 };
971 
973  .name = "stream_segment,ssegment",
974  .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
975  .priv_data_size = sizeof(SegmentContext),
976  .flags = AVFMT_NOFILE,
980  .priv_class = &sseg_class,
981 };
struct SegmentListEntry * next
Definition: segment.c:52
#define NULL
Definition: coverity.c:32
AVFormatContext * avf
Definition: segment.c:76
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:1523
char * header_filename
filename to write the output header to
Definition: segment.c:109
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:447
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file.
Definition: mux.c:691
#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:89
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:4083
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:558
AVDictionary * format_options
Definition: segment.c:79
static int segment_start(AVFormatContext *s, int write_header)
Definition: segment.c:219
int segment_idx_wrap
number after which the index wraps
Definition: segment.c:72
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:1041
#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:486
static AVPacket pkt
int segment_frame_count
number of reference frames in the segment
Definition: segment.c:104
char * filename
Definition: segment.c:51
int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src)
Copy the settings of the source AVCodecContext into the destination AVCodecContext.
Definition: options.c:182
static int parse_frames(void *log_ctx, int **frames, int *nb_frames, const char *frames_str)
Definition: segment.c:453
static int seg_write_header(AVFormatContext *s)
Definition: segment.c:596
static int segment_end(AVFormatContext *s, int write_trailer, int is_last)
Definition: segment.c:331
int list_flags
flags affecting list generation
Definition: segment.c:81
static int segment_mux_init(AVFormatContext *s)
Definition: segment.c:141
Format I/O context.
Definition: avformat.h:1273
int64_t last_duration
Definition: segment.c:53
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:526
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:195
char temp_list_filename[1024]
Definition: segment.c:118
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:90
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:4309
static int seg_write_trailer(struct AVFormatContext *s)
Definition: segment.c:862
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:3749
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1341
static double av_q2d(AVRational a)
Convert rational to double.
Definition: rational.h:80
#define ff_dlog(a,...)
#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:1441
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:77
static int select_reference_stream(AVFormatContext *s)
Definition: segment.c:532
#define av_log(a,...)
int break_non_keyframes
Definition: segment.c:115
struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:1292
int64_t time_delta
Definition: segment.c:106
int64_t initial_offset
initial timestamps offset, expressed in microseconds
Definition: segment.c:112
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1469
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:112
#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:1485
int individual_header_trailer
Set by a private option.
Definition: segment.c:107
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().
int use_rename
Definition: segment.c:117
int64_t * times
list of segment interval specification
Definition: segment.c:97
static const uint8_t offset[127][2]
Definition: vf_spp.c:92
char * reference_stream_specifier
reference stream specifier
Definition: segment.c:113
#define FFMAX(a, b)
Definition: common.h:79
static int set_segment_filename(AVFormatContext *s)
Definition: segment.c:181
int64_t offset_pts
Definition: segment.c:50
#define fail()
Definition: checkasm.h:57
int reference_stream_index
Definition: segment.c:114
int nb_times
number of elments in the times array
Definition: segment.c:98
#define OFFSET(x)
Definition: segment.c:905
static int segment_list_open(AVFormatContext *s)
Definition: segment.c:260
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1429
int64_t last_val
remember last time for wrap around detection
Definition: segment.c:85
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:91
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:861
common internal API header
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1329
static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
Definition: segment.c:125
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:198
char filename[1024]
input or output filename
Definition: avformat.h:1349
int cut_pending
Definition: segment.c:87
static struct tm * localtime_r(const time_t *clock, struct tm *result)
Definition: time_internal.h:37
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:965
int use_strftime
flag to expand filename with strftime
Definition: segment.c:94
const char * name
Definition: avformat.h:513
int reset_timestamps
reset timestamps at the begin of each segment
Definition: segment.c:111
int use_clocktime
flag to cut segments at regular clock time
Definition: segment.c:84
ListType
Definition: segment.c:56
int avoid_negative_ts
Avoid negative timestamps during muxing.
Definition: avformat.h:1576
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:197
const AVClass * priv_class
AVClass for the private context.
Definition: avformat.h:541
#define FF_ARRAY_ELEMS(a)
#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:3908
static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: segment.c:752
int64_t av_gettime(void)
Get the current time in microseconds.
Definition: time.c:39
Stream structure.
Definition: avformat.h:842
char * list
filename for the segment list file
Definition: segment.c:80
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:100
enum AVMediaType codec_type
Definition: avcodec.h:1510
enum AVCodecID codec_id
Definition: avcodec.h:1519
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:252
char * av_strdup(const char *s)
Duplicate the string s.
Definition: mem.c:267
AVIOContext * pb
I/O context.
Definition: avformat.h:1315
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:156
main external API structure.
Definition: avcodec.h:1502
int64_t time
segment duration
Definition: segment.c:93
unsigned int codec_tag
fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
Definition: avcodec.h:1534
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:90
AVOutputFormat ff_segment_muxer
Definition: segment.c:954
static int ff_rename(const char *oldpath, const char *newpath, void *logctx)
Wrap errno on rename() error.
Definition: internal.h:447
int segment_idx
index of the segment file to write, starting from 0
Definition: segment.c:71
Describe the class of an AVClass context structure.
Definition: log.h:67
int * frames
list of frame number specification
Definition: segment.c:101
int64_t start_pts
Definition: segment.c:49
char * time_str
segment duration specification string
Definition: segment.c:92
AVMediaType
Definition: avutil.h:191
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:918
#define snprintf
Definition: snprintf.h:34
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:3686
misc parsing utilities
const char * avio_find_protocol_name(const char *url)
Return the name of the protocol that will handle the passed URL.
Definition: avio.c:418
SegmentListEntry * segment_list_entries
Definition: segment.c:121
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:79
int nb_frames
number of elments in the frames array
Definition: segment.c:102
static int flags
Definition: cpu.c:47
int write_header_trailer
Set by a private option.
Definition: segment.c:108
char * format_options_str
format options to use for output segment files
Definition: segment.c:78
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:296
double end_time
Definition: segment.c:48
static const AVClass seg_class
Definition: segment.c:947
Main libavformat public API header.
void av_opt_free(void *obj)
Free all allocated objects in obj.
Definition: opt.c:1432
#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:66
#define E
Definition: segment.c:906
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:395
int den
denominator
Definition: rational.h:45
double start_time
Definition: segment.c:48
#define av_free(p)
int segment_idx_wrap_nb
number of time the index has wraped
Definition: segment.c:73
#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:1301
static const AVOption options[]
Definition: segment.c:907
int64_t last_cut
remember last cut
Definition: segment.c:86
#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:972
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1422
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition: mux.c:986
static int open_null_ctx(AVIOContext **ctx)
Definition: segment.c:512
#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:74
static void seg_free_context(SegmentContext *seg)
Definition: segment.c:589
char * times_str
segment times specification string
Definition: segment.c:96
#define av_malloc_array(a, b)
int stream_index
Definition: avcodec.h:1425
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:120
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:82
deprecated
Definition: segment.c:61
This structure stores compressed data.
Definition: avcodec.h:1400
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:959
int frame_count
total number of reference frames
Definition: segment.c:103
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:252
#define SEGMENT_LIST_FLAG_LIVE
Definition: segment.c:67
SegmentListEntry * segment_list_entries_end
Definition: segment.c:122
AVOutputFormat * oformat
Definition: segment.c:75
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1416
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:240
int avio_printf(AVIOContext *s, const char *fmt,...) av_printf_format(2