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.

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