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.

994 lines
37KB

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