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
28KB

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