You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1137 lines
42KB

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