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.

947 lines
34KB

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