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.

850 lines
30KB

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