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.

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