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.

970 lines
35KB

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