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.

849 lines
30KB

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