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