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.

1039 lines
39KB

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