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.

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