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.

1135 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, *ist = s->streams[i];
  143. AVCodecParameters *ipar = ist->codecpar, *opar;
  144. if (!(st = avformat_new_stream(oc, NULL)))
  145. return AVERROR(ENOMEM);
  146. opar = st->codecpar;
  147. avcodec_parameters_copy(opar, ipar);
  148. if (!oc->oformat->codec_tag ||
  149. av_codec_get_id (oc->oformat->codec_tag, ipar->codec_tag) == opar->codec_id ||
  150. av_codec_get_tag(oc->oformat->codec_tag, ipar->codec_id) <= 0) {
  151. opar->codec_tag = ipar->codec_tag;
  152. } else {
  153. opar->codec_tag = 0;
  154. }
  155. st->sample_aspect_ratio = ist->sample_aspect_ratio;
  156. st->time_base = ist->time_base;
  157. st->avg_frame_rate = ist->avg_frame_rate;
  158. #if FF_API_LAVF_AVCTX
  159. FF_DISABLE_DEPRECATION_WARNINGS
  160. if (ipar->codec_tag == MKTAG('t','m','c','d'))
  161. st->codec->time_base = ist->codec->time_base;
  162. FF_ENABLE_DEPRECATION_WARNINGS
  163. #endif
  164. av_dict_copy(&st->metadata, ist->metadata, 0);
  165. }
  166. return 0;
  167. }
  168. static int set_segment_filename(AVFormatContext *s)
  169. {
  170. SegmentContext *seg = s->priv_data;
  171. AVFormatContext *oc = seg->avf;
  172. size_t size;
  173. int ret;
  174. char buf[1024];
  175. char *new_name;
  176. if (seg->segment_idx_wrap)
  177. seg->segment_idx %= seg->segment_idx_wrap;
  178. if (seg->use_strftime) {
  179. time_t now0;
  180. struct tm *tm, tmpbuf;
  181. time(&now0);
  182. tm = localtime_r(&now0, &tmpbuf);
  183. if (!strftime(buf, sizeof(buf), s->url, tm)) {
  184. av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
  185. return AVERROR(EINVAL);
  186. }
  187. } else if (av_get_frame_filename(buf, sizeof(buf),
  188. s->url, seg->segment_idx) < 0) {
  189. av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->url);
  190. return AVERROR(EINVAL);
  191. }
  192. new_name = av_strdup(buf);
  193. if (!new_name)
  194. return AVERROR(ENOMEM);
  195. ff_format_set_url(oc, new_name);
  196. /* copy modified name in list entry */
  197. size = strlen(av_basename(oc->url)) + 1;
  198. if (seg->entry_prefix)
  199. size += strlen(seg->entry_prefix);
  200. if ((ret = av_reallocp(&seg->cur_entry.filename, size)) < 0)
  201. return ret;
  202. snprintf(seg->cur_entry.filename, size, "%s%s",
  203. seg->entry_prefix ? seg->entry_prefix : "",
  204. av_basename(oc->url));
  205. return 0;
  206. }
  207. static int segment_start(AVFormatContext *s, int write_header)
  208. {
  209. SegmentContext *seg = s->priv_data;
  210. AVFormatContext *oc = seg->avf;
  211. int err = 0;
  212. if (write_header) {
  213. avformat_free_context(oc);
  214. seg->avf = NULL;
  215. if ((err = segment_mux_init(s)) < 0)
  216. return err;
  217. oc = seg->avf;
  218. }
  219. seg->segment_idx++;
  220. if ((seg->segment_idx_wrap) && (seg->segment_idx % seg->segment_idx_wrap == 0))
  221. seg->segment_idx_wrap_nb++;
  222. if ((err = set_segment_filename(s)) < 0)
  223. return err;
  224. if ((err = s->io_open(s, &oc->pb, oc->url, AVIO_FLAG_WRITE, NULL)) < 0) {
  225. av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->url);
  226. return err;
  227. }
  228. if (!seg->individual_header_trailer)
  229. oc->pb->seekable = 0;
  230. if (oc->oformat->priv_class && oc->priv_data)
  231. av_opt_set(oc->priv_data, "mpegts_flags", "+resend_headers", 0);
  232. if (write_header) {
  233. AVDictionary *options = NULL;
  234. av_dict_copy(&options, seg->format_options, 0);
  235. av_dict_set(&options, "fflags", "-autobsf", 0);
  236. err = avformat_write_header(oc, &options);
  237. av_dict_free(&options);
  238. if (err < 0)
  239. return err;
  240. }
  241. seg->segment_frame_count = 0;
  242. return 0;
  243. }
  244. static int segment_list_open(AVFormatContext *s)
  245. {
  246. SegmentContext *seg = s->priv_data;
  247. int ret;
  248. snprintf(seg->temp_list_filename, sizeof(seg->temp_list_filename), seg->use_rename ? "%s.tmp" : "%s", seg->list);
  249. ret = s->io_open(s, &seg->list_pb, seg->temp_list_filename, AVIO_FLAG_WRITE, NULL);
  250. if (ret < 0) {
  251. av_log(s, AV_LOG_ERROR, "Failed to open segment list '%s'\n", seg->list);
  252. return ret;
  253. }
  254. if (seg->list_type == LIST_TYPE_M3U8 && seg->segment_list_entries) {
  255. SegmentListEntry *entry;
  256. double max_duration = 0;
  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. av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n",
  263. seg->segment_list_entries->index);
  264. for (entry = seg->segment_list_entries; entry; entry = entry->next)
  265. max_duration = FFMAX(max_duration, entry->end_time - entry->start_time);
  266. avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%"PRId64"\n", (int64_t)ceil(max_duration));
  267. } else if (seg->list_type == LIST_TYPE_FFCONCAT) {
  268. avio_printf(seg->list_pb, "ffconcat version 1.0\n");
  269. }
  270. return ret;
  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. static int segment_end(AVFormatContext *s, int write_trailer, int is_last)
  307. {
  308. SegmentContext *seg = s->priv_data;
  309. AVFormatContext *oc = seg->avf;
  310. int ret = 0;
  311. AVTimecode tc;
  312. AVRational rate;
  313. AVDictionaryEntry *tcr;
  314. char buf[AV_TIMECODE_STR_SIZE];
  315. int i;
  316. int err;
  317. if (!oc || !oc->pb)
  318. return AVERROR(EINVAL);
  319. av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
  320. if (write_trailer)
  321. ret = av_write_trailer(oc);
  322. if (ret < 0)
  323. av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
  324. oc->url);
  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. /* append new element */
  333. memcpy(entry, &seg->cur_entry, sizeof(*entry));
  334. entry->filename = av_strdup(entry->filename);
  335. if (!seg->segment_list_entries)
  336. seg->segment_list_entries = seg->segment_list_entries_end = entry;
  337. else
  338. seg->segment_list_entries_end->next = entry;
  339. seg->segment_list_entries_end = entry;
  340. /* drop first item */
  341. if (seg->list_size && seg->segment_count >= seg->list_size) {
  342. entry = seg->segment_list_entries;
  343. seg->segment_list_entries = seg->segment_list_entries->next;
  344. av_freep(&entry->filename);
  345. av_freep(&entry);
  346. }
  347. if ((ret = segment_list_open(s)) < 0)
  348. goto end;
  349. for (entry = seg->segment_list_entries; entry; entry = entry->next)
  350. segment_list_print_entry(seg->list_pb, seg->list_type, entry, s);
  351. if (seg->list_type == LIST_TYPE_M3U8 && is_last)
  352. avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
  353. ff_format_io_close(s, &seg->list_pb);
  354. if (seg->use_rename)
  355. ff_rename(seg->temp_list_filename, seg->list, s);
  356. } else {
  357. segment_list_print_entry(seg->list_pb, seg->list_type, &seg->cur_entry, s);
  358. avio_flush(seg->list_pb);
  359. }
  360. }
  361. av_log(s, AV_LOG_VERBOSE, "segment:'%s' count:%d ended\n",
  362. seg->avf->url, seg->segment_count);
  363. seg->segment_count++;
  364. if (seg->increment_tc) {
  365. tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
  366. if (tcr) {
  367. /* search the first video stream */
  368. for (i = 0; i < s->nb_streams; i++) {
  369. if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  370. rate = s->streams[i]->avg_frame_rate;/* Get fps from the video stream */
  371. err = av_timecode_init_from_string(&tc, rate, tcr->value, s);
  372. if (err < 0) {
  373. av_log(s, AV_LOG_WARNING, "Could not increment global timecode, error occurred during timecode creation.\n");
  374. break;
  375. }
  376. tc.start += (int)((seg->cur_entry.end_time - seg->cur_entry.start_time) * av_q2d(rate));/* increment timecode */
  377. av_dict_set(&s->metadata, "timecode",
  378. av_timecode_make_string(&tc, buf, 0), 0);
  379. break;
  380. }
  381. }
  382. } else {
  383. av_log(s, AV_LOG_WARNING, "Could not increment global timecode, no global timecode metadata found.\n");
  384. }
  385. for (i = 0; i < s->nb_streams; i++) {
  386. if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  387. char st_buf[AV_TIMECODE_STR_SIZE];
  388. AVTimecode st_tc;
  389. AVRational st_rate = s->streams[i]->avg_frame_rate;
  390. AVDictionaryEntry *st_tcr = av_dict_get(s->streams[i]->metadata, "timecode", NULL, 0);
  391. if (st_tcr) {
  392. if ((av_timecode_init_from_string(&st_tc, st_rate, st_tcr->value, s) < 0)) {
  393. av_log(s, AV_LOG_WARNING, "Could not increment stream %d timecode, error occurred during timecode creation.\n", i);
  394. continue;
  395. }
  396. st_tc.start += (int)((seg->cur_entry.end_time - seg->cur_entry.start_time) * av_q2d(st_rate)); // increment timecode
  397. av_dict_set(&s->streams[i]->metadata, "timecode", av_timecode_make_string(&st_tc, st_buf, 0), 0);
  398. }
  399. }
  400. }
  401. }
  402. end:
  403. ff_format_io_close(oc, &oc->pb);
  404. return ret;
  405. }
  406. static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
  407. const char *times_str)
  408. {
  409. char *p;
  410. int i, ret = 0;
  411. char *times_str1 = av_strdup(times_str);
  412. char *saveptr = NULL;
  413. if (!times_str1)
  414. return AVERROR(ENOMEM);
  415. #define FAIL(err) ret = err; goto end
  416. *nb_times = 1;
  417. for (p = times_str1; *p; p++)
  418. if (*p == ',')
  419. (*nb_times)++;
  420. *times = av_malloc_array(*nb_times, sizeof(**times));
  421. if (!*times) {
  422. av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
  423. FAIL(AVERROR(ENOMEM));
  424. }
  425. p = times_str1;
  426. for (i = 0; i < *nb_times; i++) {
  427. int64_t t;
  428. char *tstr = av_strtok(p, ",", &saveptr);
  429. p = NULL;
  430. if (!tstr || !tstr[0]) {
  431. av_log(log_ctx, AV_LOG_ERROR, "Empty time specification in times list %s\n",
  432. times_str);
  433. FAIL(AVERROR(EINVAL));
  434. }
  435. ret = av_parse_time(&t, tstr, 1);
  436. if (ret < 0) {
  437. av_log(log_ctx, AV_LOG_ERROR,
  438. "Invalid time duration specification '%s' in times list %s\n", tstr, times_str);
  439. FAIL(AVERROR(EINVAL));
  440. }
  441. (*times)[i] = t;
  442. /* check on monotonicity */
  443. if (i && (*times)[i-1] > (*times)[i]) {
  444. av_log(log_ctx, AV_LOG_ERROR,
  445. "Specified time %f is greater than the following time %f\n",
  446. (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
  447. FAIL(AVERROR(EINVAL));
  448. }
  449. }
  450. end:
  451. av_free(times_str1);
  452. return ret;
  453. }
  454. static int parse_frames(void *log_ctx, int **frames, int *nb_frames,
  455. const char *frames_str)
  456. {
  457. char *p;
  458. int i, ret = 0;
  459. char *frames_str1 = av_strdup(frames_str);
  460. char *saveptr = NULL;
  461. if (!frames_str1)
  462. return AVERROR(ENOMEM);
  463. #define FAIL(err) ret = err; goto end
  464. *nb_frames = 1;
  465. for (p = frames_str1; *p; p++)
  466. if (*p == ',')
  467. (*nb_frames)++;
  468. *frames = av_malloc_array(*nb_frames, sizeof(**frames));
  469. if (!*frames) {
  470. av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced frames array\n");
  471. FAIL(AVERROR(ENOMEM));
  472. }
  473. p = frames_str1;
  474. for (i = 0; i < *nb_frames; i++) {
  475. long int f;
  476. char *tailptr;
  477. char *fstr = av_strtok(p, ",", &saveptr);
  478. p = NULL;
  479. if (!fstr) {
  480. av_log(log_ctx, AV_LOG_ERROR, "Empty frame specification in frame list %s\n",
  481. frames_str);
  482. FAIL(AVERROR(EINVAL));
  483. }
  484. f = strtol(fstr, &tailptr, 10);
  485. if (*tailptr || f <= 0 || f >= INT_MAX) {
  486. av_log(log_ctx, AV_LOG_ERROR,
  487. "Invalid argument '%s', must be a positive integer <= INT64_MAX\n",
  488. fstr);
  489. FAIL(AVERROR(EINVAL));
  490. }
  491. (*frames)[i] = f;
  492. /* check on monotonicity */
  493. if (i && (*frames)[i-1] > (*frames)[i]) {
  494. av_log(log_ctx, AV_LOG_ERROR,
  495. "Specified frame %d is greater than the following frame %d\n",
  496. (*frames)[i], (*frames)[i-1]);
  497. FAIL(AVERROR(EINVAL));
  498. }
  499. }
  500. end:
  501. av_free(frames_str1);
  502. return ret;
  503. }
  504. static int open_null_ctx(AVIOContext **ctx)
  505. {
  506. int buf_size = 32768;
  507. uint8_t *buf = av_malloc(buf_size);
  508. if (!buf)
  509. return AVERROR(ENOMEM);
  510. *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
  511. if (!*ctx) {
  512. av_free(buf);
  513. return AVERROR(ENOMEM);
  514. }
  515. return 0;
  516. }
  517. static void close_null_ctxp(AVIOContext **pb)
  518. {
  519. av_freep(&(*pb)->buffer);
  520. avio_context_free(pb);
  521. }
  522. static int select_reference_stream(AVFormatContext *s)
  523. {
  524. SegmentContext *seg = s->priv_data;
  525. int ret, i;
  526. seg->reference_stream_index = -1;
  527. if (!strcmp(seg->reference_stream_specifier, "auto")) {
  528. /* select first index of type with highest priority */
  529. int type_index_map[AVMEDIA_TYPE_NB];
  530. static const enum AVMediaType type_priority_list[] = {
  531. AVMEDIA_TYPE_VIDEO,
  532. AVMEDIA_TYPE_AUDIO,
  533. AVMEDIA_TYPE_SUBTITLE,
  534. AVMEDIA_TYPE_DATA,
  535. AVMEDIA_TYPE_ATTACHMENT
  536. };
  537. enum AVMediaType type;
  538. for (i = 0; i < AVMEDIA_TYPE_NB; i++)
  539. type_index_map[i] = -1;
  540. /* select first index for each type */
  541. for (i = 0; i < s->nb_streams; i++) {
  542. type = s->streams[i]->codecpar->codec_type;
  543. if ((unsigned)type < AVMEDIA_TYPE_NB && type_index_map[type] == -1
  544. /* ignore attached pictures/cover art streams */
  545. && !(s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC))
  546. type_index_map[type] = i;
  547. }
  548. for (i = 0; i < FF_ARRAY_ELEMS(type_priority_list); i++) {
  549. type = type_priority_list[i];
  550. if ((seg->reference_stream_index = type_index_map[type]) >= 0)
  551. break;
  552. }
  553. } else {
  554. for (i = 0; i < s->nb_streams; i++) {
  555. ret = avformat_match_stream_specifier(s, s->streams[i],
  556. seg->reference_stream_specifier);
  557. if (ret < 0)
  558. return ret;
  559. if (ret > 0) {
  560. seg->reference_stream_index = i;
  561. break;
  562. }
  563. }
  564. }
  565. if (seg->reference_stream_index < 0) {
  566. av_log(s, AV_LOG_ERROR, "Could not select stream matching identifier '%s'\n",
  567. seg->reference_stream_specifier);
  568. return AVERROR(EINVAL);
  569. }
  570. return 0;
  571. }
  572. static void seg_free(AVFormatContext *s)
  573. {
  574. SegmentContext *seg = s->priv_data;
  575. ff_format_io_close(seg->avf, &seg->list_pb);
  576. avformat_free_context(seg->avf);
  577. seg->avf = NULL;
  578. }
  579. static int seg_init(AVFormatContext *s)
  580. {
  581. SegmentContext *seg = s->priv_data;
  582. AVFormatContext *oc = seg->avf;
  583. AVDictionary *options = NULL;
  584. int ret;
  585. int i;
  586. seg->segment_count = 0;
  587. if (!seg->write_header_trailer)
  588. seg->individual_header_trailer = 0;
  589. if (seg->header_filename) {
  590. seg->write_header_trailer = 1;
  591. seg->individual_header_trailer = 0;
  592. }
  593. if (seg->initial_offset > 0) {
  594. av_log(s, AV_LOG_WARNING, "NOTE: the option initial_offset is deprecated,"
  595. "you can use output_ts_offset instead of it\n");
  596. }
  597. if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) {
  598. av_log(s, AV_LOG_ERROR,
  599. "segment_time, segment_times, and segment_frames options "
  600. "are mutually exclusive, select just one of them\n");
  601. return AVERROR(EINVAL);
  602. }
  603. if (seg->times_str) {
  604. if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
  605. return ret;
  606. } else if (seg->frames_str) {
  607. if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
  608. return ret;
  609. } else {
  610. /* set default value if not specified */
  611. if (!seg->time_str)
  612. seg->time_str = av_strdup("2");
  613. if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
  614. av_log(s, AV_LOG_ERROR,
  615. "Invalid time duration specification '%s' for segment_time option\n",
  616. seg->time_str);
  617. return ret;
  618. }
  619. if (seg->use_clocktime) {
  620. if (seg->time <= 0) {
  621. av_log(s, AV_LOG_ERROR, "Invalid negative segment_time with segment_atclocktime option set\n");
  622. return AVERROR(EINVAL);
  623. }
  624. seg->clocktime_offset = seg->time - (seg->clocktime_offset % seg->time);
  625. }
  626. }
  627. if (seg->list) {
  628. if (seg->list_type == LIST_TYPE_UNDEFINED) {
  629. if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
  630. else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
  631. else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
  632. else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
  633. else seg->list_type = LIST_TYPE_FLAT;
  634. }
  635. if (!seg->list_size && seg->list_type != LIST_TYPE_M3U8) {
  636. if ((ret = segment_list_open(s)) < 0)
  637. return ret;
  638. } else {
  639. const char *proto = avio_find_protocol_name(seg->list);
  640. seg->use_rename = proto && !strcmp(proto, "file");
  641. }
  642. }
  643. if (seg->list_type == LIST_TYPE_EXT)
  644. av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
  645. if ((ret = select_reference_stream(s)) < 0)
  646. return ret;
  647. av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
  648. seg->reference_stream_index,
  649. av_get_media_type_string(s->streams[seg->reference_stream_index]->codecpar->codec_type));
  650. seg->oformat = av_guess_format(seg->format, s->url, NULL);
  651. if (!seg->oformat)
  652. return AVERROR_MUXER_NOT_FOUND;
  653. if (seg->oformat->flags & AVFMT_NOFILE) {
  654. av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
  655. seg->oformat->name);
  656. return AVERROR(EINVAL);
  657. }
  658. if ((ret = segment_mux_init(s)) < 0)
  659. return ret;
  660. if ((ret = set_segment_filename(s)) < 0)
  661. return ret;
  662. oc = seg->avf;
  663. if (seg->write_header_trailer) {
  664. if ((ret = s->io_open(s, &oc->pb,
  665. seg->header_filename ? seg->header_filename : oc->url,
  666. AVIO_FLAG_WRITE, NULL)) < 0) {
  667. av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->url);
  668. return ret;
  669. }
  670. if (!seg->individual_header_trailer)
  671. oc->pb->seekable = 0;
  672. } else {
  673. if ((ret = open_null_ctx(&oc->pb)) < 0)
  674. return ret;
  675. }
  676. av_dict_copy(&options, seg->format_options, 0);
  677. av_dict_set(&options, "fflags", "-autobsf", 0);
  678. ret = avformat_init_output(oc, &options);
  679. if (av_dict_count(options)) {
  680. av_log(s, AV_LOG_ERROR,
  681. "Some of the provided format options are not recognized\n");
  682. av_dict_free(&options);
  683. return AVERROR(EINVAL);
  684. }
  685. av_dict_free(&options);
  686. if (ret < 0) {
  687. ff_format_io_close(oc, &oc->pb);
  688. return ret;
  689. }
  690. seg->segment_frame_count = 0;
  691. av_assert0(s->nb_streams == oc->nb_streams);
  692. if (ret == AVSTREAM_INIT_IN_WRITE_HEADER) {
  693. ret = avformat_write_header(oc, NULL);
  694. if (ret < 0)
  695. return ret;
  696. seg->header_written = 1;
  697. }
  698. for (i = 0; i < s->nb_streams; i++) {
  699. AVStream *inner_st = oc->streams[i];
  700. AVStream *outer_st = s->streams[i];
  701. avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
  702. }
  703. if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
  704. s->avoid_negative_ts = 1;
  705. return ret;
  706. }
  707. static int seg_write_header(AVFormatContext *s)
  708. {
  709. SegmentContext *seg = s->priv_data;
  710. AVFormatContext *oc = seg->avf;
  711. int ret, i;
  712. if (!seg->header_written) {
  713. for (i = 0; i < s->nb_streams; i++) {
  714. AVStream *st = oc->streams[i];
  715. AVCodecParameters *ipar, *opar;
  716. ipar = s->streams[i]->codecpar;
  717. opar = oc->streams[i]->codecpar;
  718. avcodec_parameters_copy(opar, ipar);
  719. if (!oc->oformat->codec_tag ||
  720. av_codec_get_id (oc->oformat->codec_tag, ipar->codec_tag) == opar->codec_id ||
  721. av_codec_get_tag(oc->oformat->codec_tag, ipar->codec_id) <= 0) {
  722. opar->codec_tag = ipar->codec_tag;
  723. } else {
  724. opar->codec_tag = 0;
  725. }
  726. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  727. st->time_base = s->streams[i]->time_base;
  728. }
  729. ret = avformat_write_header(oc, NULL);
  730. if (ret < 0)
  731. return ret;
  732. }
  733. if (!seg->write_header_trailer || seg->header_filename) {
  734. if (seg->header_filename) {
  735. av_write_frame(oc, NULL);
  736. ff_format_io_close(oc, &oc->pb);
  737. } else {
  738. close_null_ctxp(&oc->pb);
  739. }
  740. if ((ret = oc->io_open(oc, &oc->pb, oc->url, AVIO_FLAG_WRITE, NULL)) < 0)
  741. return ret;
  742. if (!seg->individual_header_trailer)
  743. oc->pb->seekable = 0;
  744. }
  745. return 0;
  746. }
  747. static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
  748. {
  749. SegmentContext *seg = s->priv_data;
  750. AVStream *st = s->streams[pkt->stream_index];
  751. int64_t end_pts = INT64_MAX, offset;
  752. int start_frame = INT_MAX;
  753. int ret;
  754. struct tm ti;
  755. int64_t usecs;
  756. int64_t wrapped_val;
  757. if (!seg->avf || !seg->avf->pb)
  758. return AVERROR(EINVAL);
  759. if (!st->codecpar->extradata_size) {
  760. int pkt_extradata_size = 0;
  761. uint8_t *pkt_extradata = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &pkt_extradata_size);
  762. if (pkt_extradata && pkt_extradata_size > 0) {
  763. ret = ff_alloc_extradata(st->codecpar, pkt_extradata_size);
  764. if (ret < 0) {
  765. av_log(s, AV_LOG_WARNING, "Unable to add extradata to stream. Output segments may be invalid.\n");
  766. goto calc_times;
  767. }
  768. memcpy(st->codecpar->extradata, pkt_extradata, pkt_extradata_size);
  769. }
  770. }
  771. calc_times:
  772. if (seg->times) {
  773. end_pts = seg->segment_count < seg->nb_times ?
  774. seg->times[seg->segment_count] : INT64_MAX;
  775. } else if (seg->frames) {
  776. start_frame = seg->segment_count < seg->nb_frames ?
  777. seg->frames[seg->segment_count] : INT_MAX;
  778. } else {
  779. if (seg->use_clocktime) {
  780. int64_t avgt = av_gettime();
  781. time_t sec = avgt / 1000000;
  782. localtime_r(&sec, &ti);
  783. usecs = (int64_t)(ti.tm_hour * 3600 + ti.tm_min * 60 + ti.tm_sec) * 1000000 + (avgt % 1000000);
  784. wrapped_val = (usecs + seg->clocktime_offset) % seg->time;
  785. if (wrapped_val < seg->last_val && wrapped_val < seg->clocktime_wrap_duration)
  786. seg->cut_pending = 1;
  787. seg->last_val = wrapped_val;
  788. } else {
  789. end_pts = seg->time * (seg->segment_count + 1);
  790. }
  791. }
  792. ff_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",
  793. pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
  794. av_ts2timestr(pkt->duration, &st->time_base),
  795. pkt->flags & AV_PKT_FLAG_KEY,
  796. pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);
  797. if (pkt->stream_index == seg->reference_stream_index &&
  798. (pkt->flags & AV_PKT_FLAG_KEY || seg->break_non_keyframes) &&
  799. (seg->segment_frame_count > 0 || seg->write_empty) &&
  800. (seg->cut_pending || seg->frame_count >= start_frame ||
  801. (pkt->pts != AV_NOPTS_VALUE &&
  802. av_compare_ts(pkt->pts, st->time_base,
  803. end_pts - seg->time_delta, AV_TIME_BASE_Q) >= 0))) {
  804. /* sanitize end time in case last packet didn't have a defined duration */
  805. if (seg->cur_entry.last_duration == 0)
  806. seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);
  807. if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)
  808. goto fail;
  809. if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)
  810. goto fail;
  811. seg->cut_pending = 0;
  812. seg->cur_entry.index = seg->segment_idx + seg->segment_idx_wrap * seg->segment_idx_wrap_nb;
  813. seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);
  814. seg->cur_entry.start_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
  815. seg->cur_entry.end_time = seg->cur_entry.start_time;
  816. if (seg->times || (!seg->frames && !seg->use_clocktime) && seg->write_empty)
  817. goto calc_times;
  818. }
  819. if (pkt->stream_index == seg->reference_stream_index) {
  820. if (pkt->pts != AV_NOPTS_VALUE)
  821. seg->cur_entry.end_time =
  822. FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
  823. seg->cur_entry.last_duration = pkt->duration;
  824. }
  825. if (seg->segment_frame_count == 0) {
  826. av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",
  827. seg->avf->url, pkt->stream_index,
  828. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);
  829. }
  830. av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",
  831. pkt->stream_index,
  832. av_ts2timestr(seg->cur_entry.start_pts, &AV_TIME_BASE_Q),
  833. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
  834. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
  835. /* compute new timestamps */
  836. offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),
  837. AV_TIME_BASE_Q, st->time_base);
  838. if (pkt->pts != AV_NOPTS_VALUE)
  839. pkt->pts += offset;
  840. if (pkt->dts != AV_NOPTS_VALUE)
  841. pkt->dts += offset;
  842. av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
  843. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
  844. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
  845. ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s,
  846. seg->initial_offset || seg->reset_timestamps || seg->avf->oformat->interleave_packet);
  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->bsfc = ost->internal->bsfc;
  900. ost->internal->bsfc = NULL;
  901. }
  902. return ret;
  903. }
  904. return 1;
  905. }
  906. #define OFFSET(x) offsetof(SegmentContext, x)
  907. #define E AV_OPT_FLAG_ENCODING_PARAM
  908. static const AVOption options[] = {
  909. { "reference_stream", "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, 0, 0, E },
  910. { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  911. { "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 },
  912. { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  913. { "segment_header_filename", "write a single file containing the header", OFFSET(header_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  914. { "segment_list_flags","set flags affecting segment list generation", OFFSET(list_flags), AV_OPT_TYPE_FLAGS, {.i64 = SEGMENT_LIST_FLAG_CACHE }, 0, UINT_MAX, E, "list_flags"},
  915. { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
  916. { "live", "enable live-friendly list generation (useful for HLS)", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_LIVE }, INT_MIN, INT_MAX, E, "list_flags"},
  917. { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  918. { "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" },
  919. { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" },
  920. { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, E, "list_type" },
  921. { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, E, "list_type" },
  922. { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" },
  923. { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
  924. { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
  925. { "segment_atclocktime", "set segment to be cut at clocktime", OFFSET(use_clocktime), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E},
  926. { "segment_clocktime_offset", "set segment clocktime offset", OFFSET(clocktime_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 86400000000LL, E},
  927. { "segment_clocktime_wrap_duration", "set segment clocktime wrapping duration", OFFSET(clocktime_wrap_duration), AV_OPT_TYPE_DURATION, {.i64 = INT64_MAX}, 0, INT64_MAX, E},
  928. { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  929. { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, INT64_MAX, E },
  930. { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
  931. { "segment_frames", "set segment split frame numbers", OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
  932. { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  933. { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  934. { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  935. { "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 },
  936. { "strftime", "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
  937. { "increment_tc", "increment timecode between each segment", OFFSET(increment_tc), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
  938. { "break_non_keyframes", "allow breaking segments on non-keyframes", OFFSET(break_non_keyframes), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
  939. { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, E },
  940. { "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 },
  941. { "reset_timestamps", "reset timestamps at the beginning of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
  942. { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
  943. { "write_empty_segments", "allow writing empty 'filler' segments", OFFSET(write_empty), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
  944. { NULL },
  945. };
  946. #if CONFIG_SEGMENT_MUXER
  947. static const AVClass seg_class = {
  948. .class_name = "segment muxer",
  949. .item_name = av_default_item_name,
  950. .option = options,
  951. .version = LIBAVUTIL_VERSION_INT,
  952. };
  953. AVOutputFormat ff_segment_muxer = {
  954. .name = "segment",
  955. .long_name = NULL_IF_CONFIG_SMALL("segment"),
  956. .priv_data_size = sizeof(SegmentContext),
  957. .flags = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
  958. .init = seg_init,
  959. .write_header = seg_write_header,
  960. .write_packet = seg_write_packet,
  961. .write_trailer = seg_write_trailer,
  962. .deinit = seg_free,
  963. .check_bitstream = seg_check_bitstream,
  964. .priv_class = &seg_class,
  965. };
  966. #endif
  967. #if CONFIG_STREAM_SEGMENT_MUXER
  968. static const AVClass sseg_class = {
  969. .class_name = "stream_segment muxer",
  970. .item_name = av_default_item_name,
  971. .option = options,
  972. .version = LIBAVUTIL_VERSION_INT,
  973. };
  974. AVOutputFormat ff_stream_segment_muxer = {
  975. .name = "stream_segment,ssegment",
  976. .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
  977. .priv_data_size = sizeof(SegmentContext),
  978. .flags = AVFMT_NOFILE,
  979. .init = seg_init,
  980. .write_header = seg_write_header,
  981. .write_packet = seg_write_packet,
  982. .write_trailer = seg_write_trailer,
  983. .deinit = seg_free,
  984. .check_bitstream = seg_check_bitstream,
  985. .priv_class = &sseg_class,
  986. };
  987. #endif