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.

995 lines
37KB

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