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.

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