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.

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