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.

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