FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
segment.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2011, Luca Barbato
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 /**
22  * @file generic segmenter
23  * M3U8 specification can be find here:
24  * @url{http://tools.ietf.org/id/draft-pantos-http-live-streaming}
25  */
26 
27 /* #define DEBUG */
28 
29 #include <float.h>
30 #include <time.h>
31 
32 #include "avformat.h"
33 #include "internal.h"
34 
35 #include "libavutil/avassert.h"
36 #include "libavutil/log.h"
37 #include "libavutil/opt.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/parseutils.h"
40 #include "libavutil/mathematics.h"
41 #include "libavutil/time.h"
42 #include "libavutil/timestamp.h"
43 
44 typedef struct SegmentListEntry {
45  int index;
47  int64_t start_pts;
48  int64_t offset_pts;
49  char *filename;
51  int64_t last_duration;
53 
54 typedef enum {
59  LIST_TYPE_EXT, ///< deprecated
62 } ListType;
63 
64 #define SEGMENT_LIST_FLAG_CACHE 1
65 #define SEGMENT_LIST_FLAG_LIVE 2
66 
67 typedef struct {
68  const AVClass *class; /**< Class for private options. */
69  int segment_idx; ///< index of the segment file to write, starting from 0
70  int segment_idx_wrap; ///< number after which the index wraps
71  int segment_idx_wrap_nb; ///< number of time the index has wraped
72  int segment_count; ///< number of segment files already written
75  char *format; ///< format to use for output segment files
76  char *format_options_str; ///< format options to use for output segment files
78  char *list; ///< filename for the segment list file
79  int list_flags; ///< flags affecting list generation
80  int list_size; ///< number of entries for the segment list file
81 
82  int use_clocktime; ///< flag to cut segments at regular clock time
83  int64_t last_val; ///< remember last time for wrap around detection
84  int64_t last_cut; ///< remember last cut
86 
87  char *entry_prefix; ///< prefix to add to list entry filenames
88  ListType list_type; ///< set the list type
89  AVIOContext *list_pb; ///< list file put-byte context
90  char *time_str; ///< segment duration specification string
91  int64_t time; ///< segment duration
92 
93  char *times_str; ///< segment times specification string
94  int64_t *times; ///< list of segment interval specification
95  int nb_times; ///< number of elments in the times array
96 
97  char *frames_str; ///< segment frame numbers specification string
98  int *frames; ///< list of frame number specification
99  int nb_frames; ///< number of elments in the frames array
100  int frame_count; ///< total number of reference frames
101  int segment_frame_count; ///< number of reference frames in the segment
102 
103  int64_t time_delta;
104  int individual_header_trailer; /**< Set by a private option. */
105  int write_header_trailer; /**< Set by a private option. */
106 
107  int reset_timestamps; ///< reset timestamps at the begin of each segment
108  int64_t initial_offset; ///< initial timestamps offset, expressed in microseconds
109  char *reference_stream_specifier; ///< reference stream specifier
111 
116 
117 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
118 {
119  int needs_quoting = !!str[strcspn(str, "\",\n\r")];
120 
121  if (needs_quoting)
122  avio_w8(ctx, '"');
123 
124  for (; *str; str++) {
125  if (*str == '"')
126  avio_w8(ctx, '"');
127  avio_w8(ctx, *str);
128  }
129  if (needs_quoting)
130  avio_w8(ctx, '"');
131 }
132 
134 {
135  SegmentContext *seg = s->priv_data;
136  AVFormatContext *oc;
137  int i;
138  int ret;
139 
140  ret = avformat_alloc_output_context2(&seg->avf, seg->oformat, NULL, NULL);
141  if (ret < 0)
142  return ret;
143  oc = seg->avf;
144 
146  oc->max_delay = s->max_delay;
147  av_dict_copy(&oc->metadata, s->metadata, 0);
148 
149  for (i = 0; i < s->nb_streams; i++) {
150  AVStream *st;
151  AVCodecContext *icodec, *ocodec;
152 
153  if (!(st = avformat_new_stream(oc, NULL)))
154  return AVERROR(ENOMEM);
155  icodec = s->streams[i]->codec;
156  ocodec = st->codec;
157  avcodec_copy_context(ocodec, icodec);
158  if (!oc->oformat->codec_tag ||
159  av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == ocodec->codec_id ||
160  av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0) {
161  ocodec->codec_tag = icodec->codec_tag;
162  } else {
163  ocodec->codec_tag = 0;
164  }
166  st->time_base = s->streams[i]->time_base;
167  av_dict_copy(&st->metadata, s->streams[i]->metadata, 0);
168  }
169 
170  return 0;
171 }
172 
174 {
175  SegmentContext *seg = s->priv_data;
176  AVFormatContext *oc = seg->avf;
177  size_t size;
178 
179  if (seg->segment_idx_wrap)
180  seg->segment_idx %= seg->segment_idx_wrap;
181  if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
182  s->filename, seg->segment_idx) < 0) {
183  av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
184  return AVERROR(EINVAL);
185  }
186 
187  /* copy modified name in list entry */
188  size = strlen(av_basename(oc->filename)) + 1;
189  if (seg->entry_prefix)
190  size += strlen(seg->entry_prefix);
191 
192  seg->cur_entry.filename = av_mallocz(size);
193  if (!seg->cur_entry.filename)
194  return AVERROR(ENOMEM);
195  snprintf(seg->cur_entry.filename, size, "%s%s",
196  seg->entry_prefix ? seg->entry_prefix : "",
197  av_basename(oc->filename));
198 
199  return 0;
200 }
201 
203 {
204  SegmentContext *seg = s->priv_data;
205  AVFormatContext *oc = seg->avf;
206  int err = 0;
207 
208  if (write_header) {
210  seg->avf = NULL;
211  if ((err = segment_mux_init(s)) < 0)
212  return err;
213  oc = seg->avf;
214  }
215 
216  seg->segment_idx++;
217  if ((seg->segment_idx_wrap) && (seg->segment_idx%seg->segment_idx_wrap == 0))
218  seg->segment_idx_wrap_nb++;
219 
220  if ((err = set_segment_filename(s)) < 0)
221  return err;
222 
223  if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
224  &s->interrupt_callback, NULL)) < 0) {
225  av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
226  return err;
227  }
228 
229  if (oc->oformat->priv_class && oc->priv_data)
230  av_opt_set(oc->priv_data, "mpegts_flags", "+resend_headers", 0);
231 
232  if (write_header) {
233  if ((err = avformat_write_header(oc, NULL)) < 0)
234  return err;
235  }
236 
237  seg->segment_frame_count = 0;
238  return 0;
239 }
240 
242 {
243  SegmentContext *seg = s->priv_data;
244  int ret;
245 
246  ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
247  &s->interrupt_callback, NULL);
248  if (ret < 0) {
249  av_log(s, AV_LOG_ERROR, "Failed to open segment list '%s'\n", seg->list);
250  return ret;
251  }
252 
253  if (seg->list_type == LIST_TYPE_M3U8 && seg->segment_list_entries) {
254  SegmentListEntry *entry;
255  double max_duration = 0;
256 
257  avio_printf(seg->list_pb, "#EXTM3U\n");
258  avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
259  avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_list_entries->index);
260  avio_printf(seg->list_pb, "#EXT-X-ALLOW-CACHE:%s\n",
261  seg->list_flags & SEGMENT_LIST_FLAG_CACHE ? "YES" : "NO");
262 
263  av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n",
265 
266  for (entry = seg->segment_list_entries; entry; entry = entry->next)
267  max_duration = FFMAX(max_duration, entry->end_time - entry->start_time);
268  avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%"PRId64"\n", (int64_t)ceil(max_duration));
269  } else if (seg->list_type == LIST_TYPE_FFCONCAT) {
270  avio_printf(seg->list_pb, "ffconcat version 1.0\n");
271  }
272 
273  return ret;
274 }
275 
276 static void segment_list_print_entry(AVIOContext *list_ioctx,
277  ListType list_type,
278  const SegmentListEntry *list_entry,
279  void *log_ctx)
280 {
281  switch (list_type) {
282  case LIST_TYPE_FLAT:
283  avio_printf(list_ioctx, "%s\n", list_entry->filename);
284  break;
285  case LIST_TYPE_CSV:
286  case LIST_TYPE_EXT:
287  print_csv_escaped_str(list_ioctx, list_entry->filename);
288  avio_printf(list_ioctx, ",%f,%f\n", list_entry->start_time, list_entry->end_time);
289  break;
290  case LIST_TYPE_M3U8:
291  avio_printf(list_ioctx, "#EXTINF:%f,\n%s\n",
292  list_entry->end_time - list_entry->start_time, list_entry->filename);
293  break;
294  case LIST_TYPE_FFCONCAT:
295  {
296  char *buf;
297  if (av_escape(&buf, list_entry->filename, NULL, AV_ESCAPE_MODE_AUTO, AV_ESCAPE_FLAG_WHITESPACE) < 0) {
298  av_log(log_ctx, AV_LOG_WARNING,
299  "Error writing list entry '%s' in list file\n", list_entry->filename);
300  return;
301  }
302  avio_printf(list_ioctx, "file %s\n", buf);
303  av_free(buf);
304  break;
305  }
306  default:
307  av_assert0(!"Invalid list type");
308  }
309 }
310 
311 static int segment_end(AVFormatContext *s, int write_trailer, int is_last)
312 {
313  SegmentContext *seg = s->priv_data;
314  AVFormatContext *oc = seg->avf;
315  int ret = 0;
316 
317  av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
318  if (write_trailer)
319  ret = av_write_trailer(oc);
320 
321  if (ret < 0)
322  av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
323  oc->filename);
324 
325  if (seg->list) {
326  if (seg->list_size || seg->list_type == LIST_TYPE_M3U8) {
327  SegmentListEntry *entry = av_mallocz(sizeof(*entry));
328  if (!entry) {
329  ret = AVERROR(ENOMEM);
330  goto end;
331  }
332 
333  /* append new element */
334  memcpy(entry, &seg->cur_entry, sizeof(*entry));
335  if (!seg->segment_list_entries)
337  else
338  seg->segment_list_entries_end->next = entry;
339  seg->segment_list_entries_end = entry;
340 
341  /* drop first item */
342  if (seg->list_size && seg->segment_count >= seg->list_size) {
343  entry = seg->segment_list_entries;
345  av_free(entry->filename);
346  av_freep(&entry);
347  }
348 
349  avio_close(seg->list_pb);
350  if ((ret = segment_list_open(s)) < 0)
351  goto end;
352  for (entry = seg->segment_list_entries; entry; entry = entry->next)
353  segment_list_print_entry(seg->list_pb, seg->list_type, entry, s);
354  if (seg->list_type == LIST_TYPE_M3U8 && is_last)
355  avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
356  } else {
357  segment_list_print_entry(seg->list_pb, seg->list_type, &seg->cur_entry, s);
358  }
359  avio_flush(seg->list_pb);
360  }
361 
362  av_log(s, AV_LOG_VERBOSE, "segment:'%s' count:%d ended\n",
363  seg->avf->filename, seg->segment_count);
364  seg->segment_count++;
365 
366 end:
367  avio_close(oc->pb);
368 
369  return ret;
370 }
371 
372 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
373  const char *times_str)
374 {
375  char *p;
376  int i, ret = 0;
377  char *times_str1 = av_strdup(times_str);
378  char *saveptr = NULL;
379 
380  if (!times_str1)
381  return AVERROR(ENOMEM);
382 
383 #define FAIL(err) ret = err; goto end
384 
385  *nb_times = 1;
386  for (p = times_str1; *p; p++)
387  if (*p == ',')
388  (*nb_times)++;
389 
390  *times = av_malloc_array(*nb_times, sizeof(**times));
391  if (!*times) {
392  av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
393  FAIL(AVERROR(ENOMEM));
394  }
395 
396  p = times_str1;
397  for (i = 0; i < *nb_times; i++) {
398  int64_t t;
399  char *tstr = av_strtok(p, ",", &saveptr);
400  p = NULL;
401 
402  if (!tstr || !tstr[0]) {
403  av_log(log_ctx, AV_LOG_ERROR, "Empty time specification in times list %s\n",
404  times_str);
405  FAIL(AVERROR(EINVAL));
406  }
407 
408  ret = av_parse_time(&t, tstr, 1);
409  if (ret < 0) {
410  av_log(log_ctx, AV_LOG_ERROR,
411  "Invalid time duration specification '%s' in times list %s\n", tstr, times_str);
412  FAIL(AVERROR(EINVAL));
413  }
414  (*times)[i] = t;
415 
416  /* check on monotonicity */
417  if (i && (*times)[i-1] > (*times)[i]) {
418  av_log(log_ctx, AV_LOG_ERROR,
419  "Specified time %f is greater than the following time %f\n",
420  (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
421  FAIL(AVERROR(EINVAL));
422  }
423  }
424 
425 end:
426  av_free(times_str1);
427  return ret;
428 }
429 
430 static int parse_frames(void *log_ctx, int **frames, int *nb_frames,
431  const char *frames_str)
432 {
433  char *p;
434  int i, ret = 0;
435  char *frames_str1 = av_strdup(frames_str);
436  char *saveptr = NULL;
437 
438  if (!frames_str1)
439  return AVERROR(ENOMEM);
440 
441 #define FAIL(err) ret = err; goto end
442 
443  *nb_frames = 1;
444  for (p = frames_str1; *p; p++)
445  if (*p == ',')
446  (*nb_frames)++;
447 
448  *frames = av_malloc_array(*nb_frames, sizeof(**frames));
449  if (!*frames) {
450  av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced frames array\n");
451  FAIL(AVERROR(ENOMEM));
452  }
453 
454  p = frames_str1;
455  for (i = 0; i < *nb_frames; i++) {
456  long int f;
457  char *tailptr;
458  char *fstr = av_strtok(p, ",", &saveptr);
459 
460  p = NULL;
461  if (!fstr) {
462  av_log(log_ctx, AV_LOG_ERROR, "Empty frame specification in frame list %s\n",
463  frames_str);
464  FAIL(AVERROR(EINVAL));
465  }
466  f = strtol(fstr, &tailptr, 10);
467  if (*tailptr || f <= 0 || f >= INT_MAX) {
468  av_log(log_ctx, AV_LOG_ERROR,
469  "Invalid argument '%s', must be a positive integer <= INT64_MAX\n",
470  fstr);
471  FAIL(AVERROR(EINVAL));
472  }
473  (*frames)[i] = f;
474 
475  /* check on monotonicity */
476  if (i && (*frames)[i-1] > (*frames)[i]) {
477  av_log(log_ctx, AV_LOG_ERROR,
478  "Specified frame %d is greater than the following frame %d\n",
479  (*frames)[i], (*frames)[i-1]);
480  FAIL(AVERROR(EINVAL));
481  }
482  }
483 
484 end:
485  av_free(frames_str1);
486  return ret;
487 }
488 
489 static int open_null_ctx(AVIOContext **ctx)
490 {
491  int buf_size = 32768;
492  uint8_t *buf = av_malloc(buf_size);
493  if (!buf)
494  return AVERROR(ENOMEM);
495  *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
496  if (!*ctx) {
497  av_free(buf);
498  return AVERROR(ENOMEM);
499  }
500  return 0;
501 }
502 
503 static void close_null_ctx(AVIOContext *pb)
504 {
505  av_free(pb->buffer);
506  av_free(pb);
507 }
508 
510 {
511  SegmentContext *seg = s->priv_data;
512  int ret, i;
513 
514  seg->reference_stream_index = -1;
515  if (!strcmp(seg->reference_stream_specifier, "auto")) {
516  /* select first index of type with highest priority */
517  int type_index_map[AVMEDIA_TYPE_NB];
518  static const enum AVMediaType type_priority_list[] = {
524  };
525  enum AVMediaType type;
526 
527  for (i = 0; i < AVMEDIA_TYPE_NB; i++)
528  type_index_map[i] = -1;
529 
530  /* select first index for each type */
531  for (i = 0; i < s->nb_streams; i++) {
532  type = s->streams[i]->codec->codec_type;
533  if ((unsigned)type < AVMEDIA_TYPE_NB && type_index_map[type] == -1
534  /* ignore attached pictures/cover art streams */
536  type_index_map[type] = i;
537  }
538 
539  for (i = 0; i < FF_ARRAY_ELEMS(type_priority_list); i++) {
540  type = type_priority_list[i];
541  if ((seg->reference_stream_index = type_index_map[type]) >= 0)
542  break;
543  }
544  } else {
545  for (i = 0; i < s->nb_streams; i++) {
548  if (ret < 0)
549  return ret;
550  if (ret > 0) {
551  seg->reference_stream_index = i;
552  break;
553  }
554  }
555  }
556 
557  if (seg->reference_stream_index < 0) {
558  av_log(s, AV_LOG_ERROR, "Could not select stream matching identifier '%s'\n",
560  return AVERROR(EINVAL);
561  }
562 
563  return 0;
564 }
565 
567 {
568  SegmentContext *seg = s->priv_data;
569  AVFormatContext *oc = NULL;
570  AVDictionary *options = NULL;
571  int ret;
572 
573  seg->segment_count = 0;
574  if (!seg->write_header_trailer)
575  seg->individual_header_trailer = 0;
576 
577  if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) {
578  av_log(s, AV_LOG_ERROR,
579  "segment_time, segment_times, and segment_frames options "
580  "are mutually exclusive, select just one of them\n");
581  return AVERROR(EINVAL);
582  }
583 
584  if (seg->times_str) {
585  if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
586  return ret;
587  } else if (seg->frames_str) {
588  if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
589  return ret;
590  } else {
591  /* set default value if not specified */
592  if (!seg->time_str)
593  seg->time_str = av_strdup("2");
594  if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
595  av_log(s, AV_LOG_ERROR,
596  "Invalid time duration specification '%s' for segment_time option\n",
597  seg->time_str);
598  return ret;
599  }
600  }
601 
602  if (seg->format_options_str) {
603  ret = av_dict_parse_string(&seg->format_options, seg->format_options_str, "=", ":", 0);
604  if (ret < 0) {
605  av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
606  seg->format_options_str);
607  goto fail;
608  }
609  }
610 
611  if (seg->list) {
612  if (seg->list_type == LIST_TYPE_UNDEFINED) {
613  if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
614  else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
615  else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
616  else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
617  else seg->list_type = LIST_TYPE_FLAT;
618  }
619  if ((ret = segment_list_open(s)) < 0)
620  goto fail;
621  }
622  if (seg->list_type == LIST_TYPE_EXT)
623  av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
624 
625  if ((ret = select_reference_stream(s)) < 0)
626  goto fail;
627  av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
630 
631  seg->oformat = av_guess_format(seg->format, s->filename, NULL);
632 
633  if (!seg->oformat) {
635  goto fail;
636  }
637  if (seg->oformat->flags & AVFMT_NOFILE) {
638  av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
639  seg->oformat->name);
640  ret = AVERROR(EINVAL);
641  goto fail;
642  }
643 
644  if ((ret = segment_mux_init(s)) < 0)
645  goto fail;
646  oc = seg->avf;
647 
648  if ((ret = set_segment_filename(s)) < 0)
649  goto fail;
650 
651  if (seg->write_header_trailer) {
652  if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
653  &s->interrupt_callback, NULL)) < 0) {
654  av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
655  goto fail;
656  }
657  } else {
658  if ((ret = open_null_ctx(&oc->pb)) < 0)
659  goto fail;
660  }
661 
662  av_dict_copy(&options, seg->format_options, 0);
663  ret = avformat_write_header(oc, &options);
664  if (av_dict_count(options)) {
665  av_log(s, AV_LOG_ERROR,
666  "Some of the provided format options in '%s' are not recognized\n", seg->format_options_str);
667  ret = AVERROR(EINVAL);
668  goto fail;
669  }
670 
671  if (ret < 0) {
672  avio_close(oc->pb);
673  goto fail;
674  }
675  seg->segment_frame_count = 0;
676 
677  if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
678  s->avoid_negative_ts = 1;
679 
680  if (!seg->write_header_trailer) {
681  close_null_ctx(oc->pb);
682  if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
683  &s->interrupt_callback, NULL)) < 0)
684  goto fail;
685  }
686 
687 fail:
688  av_dict_free(&options);
689  if (ret) {
690  if (seg->list)
691  avio_close(seg->list_pb);
692  if (seg->avf)
694  }
695  return ret;
696 }
697 
699 {
700  SegmentContext *seg = s->priv_data;
701  AVStream *st = s->streams[pkt->stream_index];
702  int64_t end_pts = INT64_MAX, offset;
703  int start_frame = INT_MAX;
704  int ret;
705  struct tm ti;
706  int64_t usecs;
707  int64_t wrapped_val;
708 
709  if (seg->times) {
710  end_pts = seg->segment_count < seg->nb_times ?
711  seg->times[seg->segment_count] : INT64_MAX;
712  } else if (seg->frames) {
713  start_frame = seg->segment_count < seg->nb_frames ?
714  seg->frames[seg->segment_count] : INT_MAX;
715  } else {
716  if (seg->use_clocktime) {
717  int64_t avgt = av_gettime();
718  time_t sec = avgt / 1000000;
719 #if HAVE_LOCALTIME_R
720  localtime_r(&sec, &ti);
721 #else
722  ti = *localtime(&sec);
723 #endif
724  usecs = (int64_t)(ti.tm_hour*3600 + ti.tm_min*60 + ti.tm_sec) * 1000000 + (avgt % 1000000);
725  wrapped_val = usecs % seg->time;
726  if (seg->last_cut != usecs && wrapped_val < seg->last_val) {
727  seg->cut_pending = 1;
728  seg->last_cut = usecs;
729  }
730  seg->last_val = wrapped_val;
731  } else {
732  end_pts = seg->time * (seg->segment_count+1);
733  }
734  }
735 
736  av_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",
737  pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
738  av_ts2timestr(pkt->duration, &st->time_base),
739  pkt->flags & AV_PKT_FLAG_KEY,
740  pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);
741 
742  if (pkt->stream_index == seg->reference_stream_index &&
743  pkt->flags & AV_PKT_FLAG_KEY &&
744  seg->segment_frame_count > 0 &&
745  (seg->cut_pending || seg->frame_count >= start_frame ||
746  (pkt->pts != AV_NOPTS_VALUE &&
747  av_compare_ts(pkt->pts, st->time_base,
748  end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0))) {
749  /* sanitize end time in case last packet didn't have a defined duration */
750  if (seg->cur_entry.last_duration == 0)
751  seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);
752 
753  if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)
754  goto fail;
755 
756  if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)
757  goto fail;
758 
759  seg->cut_pending = 0;
761  seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);
763  seg->cur_entry.end_time = seg->cur_entry.start_time +
764  pkt->pts != AV_NOPTS_VALUE ? (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base) : 0;
765  } else if (pkt->pts != AV_NOPTS_VALUE && pkt->stream_index == seg->reference_stream_index) {
766  seg->cur_entry.end_time =
767  FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
768  seg->cur_entry.last_duration = pkt->duration;
769  }
770 
771  if (seg->segment_frame_count == 0) {
772  av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",
773  seg->avf->filename, pkt->stream_index,
774  av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);
775  }
776 
777  av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",
778  pkt->stream_index,
780  av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
781  av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
782 
783  /* compute new timestamps */
784  offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),
786  if (pkt->pts != AV_NOPTS_VALUE)
787  pkt->pts += offset;
788  if (pkt->dts != AV_NOPTS_VALUE)
789  pkt->dts += offset;
790 
791  av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
792  av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
793  av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
794 
795  ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s, seg->initial_offset || seg->reset_timestamps);
796 
797 fail:
798  if (pkt->stream_index == seg->reference_stream_index) {
799  seg->frame_count++;
800  seg->segment_frame_count++;
801  }
802 
803  return ret;
804 }
805 
807 {
808  SegmentContext *seg = s->priv_data;
809  AVFormatContext *oc = seg->avf;
810  SegmentListEntry *cur, *next;
811 
812  int ret;
813  if (!seg->write_header_trailer) {
814  if ((ret = segment_end(s, 0, 1)) < 0)
815  goto fail;
816  open_null_ctx(&oc->pb);
817  ret = av_write_trailer(oc);
818  close_null_ctx(oc->pb);
819  } else {
820  ret = segment_end(s, 1, 1);
821  }
822 fail:
823  if (seg->list)
824  avio_close(seg->list_pb);
825 
827  av_opt_free(seg);
828  av_freep(&seg->times);
829  av_freep(&seg->frames);
830 
831  cur = seg->segment_list_entries;
832  while (cur) {
833  next = cur->next;
834  av_free(cur->filename);
835  av_free(cur);
836  cur = next;
837  }
838 
840  return ret;
841 }
842 
843 #define OFFSET(x) offsetof(SegmentContext, x)
844 #define E AV_OPT_FLAG_ENCODING_PARAM
845 static const AVOption options[] = {
846  { "reference_stream", "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, CHAR_MIN, CHAR_MAX, E },
847  { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
848  { "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 },
849  { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
850 
851  { "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"},
852  { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
853  { "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"},
854 
855  { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
856 
857  { "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" },
858  { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" },
859  { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, E, "list_type" },
860  { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, E, "list_type" },
861  { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" },
862  { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
863  { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
864 
865  { "segment_atclocktime", "set segment to be cut at clocktime", OFFSET(use_clocktime), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E},
866  { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
867  { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 0, E },
868  { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
869  { "segment_frames", "set segment split frame numbers", OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
870  { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
871  { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
872  { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
873  { "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 },
874 
875  { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
876  { "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 },
877  { "reset_timestamps", "reset timestamps at the begin of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
878  { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
879  { NULL },
880 };
881 
882 static const AVClass seg_class = {
883  .class_name = "segment muxer",
884  .item_name = av_default_item_name,
885  .option = options,
886  .version = LIBAVUTIL_VERSION_INT,
887 };
888 
890  .name = "segment",
891  .long_name = NULL_IF_CONFIG_SMALL("segment"),
892  .priv_data_size = sizeof(SegmentContext),
897  .priv_class = &seg_class,
898 };
899 
900 static const AVClass sseg_class = {
901  .class_name = "stream_segment muxer",
902  .item_name = av_default_item_name,
903  .option = options,
904  .version = LIBAVUTIL_VERSION_INT,
905 };
906 
908  .name = "stream_segment,ssegment",
909  .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
910  .priv_data_size = sizeof(SegmentContext),
911  .flags = AVFMT_NOFILE,
915  .priv_class = &sseg_class,
916 };