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.

1059 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. for (i = 0; i < s->nb_streams; i++) {
  143. AVStream *st;
  144. AVCodecContext *icodec, *ocodec;
  145. if (!(st = avformat_new_stream(oc, NULL)))
  146. return AVERROR(ENOMEM);
  147. icodec = s->streams[i]->codec;
  148. ocodec = st->codec;
  149. avcodec_copy_context(ocodec, icodec);
  150. if (!oc->oformat->codec_tag ||
  151. av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == ocodec->codec_id ||
  152. av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0) {
  153. ocodec->codec_tag = icodec->codec_tag;
  154. } else {
  155. ocodec->codec_tag = 0;
  156. }
  157. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  158. st->time_base = s->streams[i]->time_base;
  159. av_dict_copy(&st->metadata, s->streams[i]->metadata, 0);
  160. }
  161. return 0;
  162. }
  163. static int set_segment_filename(AVFormatContext *s)
  164. {
  165. SegmentContext *seg = s->priv_data;
  166. AVFormatContext *oc = seg->avf;
  167. size_t size;
  168. int ret;
  169. if (seg->segment_idx_wrap)
  170. seg->segment_idx %= seg->segment_idx_wrap;
  171. if (seg->use_strftime) {
  172. time_t now0;
  173. struct tm *tm, tmpbuf;
  174. time(&now0);
  175. tm = localtime_r(&now0, &tmpbuf);
  176. if (!strftime(oc->filename, sizeof(oc->filename), s->filename, tm)) {
  177. av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
  178. return AVERROR(EINVAL);
  179. }
  180. } else if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
  181. s->filename, seg->segment_idx) < 0) {
  182. av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
  183. return AVERROR(EINVAL);
  184. }
  185. /* copy modified name in list entry */
  186. size = strlen(av_basename(oc->filename)) + 1;
  187. if (seg->entry_prefix)
  188. size += strlen(seg->entry_prefix);
  189. if ((ret = av_reallocp(&seg->cur_entry.filename, size)) < 0)
  190. return ret;
  191. snprintf(seg->cur_entry.filename, size, "%s%s",
  192. seg->entry_prefix ? seg->entry_prefix : "",
  193. av_basename(oc->filename));
  194. return 0;
  195. }
  196. static int segment_start(AVFormatContext *s, int write_header)
  197. {
  198. SegmentContext *seg = s->priv_data;
  199. AVFormatContext *oc = seg->avf;
  200. int err = 0;
  201. if (write_header) {
  202. avformat_free_context(oc);
  203. seg->avf = NULL;
  204. if ((err = segment_mux_init(s)) < 0)
  205. return err;
  206. oc = seg->avf;
  207. }
  208. seg->segment_idx++;
  209. if ((seg->segment_idx_wrap) && (seg->segment_idx % seg->segment_idx_wrap == 0))
  210. seg->segment_idx_wrap_nb++;
  211. if ((err = set_segment_filename(s)) < 0)
  212. return err;
  213. if ((err = s->io_open(s, &oc->pb, oc->filename, AVIO_FLAG_WRITE, NULL)) < 0) {
  214. av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
  215. return err;
  216. }
  217. if (!seg->individual_header_trailer)
  218. oc->pb->seekable = 0;
  219. if (oc->oformat->priv_class && oc->priv_data)
  220. av_opt_set(oc->priv_data, "mpegts_flags", "+resend_headers", 0);
  221. if (write_header) {
  222. AVDictionary *options = NULL;
  223. av_dict_copy(&options, seg->format_options, 0);
  224. err = avformat_write_header(oc, &options);
  225. av_dict_free(&options);
  226. if (err < 0)
  227. return err;
  228. }
  229. seg->segment_frame_count = 0;
  230. return 0;
  231. }
  232. static int segment_list_open(AVFormatContext *s)
  233. {
  234. SegmentContext *seg = s->priv_data;
  235. int ret;
  236. snprintf(seg->temp_list_filename, sizeof(seg->temp_list_filename), seg->use_rename ? "%s.tmp" : "%s", seg->list);
  237. ret = s->io_open(s, &seg->list_pb, seg->temp_list_filename, AVIO_FLAG_WRITE, NULL);
  238. if (ret < 0) {
  239. av_log(s, AV_LOG_ERROR, "Failed to open segment list '%s'\n", seg->list);
  240. return ret;
  241. }
  242. if (seg->list_type == LIST_TYPE_M3U8 && seg->segment_list_entries) {
  243. SegmentListEntry *entry;
  244. double max_duration = 0;
  245. avio_printf(seg->list_pb, "#EXTM3U\n");
  246. avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
  247. avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_list_entries->index);
  248. avio_printf(seg->list_pb, "#EXT-X-ALLOW-CACHE:%s\n",
  249. seg->list_flags & SEGMENT_LIST_FLAG_CACHE ? "YES" : "NO");
  250. av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n",
  251. seg->segment_list_entries->index);
  252. for (entry = seg->segment_list_entries; entry; entry = entry->next)
  253. max_duration = FFMAX(max_duration, entry->end_time - entry->start_time);
  254. avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%"PRId64"\n", (int64_t)ceil(max_duration));
  255. } else if (seg->list_type == LIST_TYPE_FFCONCAT) {
  256. avio_printf(seg->list_pb, "ffconcat version 1.0\n");
  257. }
  258. return ret;
  259. }
  260. static void segment_list_print_entry(AVIOContext *list_ioctx,
  261. ListType list_type,
  262. const SegmentListEntry *list_entry,
  263. void *log_ctx)
  264. {
  265. switch (list_type) {
  266. case LIST_TYPE_FLAT:
  267. avio_printf(list_ioctx, "%s\n", list_entry->filename);
  268. break;
  269. case LIST_TYPE_CSV:
  270. case LIST_TYPE_EXT:
  271. print_csv_escaped_str(list_ioctx, list_entry->filename);
  272. avio_printf(list_ioctx, ",%f,%f\n", list_entry->start_time, list_entry->end_time);
  273. break;
  274. case LIST_TYPE_M3U8:
  275. avio_printf(list_ioctx, "#EXTINF:%f,\n%s\n",
  276. list_entry->end_time - list_entry->start_time, list_entry->filename);
  277. break;
  278. case LIST_TYPE_FFCONCAT:
  279. {
  280. char *buf;
  281. if (av_escape(&buf, list_entry->filename, NULL, AV_ESCAPE_MODE_AUTO, AV_ESCAPE_FLAG_WHITESPACE) < 0) {
  282. av_log(log_ctx, AV_LOG_WARNING,
  283. "Error writing list entry '%s' in list file\n", list_entry->filename);
  284. return;
  285. }
  286. avio_printf(list_ioctx, "file %s\n", buf);
  287. av_free(buf);
  288. break;
  289. }
  290. default:
  291. av_assert0(!"Invalid list type");
  292. }
  293. }
  294. static int segment_end(AVFormatContext *s, int write_trailer, int is_last)
  295. {
  296. SegmentContext *seg = s->priv_data;
  297. AVFormatContext *oc = seg->avf;
  298. int ret = 0;
  299. AVTimecode tc;
  300. AVRational rate;
  301. AVDictionaryEntry *tcr;
  302. char buf[AV_TIMECODE_STR_SIZE];
  303. int i;
  304. int err;
  305. av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
  306. if (write_trailer)
  307. ret = av_write_trailer(oc);
  308. if (ret < 0)
  309. av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
  310. oc->filename);
  311. if (seg->list) {
  312. if (seg->list_size || seg->list_type == LIST_TYPE_M3U8) {
  313. SegmentListEntry *entry = av_mallocz(sizeof(*entry));
  314. if (!entry) {
  315. ret = AVERROR(ENOMEM);
  316. goto end;
  317. }
  318. /* append new element */
  319. memcpy(entry, &seg->cur_entry, sizeof(*entry));
  320. entry->filename = av_strdup(entry->filename);
  321. if (!seg->segment_list_entries)
  322. seg->segment_list_entries = seg->segment_list_entries_end = entry;
  323. else
  324. seg->segment_list_entries_end->next = entry;
  325. seg->segment_list_entries_end = entry;
  326. /* drop first item */
  327. if (seg->list_size && seg->segment_count >= seg->list_size) {
  328. entry = seg->segment_list_entries;
  329. seg->segment_list_entries = seg->segment_list_entries->next;
  330. av_freep(&entry->filename);
  331. av_freep(&entry);
  332. }
  333. if ((ret = segment_list_open(s)) < 0)
  334. goto end;
  335. for (entry = seg->segment_list_entries; entry; entry = entry->next)
  336. segment_list_print_entry(seg->list_pb, seg->list_type, entry, s);
  337. if (seg->list_type == LIST_TYPE_M3U8 && is_last)
  338. avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
  339. ff_format_io_close(s, &seg->list_pb);
  340. if (seg->use_rename)
  341. ff_rename(seg->temp_list_filename, seg->list, s);
  342. } else {
  343. segment_list_print_entry(seg->list_pb, seg->list_type, &seg->cur_entry, s);
  344. avio_flush(seg->list_pb);
  345. }
  346. }
  347. av_log(s, AV_LOG_VERBOSE, "segment:'%s' count:%d ended\n",
  348. seg->avf->filename, seg->segment_count);
  349. seg->segment_count++;
  350. if (seg->increment_tc) {
  351. tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
  352. if (tcr) {
  353. /* search the first video stream */
  354. for (i = 0; i < s->nb_streams; i++) {
  355. if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  356. rate = s->streams[i]->avg_frame_rate;/* Get fps from the video stream */
  357. err = av_timecode_init_from_string(&tc, rate, tcr->value, s);
  358. if (err < 0) {
  359. av_log(s, AV_LOG_WARNING, "Could not increment timecode, error occurred during timecode creation.");
  360. break;
  361. }
  362. tc.start += (int)((seg->cur_entry.end_time - seg->cur_entry.start_time) * av_q2d(rate));/* increment timecode */
  363. av_dict_set(&s->metadata, "timecode",
  364. av_timecode_make_string(&tc, buf, 0), 0);
  365. break;
  366. }
  367. }
  368. } else {
  369. av_log(s, AV_LOG_WARNING, "Could not increment timecode, no timecode metadata found");
  370. }
  371. }
  372. end:
  373. ff_format_io_close(oc, &oc->pb);
  374. return ret;
  375. }
  376. static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
  377. const char *times_str)
  378. {
  379. char *p;
  380. int i, ret = 0;
  381. char *times_str1 = av_strdup(times_str);
  382. char *saveptr = NULL;
  383. if (!times_str1)
  384. return AVERROR(ENOMEM);
  385. #define FAIL(err) ret = err; goto end
  386. *nb_times = 1;
  387. for (p = times_str1; *p; p++)
  388. if (*p == ',')
  389. (*nb_times)++;
  390. *times = av_malloc_array(*nb_times, sizeof(**times));
  391. if (!*times) {
  392. av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
  393. FAIL(AVERROR(ENOMEM));
  394. }
  395. p = times_str1;
  396. for (i = 0; i < *nb_times; i++) {
  397. int64_t t;
  398. char *tstr = av_strtok(p, ",", &saveptr);
  399. p = NULL;
  400. if (!tstr || !tstr[0]) {
  401. av_log(log_ctx, AV_LOG_ERROR, "Empty time specification in times list %s\n",
  402. times_str);
  403. FAIL(AVERROR(EINVAL));
  404. }
  405. ret = av_parse_time(&t, tstr, 1);
  406. if (ret < 0) {
  407. av_log(log_ctx, AV_LOG_ERROR,
  408. "Invalid time duration specification '%s' in times list %s\n", tstr, times_str);
  409. FAIL(AVERROR(EINVAL));
  410. }
  411. (*times)[i] = t;
  412. /* check on monotonicity */
  413. if (i && (*times)[i-1] > (*times)[i]) {
  414. av_log(log_ctx, AV_LOG_ERROR,
  415. "Specified time %f is greater than the following time %f\n",
  416. (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
  417. FAIL(AVERROR(EINVAL));
  418. }
  419. }
  420. end:
  421. av_free(times_str1);
  422. return ret;
  423. }
  424. static int parse_frames(void *log_ctx, int **frames, int *nb_frames,
  425. const char *frames_str)
  426. {
  427. char *p;
  428. int i, ret = 0;
  429. char *frames_str1 = av_strdup(frames_str);
  430. char *saveptr = NULL;
  431. if (!frames_str1)
  432. return AVERROR(ENOMEM);
  433. #define FAIL(err) ret = err; goto end
  434. *nb_frames = 1;
  435. for (p = frames_str1; *p; p++)
  436. if (*p == ',')
  437. (*nb_frames)++;
  438. *frames = av_malloc_array(*nb_frames, sizeof(**frames));
  439. if (!*frames) {
  440. av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced frames array\n");
  441. FAIL(AVERROR(ENOMEM));
  442. }
  443. p = frames_str1;
  444. for (i = 0; i < *nb_frames; i++) {
  445. long int f;
  446. char *tailptr;
  447. char *fstr = av_strtok(p, ",", &saveptr);
  448. p = NULL;
  449. if (!fstr) {
  450. av_log(log_ctx, AV_LOG_ERROR, "Empty frame specification in frame list %s\n",
  451. frames_str);
  452. FAIL(AVERROR(EINVAL));
  453. }
  454. f = strtol(fstr, &tailptr, 10);
  455. if (*tailptr || f <= 0 || f >= INT_MAX) {
  456. av_log(log_ctx, AV_LOG_ERROR,
  457. "Invalid argument '%s', must be a positive integer <= INT64_MAX\n",
  458. fstr);
  459. FAIL(AVERROR(EINVAL));
  460. }
  461. (*frames)[i] = f;
  462. /* check on monotonicity */
  463. if (i && (*frames)[i-1] > (*frames)[i]) {
  464. av_log(log_ctx, AV_LOG_ERROR,
  465. "Specified frame %d is greater than the following frame %d\n",
  466. (*frames)[i], (*frames)[i-1]);
  467. FAIL(AVERROR(EINVAL));
  468. }
  469. }
  470. end:
  471. av_free(frames_str1);
  472. return ret;
  473. }
  474. static int open_null_ctx(AVIOContext **ctx)
  475. {
  476. int buf_size = 32768;
  477. uint8_t *buf = av_malloc(buf_size);
  478. if (!buf)
  479. return AVERROR(ENOMEM);
  480. *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
  481. if (!*ctx) {
  482. av_free(buf);
  483. return AVERROR(ENOMEM);
  484. }
  485. return 0;
  486. }
  487. static void close_null_ctxp(AVIOContext **pb)
  488. {
  489. av_freep(&(*pb)->buffer);
  490. av_freep(pb);
  491. }
  492. static int select_reference_stream(AVFormatContext *s)
  493. {
  494. SegmentContext *seg = s->priv_data;
  495. int ret, i;
  496. seg->reference_stream_index = -1;
  497. if (!strcmp(seg->reference_stream_specifier, "auto")) {
  498. /* select first index of type with highest priority */
  499. int type_index_map[AVMEDIA_TYPE_NB];
  500. static const enum AVMediaType type_priority_list[] = {
  501. AVMEDIA_TYPE_VIDEO,
  502. AVMEDIA_TYPE_AUDIO,
  503. AVMEDIA_TYPE_SUBTITLE,
  504. AVMEDIA_TYPE_DATA,
  505. AVMEDIA_TYPE_ATTACHMENT
  506. };
  507. enum AVMediaType type;
  508. for (i = 0; i < AVMEDIA_TYPE_NB; i++)
  509. type_index_map[i] = -1;
  510. /* select first index for each type */
  511. for (i = 0; i < s->nb_streams; i++) {
  512. type = s->streams[i]->codec->codec_type;
  513. if ((unsigned)type < AVMEDIA_TYPE_NB && type_index_map[type] == -1
  514. /* ignore attached pictures/cover art streams */
  515. && !(s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC))
  516. type_index_map[type] = i;
  517. }
  518. for (i = 0; i < FF_ARRAY_ELEMS(type_priority_list); i++) {
  519. type = type_priority_list[i];
  520. if ((seg->reference_stream_index = type_index_map[type]) >= 0)
  521. break;
  522. }
  523. } else {
  524. for (i = 0; i < s->nb_streams; i++) {
  525. ret = avformat_match_stream_specifier(s, s->streams[i],
  526. seg->reference_stream_specifier);
  527. if (ret < 0)
  528. return ret;
  529. if (ret > 0) {
  530. seg->reference_stream_index = i;
  531. break;
  532. }
  533. }
  534. }
  535. if (seg->reference_stream_index < 0) {
  536. av_log(s, AV_LOG_ERROR, "Could not select stream matching identifier '%s'\n",
  537. seg->reference_stream_specifier);
  538. return AVERROR(EINVAL);
  539. }
  540. return 0;
  541. }
  542. static void seg_free_context(SegmentContext *seg)
  543. {
  544. ff_format_io_close(seg->avf, &seg->list_pb);
  545. avformat_free_context(seg->avf);
  546. seg->avf = NULL;
  547. }
  548. static int seg_init(AVFormatContext *s)
  549. {
  550. SegmentContext *seg = s->priv_data;
  551. AVFormatContext *oc = seg->avf;
  552. AVDictionary *options = NULL;
  553. int ret;
  554. int i;
  555. seg->segment_count = 0;
  556. if (!seg->write_header_trailer)
  557. seg->individual_header_trailer = 0;
  558. if (seg->header_filename) {
  559. seg->write_header_trailer = 1;
  560. seg->individual_header_trailer = 0;
  561. }
  562. if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) {
  563. av_log(s, AV_LOG_ERROR,
  564. "segment_time, segment_times, and segment_frames options "
  565. "are mutually exclusive, select just one of them\n");
  566. return AVERROR(EINVAL);
  567. }
  568. if (seg->times_str) {
  569. if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
  570. return ret;
  571. } else if (seg->frames_str) {
  572. if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
  573. return ret;
  574. } else {
  575. /* set default value if not specified */
  576. if (!seg->time_str)
  577. seg->time_str = av_strdup("2");
  578. if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
  579. av_log(s, AV_LOG_ERROR,
  580. "Invalid time duration specification '%s' for segment_time option\n",
  581. seg->time_str);
  582. return ret;
  583. }
  584. if (seg->use_clocktime) {
  585. if (seg->time <= 0) {
  586. av_log(s, AV_LOG_ERROR, "Invalid negative segment_time with segment_atclocktime option set\n");
  587. return AVERROR(EINVAL);
  588. }
  589. seg->clocktime_offset = seg->time - (seg->clocktime_offset % seg->time);
  590. }
  591. }
  592. if (seg->format_options_str) {
  593. ret = av_dict_parse_string(&seg->format_options, seg->format_options_str, "=", ":", 0);
  594. if (ret < 0) {
  595. av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
  596. seg->format_options_str);
  597. goto fail;
  598. }
  599. }
  600. if (seg->list) {
  601. if (seg->list_type == LIST_TYPE_UNDEFINED) {
  602. if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
  603. else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
  604. else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
  605. else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
  606. else seg->list_type = LIST_TYPE_FLAT;
  607. }
  608. if (!seg->list_size && seg->list_type != LIST_TYPE_M3U8) {
  609. if ((ret = segment_list_open(s)) < 0)
  610. goto fail;
  611. } else {
  612. const char *proto = avio_find_protocol_name(s->filename);
  613. seg->use_rename = proto && !strcmp(proto, "file");
  614. }
  615. }
  616. if (seg->list_type == LIST_TYPE_EXT)
  617. av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
  618. if ((ret = select_reference_stream(s)) < 0)
  619. goto fail;
  620. av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
  621. seg->reference_stream_index,
  622. av_get_media_type_string(s->streams[seg->reference_stream_index]->codec->codec_type));
  623. seg->oformat = av_guess_format(seg->format, s->filename, NULL);
  624. if (!seg->oformat) {
  625. ret = AVERROR_MUXER_NOT_FOUND;
  626. goto fail;
  627. }
  628. if (seg->oformat->flags & AVFMT_NOFILE) {
  629. av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
  630. seg->oformat->name);
  631. ret = AVERROR(EINVAL);
  632. goto fail;
  633. }
  634. if ((ret = segment_mux_init(s)) < 0)
  635. goto fail;
  636. if ((ret = set_segment_filename(s)) < 0)
  637. goto fail;
  638. oc = seg->avf;
  639. if (seg->write_header_trailer) {
  640. if ((ret = s->io_open(s, &oc->pb,
  641. seg->header_filename ? seg->header_filename : oc->filename,
  642. AVIO_FLAG_WRITE, NULL)) < 0) {
  643. av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
  644. goto fail;
  645. }
  646. if (!seg->individual_header_trailer)
  647. oc->pb->seekable = 0;
  648. } else {
  649. if ((ret = open_null_ctx(&oc->pb)) < 0)
  650. goto fail;
  651. }
  652. av_dict_copy(&options, seg->format_options, 0);
  653. ret = avformat_write_header(oc, &options);
  654. if (av_dict_count(options)) {
  655. av_log(s, AV_LOG_ERROR,
  656. "Some of the provided format options in '%s' are not recognized\n", seg->format_options_str);
  657. ret = AVERROR(EINVAL);
  658. goto fail;
  659. }
  660. if (ret < 0) {
  661. ff_format_io_close(oc, &oc->pb);
  662. goto fail;
  663. }
  664. seg->segment_frame_count = 0;
  665. av_assert0(s->nb_streams == oc->nb_streams);
  666. for (i = 0; i < s->nb_streams; i++) {
  667. AVStream *inner_st = oc->streams[i];
  668. AVStream *outer_st = s->streams[i];
  669. avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
  670. }
  671. if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
  672. s->avoid_negative_ts = 1;
  673. if (!seg->write_header_trailer || seg->header_filename) {
  674. if (seg->header_filename) {
  675. av_write_frame(oc, NULL);
  676. ff_format_io_close(oc, &oc->pb);
  677. } else {
  678. close_null_ctxp(&oc->pb);
  679. }
  680. if ((ret = oc->io_open(oc, &oc->pb, oc->filename, AVIO_FLAG_WRITE, NULL)) < 0)
  681. goto fail;
  682. if (!seg->individual_header_trailer)
  683. oc->pb->seekable = 0;
  684. }
  685. fail:
  686. av_dict_free(&options);
  687. if (ret < 0)
  688. seg_free_context(seg);
  689. return ret;
  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. if (ret < 0)
  786. seg_free_context(seg);
  787. return ret;
  788. }
  789. static int seg_write_trailer(struct AVFormatContext *s)
  790. {
  791. SegmentContext *seg = s->priv_data;
  792. AVFormatContext *oc = seg->avf;
  793. SegmentListEntry *cur, *next;
  794. int ret = 0;
  795. if (!oc)
  796. goto fail;
  797. if (!seg->write_header_trailer) {
  798. if ((ret = segment_end(s, 0, 1)) < 0)
  799. goto fail;
  800. if ((ret = open_null_ctx(&oc->pb)) < 0)
  801. goto fail;
  802. ret = av_write_trailer(oc);
  803. close_null_ctxp(&oc->pb);
  804. } else {
  805. ret = segment_end(s, 1, 1);
  806. }
  807. fail:
  808. if (seg->list)
  809. ff_format_io_close(s, &seg->list_pb);
  810. av_dict_free(&seg->format_options);
  811. av_opt_free(seg);
  812. av_freep(&seg->times);
  813. av_freep(&seg->frames);
  814. av_freep(&seg->cur_entry.filename);
  815. cur = seg->segment_list_entries;
  816. while (cur) {
  817. next = cur->next;
  818. av_freep(&cur->filename);
  819. av_free(cur);
  820. cur = next;
  821. }
  822. avformat_free_context(oc);
  823. seg->avf = NULL;
  824. return ret;
  825. }
  826. static int seg_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
  827. {
  828. SegmentContext *seg = s->priv_data;
  829. AVFormatContext *oc = seg->avf;
  830. if (oc->oformat->check_bitstream) {
  831. int ret = oc->oformat->check_bitstream(oc, pkt);
  832. if (ret == 1) {
  833. AVStream *st = s->streams[pkt->stream_index];
  834. AVStream *ost = oc->streams[pkt->stream_index];
  835. st->internal->bsfc = ost->internal->bsfc;
  836. ost->internal->bsfc = NULL;
  837. }
  838. return ret;
  839. }
  840. return 1;
  841. }
  842. #define OFFSET(x) offsetof(SegmentContext, x)
  843. #define E AV_OPT_FLAG_ENCODING_PARAM
  844. static const AVOption options[] = {
  845. { "reference_stream", "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, CHAR_MIN, CHAR_MAX, E },
  846. { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  847. { "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 },
  848. { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  849. { "segment_header_filename", "write a single file containing the header", OFFSET(header_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  850. { "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"},
  851. { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
  852. { "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"},
  853. { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  854. { "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" },
  855. { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" },
  856. { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, E, "list_type" },
  857. { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, E, "list_type" },
  858. { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" },
  859. { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
  860. { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
  861. { "segment_atclocktime", "set segment to be cut at clocktime", OFFSET(use_clocktime), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E},
  862. { "segment_clocktime_offset", "set segment clocktime offset", OFFSET(clocktime_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 86400000000LL, E},
  863. { "segment_clocktime_wrap_duration", "set segment clocktime wrapping duration", OFFSET(clocktime_wrap_duration), AV_OPT_TYPE_DURATION, {.i64 = INT64_MAX}, 0, INT64_MAX, E},
  864. { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  865. { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 0, E },
  866. { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
  867. { "segment_frames", "set segment split frame numbers", OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
  868. { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  869. { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  870. { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  871. { "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 },
  872. { "strftime", "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
  873. { "increment_tc", "increment timecode between each segment", OFFSET(increment_tc), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
  874. { "break_non_keyframes", "allow breaking segments on non-keyframes", OFFSET(break_non_keyframes), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
  875. { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, E },
  876. { "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 },
  877. { "reset_timestamps", "reset timestamps at the begin of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
  878. { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
  879. { "write_empty_segments", "allow writing empty 'filler' segments", OFFSET(write_empty), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
  880. { NULL },
  881. };
  882. static const AVClass seg_class = {
  883. .class_name = "segment muxer",
  884. .item_name = av_default_item_name,
  885. .option = options,
  886. .version = LIBAVUTIL_VERSION_INT,
  887. };
  888. AVOutputFormat ff_segment_muxer = {
  889. .name = "segment",
  890. .long_name = NULL_IF_CONFIG_SMALL("segment"),
  891. .priv_data_size = sizeof(SegmentContext),
  892. .flags = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
  893. .init = seg_init,
  894. .write_packet = seg_write_packet,
  895. .write_trailer = seg_write_trailer,
  896. .check_bitstream = seg_check_bitstream,
  897. .priv_class = &seg_class,
  898. };
  899. static const AVClass sseg_class = {
  900. .class_name = "stream_segment muxer",
  901. .item_name = av_default_item_name,
  902. .option = options,
  903. .version = LIBAVUTIL_VERSION_INT,
  904. };
  905. AVOutputFormat ff_stream_segment_muxer = {
  906. .name = "stream_segment,ssegment",
  907. .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
  908. .priv_data_size = sizeof(SegmentContext),
  909. .flags = AVFMT_NOFILE,
  910. .init = seg_init,
  911. .write_packet = seg_write_packet,
  912. .write_trailer = seg_write_trailer,
  913. .check_bitstream = seg_check_bitstream,
  914. .priv_class = &sseg_class,
  915. };