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.

1062 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_context(SegmentContext *seg)
  544. {
  545. ff_format_io_close(seg->avf, &seg->list_pb);
  546. avformat_free_context(seg->avf);
  547. seg->avf = NULL;
  548. }
  549. static int seg_init(AVFormatContext *s)
  550. {
  551. SegmentContext *seg = s->priv_data;
  552. AVFormatContext *oc = seg->avf;
  553. AVDictionary *options = NULL;
  554. int ret;
  555. int i;
  556. seg->segment_count = 0;
  557. if (!seg->write_header_trailer)
  558. seg->individual_header_trailer = 0;
  559. if (seg->header_filename) {
  560. seg->write_header_trailer = 1;
  561. seg->individual_header_trailer = 0;
  562. }
  563. if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) {
  564. av_log(s, AV_LOG_ERROR,
  565. "segment_time, segment_times, and segment_frames options "
  566. "are mutually exclusive, select just one of them\n");
  567. return AVERROR(EINVAL);
  568. }
  569. if (seg->times_str) {
  570. if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
  571. return ret;
  572. } else if (seg->frames_str) {
  573. if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
  574. return ret;
  575. } else {
  576. /* set default value if not specified */
  577. if (!seg->time_str)
  578. seg->time_str = av_strdup("2");
  579. if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
  580. av_log(s, AV_LOG_ERROR,
  581. "Invalid time duration specification '%s' for segment_time option\n",
  582. seg->time_str);
  583. return ret;
  584. }
  585. if (seg->use_clocktime) {
  586. if (seg->time <= 0) {
  587. av_log(s, AV_LOG_ERROR, "Invalid negative segment_time with segment_atclocktime option set\n");
  588. return AVERROR(EINVAL);
  589. }
  590. seg->clocktime_offset = seg->time - (seg->clocktime_offset % seg->time);
  591. }
  592. }
  593. if (seg->format_options_str) {
  594. ret = av_dict_parse_string(&seg->format_options, seg->format_options_str, "=", ":", 0);
  595. if (ret < 0) {
  596. av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
  597. seg->format_options_str);
  598. goto fail;
  599. }
  600. }
  601. if (seg->list) {
  602. if (seg->list_type == LIST_TYPE_UNDEFINED) {
  603. if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
  604. else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
  605. else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
  606. else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
  607. else seg->list_type = LIST_TYPE_FLAT;
  608. }
  609. if (!seg->list_size && seg->list_type != LIST_TYPE_M3U8) {
  610. if ((ret = segment_list_open(s)) < 0)
  611. goto fail;
  612. } else {
  613. const char *proto = avio_find_protocol_name(s->filename);
  614. seg->use_rename = proto && !strcmp(proto, "file");
  615. }
  616. }
  617. if (seg->list_type == LIST_TYPE_EXT)
  618. av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
  619. if ((ret = select_reference_stream(s)) < 0)
  620. goto fail;
  621. av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
  622. seg->reference_stream_index,
  623. av_get_media_type_string(s->streams[seg->reference_stream_index]->codecpar->codec_type));
  624. seg->oformat = av_guess_format(seg->format, s->filename, NULL);
  625. if (!seg->oformat) {
  626. ret = AVERROR_MUXER_NOT_FOUND;
  627. goto fail;
  628. }
  629. if (seg->oformat->flags & AVFMT_NOFILE) {
  630. av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
  631. seg->oformat->name);
  632. ret = AVERROR(EINVAL);
  633. goto fail;
  634. }
  635. if ((ret = segment_mux_init(s)) < 0)
  636. goto fail;
  637. if ((ret = set_segment_filename(s)) < 0)
  638. goto fail;
  639. oc = seg->avf;
  640. if (seg->write_header_trailer) {
  641. if ((ret = s->io_open(s, &oc->pb,
  642. seg->header_filename ? seg->header_filename : oc->filename,
  643. AVIO_FLAG_WRITE, NULL)) < 0) {
  644. av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
  645. goto fail;
  646. }
  647. if (!seg->individual_header_trailer)
  648. oc->pb->seekable = 0;
  649. } else {
  650. if ((ret = open_null_ctx(&oc->pb)) < 0)
  651. goto fail;
  652. }
  653. av_dict_copy(&options, seg->format_options, 0);
  654. ret = avformat_write_header(oc, &options);
  655. if (av_dict_count(options)) {
  656. av_log(s, AV_LOG_ERROR,
  657. "Some of the provided format options in '%s' are not recognized\n", seg->format_options_str);
  658. ret = AVERROR(EINVAL);
  659. goto fail;
  660. }
  661. if (ret < 0) {
  662. ff_format_io_close(oc, &oc->pb);
  663. goto fail;
  664. }
  665. seg->segment_frame_count = 0;
  666. av_assert0(s->nb_streams == oc->nb_streams);
  667. for (i = 0; i < s->nb_streams; i++) {
  668. AVStream *inner_st = oc->streams[i];
  669. AVStream *outer_st = s->streams[i];
  670. avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
  671. }
  672. if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
  673. s->avoid_negative_ts = 1;
  674. if (!seg->write_header_trailer || seg->header_filename) {
  675. if (seg->header_filename) {
  676. av_write_frame(oc, NULL);
  677. ff_format_io_close(oc, &oc->pb);
  678. } else {
  679. close_null_ctxp(&oc->pb);
  680. }
  681. if ((ret = oc->io_open(oc, &oc->pb, oc->filename, AVIO_FLAG_WRITE, NULL)) < 0)
  682. goto fail;
  683. if (!seg->individual_header_trailer)
  684. oc->pb->seekable = 0;
  685. }
  686. fail:
  687. av_dict_free(&options);
  688. if (ret < 0)
  689. seg_free_context(seg);
  690. return ret;
  691. }
  692. static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
  693. {
  694. SegmentContext *seg = s->priv_data;
  695. AVStream *st = s->streams[pkt->stream_index];
  696. int64_t end_pts = INT64_MAX, offset;
  697. int start_frame = INT_MAX;
  698. int ret;
  699. struct tm ti;
  700. int64_t usecs;
  701. int64_t wrapped_val;
  702. if (!seg->avf)
  703. return AVERROR(EINVAL);
  704. calc_times:
  705. if (seg->times) {
  706. end_pts = seg->segment_count < seg->nb_times ?
  707. seg->times[seg->segment_count] : INT64_MAX;
  708. } else if (seg->frames) {
  709. start_frame = seg->segment_count < seg->nb_frames ?
  710. seg->frames[seg->segment_count] : INT_MAX;
  711. } else {
  712. if (seg->use_clocktime) {
  713. int64_t avgt = av_gettime();
  714. time_t sec = avgt / 1000000;
  715. localtime_r(&sec, &ti);
  716. usecs = (int64_t)(ti.tm_hour * 3600 + ti.tm_min * 60 + ti.tm_sec) * 1000000 + (avgt % 1000000);
  717. wrapped_val = (usecs + seg->clocktime_offset) % seg->time;
  718. if (seg->last_cut != usecs && wrapped_val < seg->last_val && wrapped_val < seg->clocktime_wrap_duration) {
  719. seg->cut_pending = 1;
  720. seg->last_cut = usecs;
  721. }
  722. seg->last_val = wrapped_val;
  723. } else {
  724. end_pts = seg->time * (seg->segment_count + 1);
  725. }
  726. }
  727. ff_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",
  728. pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
  729. av_ts2timestr(pkt->duration, &st->time_base),
  730. pkt->flags & AV_PKT_FLAG_KEY,
  731. pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);
  732. if (pkt->stream_index == seg->reference_stream_index &&
  733. (pkt->flags & AV_PKT_FLAG_KEY || seg->break_non_keyframes) &&
  734. (seg->segment_frame_count > 0 || seg->write_empty) &&
  735. (seg->cut_pending || seg->frame_count >= start_frame ||
  736. (pkt->pts != AV_NOPTS_VALUE &&
  737. av_compare_ts(pkt->pts, st->time_base,
  738. end_pts - seg->time_delta, AV_TIME_BASE_Q) >= 0))) {
  739. /* sanitize end time in case last packet didn't have a defined duration */
  740. if (seg->cur_entry.last_duration == 0)
  741. seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);
  742. if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)
  743. goto fail;
  744. if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)
  745. goto fail;
  746. seg->cut_pending = 0;
  747. seg->cur_entry.index = seg->segment_idx + seg->segment_idx_wrap * seg->segment_idx_wrap_nb;
  748. seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);
  749. seg->cur_entry.start_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
  750. seg->cur_entry.end_time = seg->cur_entry.start_time;
  751. if (seg->times || (!seg->frames && !seg->use_clocktime) && seg->write_empty)
  752. goto calc_times;
  753. }
  754. if (pkt->stream_index == seg->reference_stream_index) {
  755. if (pkt->pts != AV_NOPTS_VALUE)
  756. seg->cur_entry.end_time =
  757. FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
  758. seg->cur_entry.last_duration = pkt->duration;
  759. }
  760. if (seg->segment_frame_count == 0) {
  761. av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",
  762. seg->avf->filename, pkt->stream_index,
  763. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);
  764. }
  765. av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",
  766. pkt->stream_index,
  767. av_ts2timestr(seg->cur_entry.start_pts, &AV_TIME_BASE_Q),
  768. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
  769. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
  770. /* compute new timestamps */
  771. offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),
  772. AV_TIME_BASE_Q, st->time_base);
  773. if (pkt->pts != AV_NOPTS_VALUE)
  774. pkt->pts += offset;
  775. if (pkt->dts != AV_NOPTS_VALUE)
  776. pkt->dts += offset;
  777. av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
  778. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
  779. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
  780. ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s, seg->initial_offset || seg->reset_timestamps);
  781. fail:
  782. if (pkt->stream_index == seg->reference_stream_index) {
  783. seg->frame_count++;
  784. seg->segment_frame_count++;
  785. }
  786. if (ret < 0)
  787. seg_free_context(seg);
  788. return ret;
  789. }
  790. static int seg_write_trailer(struct AVFormatContext *s)
  791. {
  792. SegmentContext *seg = s->priv_data;
  793. AVFormatContext *oc = seg->avf;
  794. SegmentListEntry *cur, *next;
  795. int ret = 0;
  796. if (!oc)
  797. goto fail;
  798. if (!seg->write_header_trailer) {
  799. if ((ret = segment_end(s, 0, 1)) < 0)
  800. goto fail;
  801. if ((ret = open_null_ctx(&oc->pb)) < 0)
  802. goto fail;
  803. ret = av_write_trailer(oc);
  804. close_null_ctxp(&oc->pb);
  805. } else {
  806. ret = segment_end(s, 1, 1);
  807. }
  808. fail:
  809. if (seg->list)
  810. ff_format_io_close(s, &seg->list_pb);
  811. av_dict_free(&seg->format_options);
  812. av_opt_free(seg);
  813. av_freep(&seg->times);
  814. av_freep(&seg->frames);
  815. av_freep(&seg->cur_entry.filename);
  816. cur = seg->segment_list_entries;
  817. while (cur) {
  818. next = cur->next;
  819. av_freep(&cur->filename);
  820. av_free(cur);
  821. cur = next;
  822. }
  823. avformat_free_context(oc);
  824. seg->avf = NULL;
  825. return ret;
  826. }
  827. static int seg_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
  828. {
  829. SegmentContext *seg = s->priv_data;
  830. AVFormatContext *oc = seg->avf;
  831. if (oc->oformat->check_bitstream) {
  832. int ret = oc->oformat->check_bitstream(oc, pkt);
  833. if (ret == 1) {
  834. AVStream *st = s->streams[pkt->stream_index];
  835. AVStream *ost = oc->streams[pkt->stream_index];
  836. st->internal->bsfcs = ost->internal->bsfcs;
  837. st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
  838. ost->internal->bsfcs = NULL;
  839. ost->internal->nb_bsfcs = 0;
  840. }
  841. return ret;
  842. }
  843. return 1;
  844. }
  845. #define OFFSET(x) offsetof(SegmentContext, x)
  846. #define E AV_OPT_FLAG_ENCODING_PARAM
  847. static const AVOption options[] = {
  848. { "reference_stream", "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, CHAR_MIN, CHAR_MAX, E },
  849. { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  850. { "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 },
  851. { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  852. { "segment_header_filename", "write a single file containing the header", OFFSET(header_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  853. { "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"},
  854. { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
  855. { "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"},
  856. { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  857. { "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" },
  858. { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" },
  859. { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, E, "list_type" },
  860. { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, E, "list_type" },
  861. { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" },
  862. { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
  863. { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
  864. { "segment_atclocktime", "set segment to be cut at clocktime", OFFSET(use_clocktime), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E},
  865. { "segment_clocktime_offset", "set segment clocktime offset", OFFSET(clocktime_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 86400000000LL, E},
  866. { "segment_clocktime_wrap_duration", "set segment clocktime wrapping duration", OFFSET(clocktime_wrap_duration), AV_OPT_TYPE_DURATION, {.i64 = INT64_MAX}, 0, INT64_MAX, E},
  867. { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  868. { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 0, E },
  869. { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
  870. { "segment_frames", "set segment split frame numbers", OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
  871. { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  872. { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  873. { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  874. { "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 },
  875. { "strftime", "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
  876. { "increment_tc", "increment timecode between each segment", OFFSET(increment_tc), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
  877. { "break_non_keyframes", "allow breaking segments on non-keyframes", OFFSET(break_non_keyframes), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
  878. { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, E },
  879. { "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 },
  880. { "reset_timestamps", "reset timestamps at the begin of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
  881. { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
  882. { "write_empty_segments", "allow writing empty 'filler' segments", OFFSET(write_empty), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
  883. { NULL },
  884. };
  885. static const AVClass seg_class = {
  886. .class_name = "segment muxer",
  887. .item_name = av_default_item_name,
  888. .option = options,
  889. .version = LIBAVUTIL_VERSION_INT,
  890. };
  891. AVOutputFormat ff_segment_muxer = {
  892. .name = "segment",
  893. .long_name = NULL_IF_CONFIG_SMALL("segment"),
  894. .priv_data_size = sizeof(SegmentContext),
  895. .flags = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
  896. .init = seg_init,
  897. .write_packet = seg_write_packet,
  898. .write_trailer = seg_write_trailer,
  899. .check_bitstream = seg_check_bitstream,
  900. .priv_class = &seg_class,
  901. };
  902. static const AVClass sseg_class = {
  903. .class_name = "stream_segment muxer",
  904. .item_name = av_default_item_name,
  905. .option = options,
  906. .version = LIBAVUTIL_VERSION_INT,
  907. };
  908. AVOutputFormat ff_stream_segment_muxer = {
  909. .name = "stream_segment,ssegment",
  910. .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
  911. .priv_data_size = sizeof(SegmentContext),
  912. .flags = AVFMT_NOFILE,
  913. .init = seg_init,
  914. .write_packet = seg_write_packet,
  915. .write_trailer = seg_write_trailer,
  916. .check_bitstream = seg_check_bitstream,
  917. .priv_class = &sseg_class,
  918. };