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.

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