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.

993 lines
36KB

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