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.

917 lines
33KB

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