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.

844 lines
29KB

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