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.

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