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.

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