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.

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