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.

891 lines
32KB

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