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.

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