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.

1027 lines
38KB

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