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.

834 lines
29KB

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