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.

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