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.

933 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 {
  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_close(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_close(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 int seg_write_header(AVFormatContext *s)
  493. {
  494. SegmentContext *seg = s->priv_data;
  495. AVFormatContext *oc = NULL;
  496. AVDictionary *options = NULL;
  497. int ret;
  498. int i;
  499. seg->segment_count = 0;
  500. if (!seg->write_header_trailer)
  501. seg->individual_header_trailer = 0;
  502. if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) {
  503. av_log(s, AV_LOG_ERROR,
  504. "segment_time, segment_times, and segment_frames options "
  505. "are mutually exclusive, select just one of them\n");
  506. return AVERROR(EINVAL);
  507. }
  508. if (seg->times_str) {
  509. if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
  510. return ret;
  511. } else if (seg->frames_str) {
  512. if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
  513. return ret;
  514. } else {
  515. /* set default value if not specified */
  516. if (!seg->time_str)
  517. seg->time_str = av_strdup("2");
  518. if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
  519. av_log(s, AV_LOG_ERROR,
  520. "Invalid time duration specification '%s' for segment_time option\n",
  521. seg->time_str);
  522. return ret;
  523. }
  524. }
  525. if (seg->format_options_str) {
  526. ret = av_dict_parse_string(&seg->format_options, seg->format_options_str, "=", ":", 0);
  527. if (ret < 0) {
  528. av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
  529. seg->format_options_str);
  530. goto fail;
  531. }
  532. }
  533. if (seg->list) {
  534. if (seg->list_type == LIST_TYPE_UNDEFINED) {
  535. if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
  536. else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
  537. else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
  538. else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
  539. else seg->list_type = LIST_TYPE_FLAT;
  540. }
  541. if ((ret = segment_list_open(s)) < 0)
  542. goto fail;
  543. }
  544. if (seg->list_type == LIST_TYPE_EXT)
  545. av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
  546. if ((ret = select_reference_stream(s)) < 0)
  547. goto fail;
  548. av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
  549. seg->reference_stream_index,
  550. av_get_media_type_string(s->streams[seg->reference_stream_index]->codec->codec_type));
  551. seg->oformat = av_guess_format(seg->format, s->filename, NULL);
  552. if (!seg->oformat) {
  553. ret = AVERROR_MUXER_NOT_FOUND;
  554. goto fail;
  555. }
  556. if (seg->oformat->flags & AVFMT_NOFILE) {
  557. av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
  558. seg->oformat->name);
  559. ret = AVERROR(EINVAL);
  560. goto fail;
  561. }
  562. if ((ret = segment_mux_init(s)) < 0)
  563. goto fail;
  564. oc = seg->avf;
  565. if ((ret = set_segment_filename(s)) < 0)
  566. goto fail;
  567. if (seg->write_header_trailer) {
  568. if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
  569. &s->interrupt_callback, NULL)) < 0) {
  570. av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
  571. goto fail;
  572. }
  573. } else {
  574. if ((ret = open_null_ctx(&oc->pb)) < 0)
  575. goto fail;
  576. }
  577. av_dict_copy(&options, seg->format_options, 0);
  578. ret = avformat_write_header(oc, &options);
  579. if (av_dict_count(options)) {
  580. av_log(s, AV_LOG_ERROR,
  581. "Some of the provided format options in '%s' are not recognized\n", seg->format_options_str);
  582. ret = AVERROR(EINVAL);
  583. goto fail;
  584. }
  585. if (ret < 0) {
  586. avio_close(oc->pb);
  587. goto fail;
  588. }
  589. seg->segment_frame_count = 0;
  590. av_assert0(s->nb_streams == oc->nb_streams);
  591. for (i = 0; i < s->nb_streams; i++) {
  592. AVStream *inner_st = oc->streams[i];
  593. AVStream *outer_st = s->streams[i];
  594. avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
  595. }
  596. if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
  597. s->avoid_negative_ts = 1;
  598. if (!seg->write_header_trailer) {
  599. close_null_ctxp(&oc->pb);
  600. if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
  601. &s->interrupt_callback, NULL)) < 0)
  602. goto fail;
  603. }
  604. fail:
  605. av_dict_free(&options);
  606. if (ret) {
  607. if (seg->list)
  608. avio_close(seg->list_pb);
  609. if (seg->avf)
  610. avformat_free_context(seg->avf);
  611. }
  612. return ret;
  613. }
  614. static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
  615. {
  616. SegmentContext *seg = s->priv_data;
  617. AVStream *st = s->streams[pkt->stream_index];
  618. int64_t end_pts = INT64_MAX, offset;
  619. int start_frame = INT_MAX;
  620. int ret;
  621. struct tm ti;
  622. int64_t usecs;
  623. int64_t wrapped_val;
  624. if (seg->times) {
  625. end_pts = seg->segment_count < seg->nb_times ?
  626. seg->times[seg->segment_count] : INT64_MAX;
  627. } else if (seg->frames) {
  628. start_frame = seg->segment_count < seg->nb_frames ?
  629. seg->frames[seg->segment_count] : INT_MAX;
  630. } else {
  631. if (seg->use_clocktime) {
  632. int64_t avgt = av_gettime();
  633. time_t sec = avgt / 1000000;
  634. localtime_r(&sec, &ti);
  635. usecs = (int64_t)(ti.tm_hour*3600 + ti.tm_min*60 + ti.tm_sec) * 1000000 + (avgt % 1000000);
  636. wrapped_val = usecs % seg->time;
  637. if (seg->last_cut != usecs && wrapped_val < seg->last_val) {
  638. seg->cut_pending = 1;
  639. seg->last_cut = usecs;
  640. }
  641. seg->last_val = wrapped_val;
  642. } else {
  643. end_pts = seg->time * (seg->segment_count+1);
  644. }
  645. }
  646. av_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",
  647. pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
  648. av_ts2timestr(pkt->duration, &st->time_base),
  649. pkt->flags & AV_PKT_FLAG_KEY,
  650. pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);
  651. if (pkt->stream_index == seg->reference_stream_index &&
  652. pkt->flags & AV_PKT_FLAG_KEY &&
  653. seg->segment_frame_count > 0 &&
  654. (seg->cut_pending || seg->frame_count >= start_frame ||
  655. (pkt->pts != AV_NOPTS_VALUE &&
  656. av_compare_ts(pkt->pts, st->time_base,
  657. end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0))) {
  658. /* sanitize end time in case last packet didn't have a defined duration */
  659. if (seg->cur_entry.last_duration == 0)
  660. seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);
  661. if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)
  662. goto fail;
  663. if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)
  664. goto fail;
  665. seg->cut_pending = 0;
  666. seg->cur_entry.index = seg->segment_idx + seg->segment_idx_wrap*seg->segment_idx_wrap_nb;
  667. seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);
  668. seg->cur_entry.start_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
  669. seg->cur_entry.end_time = seg->cur_entry.start_time +
  670. pkt->pts != AV_NOPTS_VALUE ? (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base) : 0;
  671. } else if (pkt->pts != AV_NOPTS_VALUE && pkt->stream_index == seg->reference_stream_index) {
  672. seg->cur_entry.end_time =
  673. FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
  674. seg->cur_entry.last_duration = pkt->duration;
  675. }
  676. if (seg->segment_frame_count == 0) {
  677. av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",
  678. seg->avf->filename, pkt->stream_index,
  679. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);
  680. }
  681. av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",
  682. pkt->stream_index,
  683. av_ts2timestr(seg->cur_entry.start_pts, &AV_TIME_BASE_Q),
  684. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
  685. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
  686. /* compute new timestamps */
  687. offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),
  688. AV_TIME_BASE_Q, st->time_base);
  689. if (pkt->pts != AV_NOPTS_VALUE)
  690. pkt->pts += offset;
  691. if (pkt->dts != AV_NOPTS_VALUE)
  692. pkt->dts += offset;
  693. av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
  694. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
  695. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
  696. ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s, seg->initial_offset || seg->reset_timestamps);
  697. fail:
  698. if (pkt->stream_index == seg->reference_stream_index) {
  699. seg->frame_count++;
  700. seg->segment_frame_count++;
  701. }
  702. return ret;
  703. }
  704. static int seg_write_trailer(struct AVFormatContext *s)
  705. {
  706. SegmentContext *seg = s->priv_data;
  707. AVFormatContext *oc = seg->avf;
  708. SegmentListEntry *cur, *next;
  709. int ret;
  710. if (!seg->write_header_trailer) {
  711. if ((ret = segment_end(s, 0, 1)) < 0)
  712. goto fail;
  713. open_null_ctx(&oc->pb);
  714. ret = av_write_trailer(oc);
  715. close_null_ctxp(&oc->pb);
  716. } else {
  717. ret = segment_end(s, 1, 1);
  718. }
  719. fail:
  720. if (seg->list)
  721. avio_close(seg->list_pb);
  722. av_dict_free(&seg->format_options);
  723. av_opt_free(seg);
  724. av_freep(&seg->times);
  725. av_freep(&seg->frames);
  726. cur = seg->segment_list_entries;
  727. while (cur) {
  728. next = cur->next;
  729. av_freep(&cur->filename);
  730. av_free(cur);
  731. cur = next;
  732. }
  733. avformat_free_context(oc);
  734. return ret;
  735. }
  736. #define OFFSET(x) offsetof(SegmentContext, x)
  737. #define E AV_OPT_FLAG_ENCODING_PARAM
  738. static const AVOption options[] = {
  739. { "reference_stream", "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, CHAR_MIN, CHAR_MAX, E },
  740. { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  741. { "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 },
  742. { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  743. { "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"},
  744. { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
  745. { "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"},
  746. { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  747. { "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" },
  748. { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" },
  749. { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, E, "list_type" },
  750. { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, E, "list_type" },
  751. { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" },
  752. { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
  753. { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
  754. { "segment_atclocktime", "set segment to be cut at clocktime", OFFSET(use_clocktime), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E},
  755. { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  756. { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 0, E },
  757. { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
  758. { "segment_frames", "set segment split frame numbers", OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
  759. { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  760. { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  761. { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  762. { "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 },
  763. { "strftime", "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, E },
  764. { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
  765. { "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 },
  766. { "reset_timestamps", "reset timestamps at the begin of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
  767. { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
  768. { NULL },
  769. };
  770. static const AVClass seg_class = {
  771. .class_name = "segment muxer",
  772. .item_name = av_default_item_name,
  773. .option = options,
  774. .version = LIBAVUTIL_VERSION_INT,
  775. };
  776. AVOutputFormat ff_segment_muxer = {
  777. .name = "segment",
  778. .long_name = NULL_IF_CONFIG_SMALL("segment"),
  779. .priv_data_size = sizeof(SegmentContext),
  780. .flags = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
  781. .write_header = seg_write_header,
  782. .write_packet = seg_write_packet,
  783. .write_trailer = seg_write_trailer,
  784. .priv_class = &seg_class,
  785. };
  786. static const AVClass sseg_class = {
  787. .class_name = "stream_segment muxer",
  788. .item_name = av_default_item_name,
  789. .option = options,
  790. .version = LIBAVUTIL_VERSION_INT,
  791. };
  792. AVOutputFormat ff_stream_segment_muxer = {
  793. .name = "stream_segment,ssegment",
  794. .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
  795. .priv_data_size = sizeof(SegmentContext),
  796. .flags = AVFMT_NOFILE,
  797. .write_header = seg_write_header,
  798. .write_packet = seg_write_packet,
  799. .write_trailer = seg_write_trailer,
  800. .priv_class = &sseg_class,
  801. };