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