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.

879 lines
31KB

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