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.

982 lines
36KB

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