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.

762 lines
26KB

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