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.

936 lines
33KB

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