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.

1970 lines
74KB

  1. /*
  2. * MPEG-DASH ISO BMFF segmenter
  3. * Copyright (c) 2014 Martin Storsjo
  4. * Copyright (c) 2018 Akamai Technologies, Inc.
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include "config.h"
  23. #if HAVE_UNISTD_H
  24. #include <unistd.h>
  25. #endif
  26. #include "libavutil/avassert.h"
  27. #include "libavutil/avutil.h"
  28. #include "libavutil/avstring.h"
  29. #include "libavutil/intreadwrite.h"
  30. #include "libavutil/mathematics.h"
  31. #include "libavutil/opt.h"
  32. #include "libavutil/rational.h"
  33. #include "libavutil/time.h"
  34. #include "libavutil/time_internal.h"
  35. #include "av1.h"
  36. #include "avc.h"
  37. #include "avformat.h"
  38. #include "avio_internal.h"
  39. #include "hlsplaylist.h"
  40. #if CONFIG_HTTP_PROTOCOL
  41. #include "http.h"
  42. #endif
  43. #include "internal.h"
  44. #include "isom.h"
  45. #include "os_support.h"
  46. #include "url.h"
  47. #include "vpcc.h"
  48. #include "dash.h"
  49. typedef enum {
  50. SEGMENT_TYPE_AUTO = 0,
  51. SEGMENT_TYPE_MP4,
  52. SEGMENT_TYPE_WEBM,
  53. SEGMENT_TYPE_NB
  54. } SegmentType;
  55. typedef struct Segment {
  56. char file[1024];
  57. int64_t start_pos;
  58. int range_length, index_length;
  59. int64_t time;
  60. double prog_date_time;
  61. int64_t duration;
  62. int n;
  63. } Segment;
  64. typedef struct AdaptationSet {
  65. char id[10];
  66. char *descriptor;
  67. enum AVMediaType media_type;
  68. AVDictionary *metadata;
  69. AVRational min_frame_rate, max_frame_rate;
  70. int ambiguous_frame_rate;
  71. } AdaptationSet;
  72. typedef struct OutputStream {
  73. AVFormatContext *ctx;
  74. int ctx_inited, as_idx;
  75. AVIOContext *out;
  76. int packets_written;
  77. char initfile[1024];
  78. int64_t init_start_pos, pos;
  79. int init_range_length;
  80. int nb_segments, segments_size, segment_index;
  81. Segment **segments;
  82. int64_t first_pts, start_pts, max_pts;
  83. int64_t last_dts, last_pts;
  84. int bit_rate;
  85. SegmentType segment_type; /* segment type selected for this particular stream */
  86. const char *format_name;
  87. const char *extension_name;
  88. const char *single_file_name; /* file names selected for this particular stream */
  89. const char *init_seg_name;
  90. const char *media_seg_name;
  91. char codec_str[100];
  92. int written_len;
  93. char filename[1024];
  94. char full_path[1024];
  95. char temp_path[1024];
  96. double availability_time_offset;
  97. int total_pkt_size;
  98. int muxer_overhead;
  99. } OutputStream;
  100. typedef struct DASHContext {
  101. const AVClass *class; /* Class for private options. */
  102. char *adaptation_sets;
  103. AdaptationSet *as;
  104. int nb_as;
  105. int window_size;
  106. int extra_window_size;
  107. #if FF_API_DASH_MIN_SEG_DURATION
  108. int min_seg_duration;
  109. #endif
  110. int64_t seg_duration;
  111. int remove_at_exit;
  112. int use_template;
  113. int use_timeline;
  114. int single_file;
  115. OutputStream *streams;
  116. int has_video;
  117. int64_t last_duration;
  118. int64_t total_duration;
  119. char availability_start_time[100];
  120. time_t start_time_s;
  121. char dirname[1024];
  122. const char *single_file_name; /* file names as specified in options */
  123. const char *init_seg_name;
  124. const char *media_seg_name;
  125. const char *utc_timing_url;
  126. const char *method;
  127. const char *user_agent;
  128. int hls_playlist;
  129. int http_persistent;
  130. int master_playlist_created;
  131. AVIOContext *mpd_out;
  132. AVIOContext *m3u8_out;
  133. int streaming;
  134. int64_t timeout;
  135. int index_correction;
  136. char *format_options_str;
  137. int global_sidx;
  138. SegmentType segment_type_option; /* segment type as specified in options */
  139. int ignore_io_errors;
  140. int lhls;
  141. int master_publish_rate;
  142. int nr_of_streams_to_flush;
  143. int nr_of_streams_flushed;
  144. } DASHContext;
  145. static struct codec_string {
  146. int id;
  147. const char *str;
  148. } codecs[] = {
  149. { AV_CODEC_ID_VP8, "vp8" },
  150. { AV_CODEC_ID_VP9, "vp9" },
  151. { AV_CODEC_ID_VORBIS, "vorbis" },
  152. { AV_CODEC_ID_OPUS, "opus" },
  153. { AV_CODEC_ID_FLAC, "flac" },
  154. { 0, NULL }
  155. };
  156. static struct format_string {
  157. SegmentType segment_type;
  158. const char *str;
  159. } formats[] = {
  160. { SEGMENT_TYPE_AUTO, "auto" },
  161. { SEGMENT_TYPE_MP4, "mp4" },
  162. { SEGMENT_TYPE_WEBM, "webm" },
  163. { 0, NULL }
  164. };
  165. static int dashenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
  166. AVDictionary **options) {
  167. DASHContext *c = s->priv_data;
  168. int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
  169. int err = AVERROR_MUXER_NOT_FOUND;
  170. if (!*pb || !http_base_proto || !c->http_persistent) {
  171. err = s->io_open(s, pb, filename, AVIO_FLAG_WRITE, options);
  172. #if CONFIG_HTTP_PROTOCOL
  173. } else {
  174. URLContext *http_url_context = ffio_geturlcontext(*pb);
  175. av_assert0(http_url_context);
  176. err = ff_http_do_new_request(http_url_context, filename);
  177. if (err < 0)
  178. ff_format_io_close(s, pb);
  179. #endif
  180. }
  181. return err;
  182. }
  183. static void dashenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename) {
  184. DASHContext *c = s->priv_data;
  185. int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
  186. if (!*pb)
  187. return;
  188. if (!http_base_proto || !c->http_persistent) {
  189. ff_format_io_close(s, pb);
  190. #if CONFIG_HTTP_PROTOCOL
  191. } else {
  192. URLContext *http_url_context = ffio_geturlcontext(*pb);
  193. av_assert0(http_url_context);
  194. avio_flush(*pb);
  195. ffurl_shutdown(http_url_context, AVIO_FLAG_WRITE);
  196. #endif
  197. }
  198. }
  199. static const char *get_format_str(SegmentType segment_type) {
  200. int i;
  201. for (i = 0; i < SEGMENT_TYPE_NB; i++)
  202. if (formats[i].segment_type == segment_type)
  203. return formats[i].str;
  204. return NULL;
  205. }
  206. static const char *get_extension_str(SegmentType type, int single_file)
  207. {
  208. switch (type) {
  209. case SEGMENT_TYPE_MP4: return single_file ? "mp4" : "m4s";
  210. case SEGMENT_TYPE_WEBM: return "webm";
  211. default: return NULL;
  212. }
  213. }
  214. static int handle_io_open_error(AVFormatContext *s, int err, char *url) {
  215. DASHContext *c = s->priv_data;
  216. char errbuf[AV_ERROR_MAX_STRING_SIZE];
  217. av_strerror(err, errbuf, sizeof(errbuf));
  218. av_log(s, c->ignore_io_errors ? AV_LOG_WARNING : AV_LOG_ERROR,
  219. "Unable to open %s for writing: %s\n", url, errbuf);
  220. return c->ignore_io_errors ? 0 : err;
  221. }
  222. static inline SegmentType select_segment_type(SegmentType segment_type, enum AVCodecID codec_id)
  223. {
  224. if (segment_type == SEGMENT_TYPE_AUTO) {
  225. if (codec_id == AV_CODEC_ID_OPUS || codec_id == AV_CODEC_ID_VORBIS ||
  226. codec_id == AV_CODEC_ID_VP8 || codec_id == AV_CODEC_ID_VP9) {
  227. segment_type = SEGMENT_TYPE_WEBM;
  228. } else {
  229. segment_type = SEGMENT_TYPE_MP4;
  230. }
  231. }
  232. return segment_type;
  233. }
  234. static int init_segment_types(AVFormatContext *s)
  235. {
  236. DASHContext *c = s->priv_data;
  237. int has_mp4_streams = 0;
  238. for (int i = 0; i < s->nb_streams; ++i) {
  239. OutputStream *os = &c->streams[i];
  240. SegmentType segment_type = select_segment_type(
  241. c->segment_type_option, s->streams[i]->codecpar->codec_id);
  242. os->segment_type = segment_type;
  243. os->format_name = get_format_str(segment_type);
  244. if (!os->format_name) {
  245. av_log(s, AV_LOG_ERROR, "Could not select DASH segment type for stream %d\n", i);
  246. return AVERROR_MUXER_NOT_FOUND;
  247. }
  248. os->extension_name = get_extension_str(segment_type, c->single_file);
  249. if (!os->extension_name) {
  250. av_log(s, AV_LOG_ERROR, "Could not get extension type for stream %d\n", i);
  251. return AVERROR_MUXER_NOT_FOUND;
  252. }
  253. has_mp4_streams |= segment_type == SEGMENT_TYPE_MP4;
  254. }
  255. if (c->hls_playlist && !has_mp4_streams) {
  256. av_log(s, AV_LOG_WARNING, "No mp4 streams, disabling HLS manifest generation\n");
  257. c->hls_playlist = 0;
  258. }
  259. return 0;
  260. }
  261. static int check_file_extension(const char *filename, const char *extension) {
  262. char *dot;
  263. if (!filename || !extension)
  264. return -1;
  265. dot = strrchr(filename, '.');
  266. if (dot && !strcmp(dot + 1, extension))
  267. return 0;
  268. return -1;
  269. }
  270. static void set_vp9_codec_str(AVFormatContext *s, AVCodecParameters *par,
  271. AVRational *frame_rate, char *str, int size) {
  272. VPCC vpcc;
  273. int ret = ff_isom_get_vpcc_features(s, par, frame_rate, &vpcc);
  274. if (ret == 0) {
  275. av_strlcatf(str, size, "vp09.%02d.%02d.%02d",
  276. vpcc.profile, vpcc.level, vpcc.bitdepth);
  277. } else {
  278. // Default to just vp9 in case of error while finding out profile or level
  279. av_log(s, AV_LOG_WARNING, "Could not find VP9 profile and/or level\n");
  280. av_strlcpy(str, "vp9", size);
  281. }
  282. return;
  283. }
  284. static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
  285. AVRational *frame_rate, char *str, int size)
  286. {
  287. const AVCodecTag *tags[2] = { NULL, NULL };
  288. uint32_t tag;
  289. int i;
  290. // common Webm codecs are not part of RFC 6381
  291. for (i = 0; codecs[i].id; i++)
  292. if (codecs[i].id == par->codec_id) {
  293. if (codecs[i].id == AV_CODEC_ID_VP9) {
  294. set_vp9_codec_str(s, par, frame_rate, str, size);
  295. } else {
  296. av_strlcpy(str, codecs[i].str, size);
  297. }
  298. return;
  299. }
  300. // for codecs part of RFC 6381
  301. if (par->codec_type == AVMEDIA_TYPE_VIDEO)
  302. tags[0] = ff_codec_movvideo_tags;
  303. else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
  304. tags[0] = ff_codec_movaudio_tags;
  305. else
  306. return;
  307. tag = par->codec_tag;
  308. if (!tag)
  309. tag = av_codec_get_tag(tags, par->codec_id);
  310. if (!tag)
  311. return;
  312. if (size < 5)
  313. return;
  314. AV_WL32(str, tag);
  315. str[4] = '\0';
  316. if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
  317. uint32_t oti;
  318. tags[0] = ff_mp4_obj_type;
  319. oti = av_codec_get_tag(tags, par->codec_id);
  320. if (oti)
  321. av_strlcatf(str, size, ".%02"PRIx32, oti);
  322. else
  323. return;
  324. if (tag == MKTAG('m', 'p', '4', 'a')) {
  325. if (par->extradata_size >= 2) {
  326. int aot = par->extradata[0] >> 3;
  327. if (aot == 31)
  328. aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
  329. av_strlcatf(str, size, ".%d", aot);
  330. }
  331. } else if (tag == MKTAG('m', 'p', '4', 'v')) {
  332. // Unimplemented, should output ProfileLevelIndication as a decimal number
  333. av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
  334. }
  335. } else if (!strcmp(str, "avc1")) {
  336. uint8_t *tmpbuf = NULL;
  337. uint8_t *extradata = par->extradata;
  338. int extradata_size = par->extradata_size;
  339. if (!extradata_size)
  340. return;
  341. if (extradata[0] != 1) {
  342. AVIOContext *pb;
  343. if (avio_open_dyn_buf(&pb) < 0)
  344. return;
  345. if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
  346. ffio_free_dyn_buf(&pb);
  347. return;
  348. }
  349. extradata_size = avio_close_dyn_buf(pb, &extradata);
  350. tmpbuf = extradata;
  351. }
  352. if (extradata_size >= 4)
  353. av_strlcatf(str, size, ".%02x%02x%02x",
  354. extradata[1], extradata[2], extradata[3]);
  355. av_free(tmpbuf);
  356. } else if (!strcmp(str, "av01")) {
  357. AV1SequenceParameters seq;
  358. if (!par->extradata_size)
  359. return;
  360. if (ff_av1_parse_seq_header(&seq, par->extradata, par->extradata_size) < 0)
  361. return;
  362. av_strlcatf(str, size, ".%01u.%02u%s.%02u",
  363. seq.profile, seq.level, seq.tier ? "H" : "M", seq.bitdepth);
  364. if (seq.color_description_present_flag)
  365. av_strlcatf(str, size, ".%01u.%01u%01u%01u.%02u.%02u.%02u.%01u",
  366. seq.monochrome,
  367. seq.chroma_subsampling_x, seq.chroma_subsampling_y, seq.chroma_sample_position,
  368. seq.color_primaries, seq.transfer_characteristics, seq.matrix_coefficients,
  369. seq.color_range);
  370. }
  371. }
  372. static int flush_dynbuf(DASHContext *c, OutputStream *os, int *range_length)
  373. {
  374. uint8_t *buffer;
  375. if (!os->ctx->pb) {
  376. return AVERROR(EINVAL);
  377. }
  378. // flush
  379. av_write_frame(os->ctx, NULL);
  380. avio_flush(os->ctx->pb);
  381. if (!c->single_file) {
  382. // write out to file
  383. *range_length = avio_close_dyn_buf(os->ctx->pb, &buffer);
  384. os->ctx->pb = NULL;
  385. if (os->out)
  386. avio_write(os->out, buffer + os->written_len, *range_length - os->written_len);
  387. os->written_len = 0;
  388. av_free(buffer);
  389. // re-open buffer
  390. return avio_open_dyn_buf(&os->ctx->pb);
  391. } else {
  392. *range_length = avio_tell(os->ctx->pb) - os->pos;
  393. return 0;
  394. }
  395. }
  396. static void set_http_options(AVDictionary **options, DASHContext *c)
  397. {
  398. if (c->method)
  399. av_dict_set(options, "method", c->method, 0);
  400. if (c->user_agent)
  401. av_dict_set(options, "user_agent", c->user_agent, 0);
  402. if (c->http_persistent)
  403. av_dict_set_int(options, "multiple_requests", 1, 0);
  404. if (c->timeout >= 0)
  405. av_dict_set_int(options, "timeout", c->timeout, 0);
  406. }
  407. static void get_hls_playlist_name(char *playlist_name, int string_size,
  408. const char *base_url, int id) {
  409. if (base_url)
  410. snprintf(playlist_name, string_size, "%smedia_%d.m3u8", base_url, id);
  411. else
  412. snprintf(playlist_name, string_size, "media_%d.m3u8", id);
  413. }
  414. static void get_start_index_number(OutputStream *os, DASHContext *c,
  415. int *start_index, int *start_number) {
  416. *start_index = 0;
  417. *start_number = 1;
  418. if (c->window_size) {
  419. *start_index = FFMAX(os->nb_segments - c->window_size, 0);
  420. *start_number = FFMAX(os->segment_index - c->window_size, 1);
  421. }
  422. }
  423. static void write_hls_media_playlist(OutputStream *os, AVFormatContext *s,
  424. int representation_id, int final,
  425. char *prefetch_url) {
  426. DASHContext *c = s->priv_data;
  427. int timescale = os->ctx->streams[0]->time_base.den;
  428. char temp_filename_hls[1024];
  429. char filename_hls[1024];
  430. AVDictionary *http_opts = NULL;
  431. int target_duration = 0;
  432. int ret = 0;
  433. const char *proto = avio_find_protocol_name(c->dirname);
  434. int use_rename = proto && !strcmp(proto, "file");
  435. int i, start_index, start_number;
  436. double prog_date_time = 0;
  437. get_start_index_number(os, c, &start_index, &start_number);
  438. if (!c->hls_playlist || start_index >= os->nb_segments ||
  439. os->segment_type != SEGMENT_TYPE_MP4)
  440. return;
  441. get_hls_playlist_name(filename_hls, sizeof(filename_hls),
  442. c->dirname, representation_id);
  443. snprintf(temp_filename_hls, sizeof(temp_filename_hls), use_rename ? "%s.tmp" : "%s", filename_hls);
  444. set_http_options(&http_opts, c);
  445. ret = dashenc_io_open(s, &c->m3u8_out, temp_filename_hls, &http_opts);
  446. av_dict_free(&http_opts);
  447. if (ret < 0) {
  448. handle_io_open_error(s, ret, temp_filename_hls);
  449. return;
  450. }
  451. for (i = start_index; i < os->nb_segments; i++) {
  452. Segment *seg = os->segments[i];
  453. double duration = (double) seg->duration / timescale;
  454. if (target_duration <= duration)
  455. target_duration = lrint(duration);
  456. }
  457. ff_hls_write_playlist_header(c->m3u8_out, 6, -1, target_duration,
  458. start_number, PLAYLIST_TYPE_NONE, 0);
  459. ff_hls_write_init_file(c->m3u8_out, os->initfile, c->single_file,
  460. os->init_range_length, os->init_start_pos);
  461. for (i = start_index; i < os->nb_segments; i++) {
  462. Segment *seg = os->segments[i];
  463. if (prog_date_time == 0) {
  464. if (os->nb_segments == 1)
  465. prog_date_time = c->start_time_s;
  466. else
  467. prog_date_time = seg->prog_date_time;
  468. }
  469. seg->prog_date_time = prog_date_time;
  470. ret = ff_hls_write_file_entry(c->m3u8_out, 0, c->single_file,
  471. (double) seg->duration / timescale, 0,
  472. seg->range_length, seg->start_pos, NULL,
  473. c->single_file ? os->initfile : seg->file,
  474. &prog_date_time, 0, 0, 0);
  475. if (ret < 0) {
  476. av_log(os->ctx, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
  477. }
  478. }
  479. if (prefetch_url)
  480. avio_printf(c->m3u8_out, "#EXT-X-PREFETCH:%s\n", prefetch_url);
  481. if (final)
  482. ff_hls_write_end_list(c->m3u8_out);
  483. dashenc_io_close(s, &c->m3u8_out, temp_filename_hls);
  484. if (use_rename)
  485. if (avpriv_io_move(temp_filename_hls, filename_hls) < 0) {
  486. av_log(os->ctx, AV_LOG_WARNING, "renaming file %s to %s failed\n\n", temp_filename_hls, filename_hls);
  487. }
  488. }
  489. static int flush_init_segment(AVFormatContext *s, OutputStream *os)
  490. {
  491. DASHContext *c = s->priv_data;
  492. int ret, range_length;
  493. ret = flush_dynbuf(c, os, &range_length);
  494. if (ret < 0)
  495. return ret;
  496. os->pos = os->init_range_length = range_length;
  497. if (!c->single_file) {
  498. char filename[1024];
  499. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
  500. dashenc_io_close(s, &os->out, filename);
  501. }
  502. return 0;
  503. }
  504. static void dash_free(AVFormatContext *s)
  505. {
  506. DASHContext *c = s->priv_data;
  507. int i, j;
  508. if (c->as) {
  509. for (i = 0; i < c->nb_as; i++) {
  510. av_dict_free(&c->as[i].metadata);
  511. av_freep(&c->as[i].descriptor);
  512. }
  513. av_freep(&c->as);
  514. c->nb_as = 0;
  515. }
  516. if (!c->streams)
  517. return;
  518. for (i = 0; i < s->nb_streams; i++) {
  519. OutputStream *os = &c->streams[i];
  520. if (os->ctx && os->ctx->pb) {
  521. if (!c->single_file)
  522. ffio_free_dyn_buf(&os->ctx->pb);
  523. else
  524. avio_close(os->ctx->pb);
  525. }
  526. ff_format_io_close(s, &os->out);
  527. if (os->ctx)
  528. avformat_free_context(os->ctx);
  529. for (j = 0; j < os->nb_segments; j++)
  530. av_free(os->segments[j]);
  531. av_free(os->segments);
  532. av_freep(&os->single_file_name);
  533. av_freep(&os->init_seg_name);
  534. av_freep(&os->media_seg_name);
  535. }
  536. av_freep(&c->streams);
  537. ff_format_io_close(s, &c->mpd_out);
  538. ff_format_io_close(s, &c->m3u8_out);
  539. }
  540. static void output_segment_list(OutputStream *os, AVIOContext *out, AVFormatContext *s,
  541. int representation_id, int final)
  542. {
  543. DASHContext *c = s->priv_data;
  544. int i, start_index, start_number;
  545. get_start_index_number(os, c, &start_index, &start_number);
  546. if (c->use_template) {
  547. int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
  548. avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
  549. if (!c->use_timeline) {
  550. avio_printf(out, "duration=\"%"PRId64"\" ", c->seg_duration);
  551. if (c->streaming && os->availability_time_offset)
  552. avio_printf(out, "availabilityTimeOffset=\"%.3f\" ",
  553. os->availability_time_offset);
  554. }
  555. avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", os->init_seg_name, os->media_seg_name, c->use_timeline ? start_number : 1);
  556. if (c->use_timeline) {
  557. int64_t cur_time = 0;
  558. avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
  559. for (i = start_index; i < os->nb_segments; ) {
  560. Segment *seg = os->segments[i];
  561. int repeat = 0;
  562. avio_printf(out, "\t\t\t\t\t\t<S ");
  563. if (i == start_index || seg->time != cur_time) {
  564. cur_time = seg->time;
  565. avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
  566. }
  567. avio_printf(out, "d=\"%"PRId64"\" ", seg->duration);
  568. while (i + repeat + 1 < os->nb_segments &&
  569. os->segments[i + repeat + 1]->duration == seg->duration &&
  570. os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
  571. repeat++;
  572. if (repeat > 0)
  573. avio_printf(out, "r=\"%d\" ", repeat);
  574. avio_printf(out, "/>\n");
  575. i += 1 + repeat;
  576. cur_time += (1 + repeat) * seg->duration;
  577. }
  578. avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
  579. }
  580. avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
  581. } else if (c->single_file) {
  582. avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
  583. avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
  584. avio_printf(out, "\t\t\t\t\t<Initialization range=\"%"PRId64"-%"PRId64"\" />\n", os->init_start_pos, os->init_start_pos + os->init_range_length - 1);
  585. for (i = start_index; i < os->nb_segments; i++) {
  586. Segment *seg = os->segments[i];
  587. avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
  588. if (seg->index_length)
  589. avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
  590. avio_printf(out, "/>\n");
  591. }
  592. avio_printf(out, "\t\t\t\t</SegmentList>\n");
  593. } else {
  594. avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
  595. avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
  596. for (i = start_index; i < os->nb_segments; i++) {
  597. Segment *seg = os->segments[i];
  598. avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
  599. }
  600. avio_printf(out, "\t\t\t\t</SegmentList>\n");
  601. }
  602. if (!c->lhls || final) {
  603. write_hls_media_playlist(os, s, representation_id, final, NULL);
  604. }
  605. }
  606. static char *xmlescape(const char *str) {
  607. int outlen = strlen(str)*3/2 + 6;
  608. char *out = av_realloc(NULL, outlen + 1);
  609. int pos = 0;
  610. if (!out)
  611. return NULL;
  612. for (; *str; str++) {
  613. if (pos + 6 > outlen) {
  614. char *tmp;
  615. outlen = 2 * outlen + 6;
  616. tmp = av_realloc(out, outlen + 1);
  617. if (!tmp) {
  618. av_free(out);
  619. return NULL;
  620. }
  621. out = tmp;
  622. }
  623. if (*str == '&') {
  624. memcpy(&out[pos], "&amp;", 5);
  625. pos += 5;
  626. } else if (*str == '<') {
  627. memcpy(&out[pos], "&lt;", 4);
  628. pos += 4;
  629. } else if (*str == '>') {
  630. memcpy(&out[pos], "&gt;", 4);
  631. pos += 4;
  632. } else if (*str == '\'') {
  633. memcpy(&out[pos], "&apos;", 6);
  634. pos += 6;
  635. } else if (*str == '\"') {
  636. memcpy(&out[pos], "&quot;", 6);
  637. pos += 6;
  638. } else {
  639. out[pos++] = *str;
  640. }
  641. }
  642. out[pos] = '\0';
  643. return out;
  644. }
  645. static void write_time(AVIOContext *out, int64_t time)
  646. {
  647. int seconds = time / AV_TIME_BASE;
  648. int fractions = time % AV_TIME_BASE;
  649. int minutes = seconds / 60;
  650. int hours = minutes / 60;
  651. seconds %= 60;
  652. minutes %= 60;
  653. avio_printf(out, "PT");
  654. if (hours)
  655. avio_printf(out, "%dH", hours);
  656. if (hours || minutes)
  657. avio_printf(out, "%dM", minutes);
  658. avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
  659. }
  660. static void format_date_now(char *buf, int size)
  661. {
  662. struct tm *ptm, tmbuf;
  663. int64_t time_us = av_gettime();
  664. int64_t time_ms = time_us / 1000;
  665. const time_t time_s = time_ms / 1000;
  666. int millisec = time_ms - (time_s * 1000);
  667. ptm = gmtime_r(&time_s, &tmbuf);
  668. if (ptm) {
  669. int len;
  670. if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%S", ptm)) {
  671. buf[0] = '\0';
  672. return;
  673. }
  674. len = strlen(buf);
  675. snprintf(buf + len, size - len, ".%03dZ", millisec);
  676. }
  677. }
  678. static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index,
  679. int final)
  680. {
  681. DASHContext *c = s->priv_data;
  682. AdaptationSet *as = &c->as[as_index];
  683. AVDictionaryEntry *lang, *role;
  684. int i;
  685. avio_printf(out, "\t\t<AdaptationSet id=\"%s\" contentType=\"%s\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
  686. as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
  687. if (as->media_type == AVMEDIA_TYPE_VIDEO && as->max_frame_rate.num && !as->ambiguous_frame_rate && av_cmp_q(as->min_frame_rate, as->max_frame_rate) < 0)
  688. avio_printf(out, " maxFrameRate=\"%d/%d\"", as->max_frame_rate.num, as->max_frame_rate.den);
  689. lang = av_dict_get(as->metadata, "language", NULL, 0);
  690. if (lang)
  691. avio_printf(out, " lang=\"%s\"", lang->value);
  692. avio_printf(out, ">\n");
  693. role = av_dict_get(as->metadata, "role", NULL, 0);
  694. if (role)
  695. avio_printf(out, "\t\t\t<Role schemeIdUri=\"urn:mpeg:dash:role:2011\" value=\"%s\"/>\n", role->value);
  696. if (as->descriptor)
  697. avio_printf(out, "\t\t\t%s\n", as->descriptor);
  698. for (i = 0; i < s->nb_streams; i++) {
  699. OutputStream *os = &c->streams[i];
  700. char bandwidth_str[64] = {'\0'};
  701. if (os->as_idx - 1 != as_index)
  702. continue;
  703. if (os->bit_rate > 0)
  704. snprintf(bandwidth_str, sizeof(bandwidth_str), " bandwidth=\"%d\"",
  705. os->bit_rate);
  706. if (as->media_type == AVMEDIA_TYPE_VIDEO) {
  707. AVStream *st = s->streams[i];
  708. avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/%s\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"",
  709. i, os->format_name, os->codec_str, bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
  710. if (st->avg_frame_rate.num)
  711. avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
  712. avio_printf(out, ">\n");
  713. } else {
  714. avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/%s\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
  715. i, os->format_name, os->codec_str, bandwidth_str, s->streams[i]->codecpar->sample_rate);
  716. avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
  717. s->streams[i]->codecpar->channels);
  718. }
  719. output_segment_list(os, out, s, i, final);
  720. avio_printf(out, "\t\t\t</Representation>\n");
  721. }
  722. avio_printf(out, "\t\t</AdaptationSet>\n");
  723. return 0;
  724. }
  725. static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
  726. {
  727. DASHContext *c = s->priv_data;
  728. void *mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
  729. if (!mem)
  730. return AVERROR(ENOMEM);
  731. c->as = mem;
  732. ++c->nb_as;
  733. *as = &c->as[c->nb_as - 1];
  734. memset(*as, 0, sizeof(**as));
  735. (*as)->media_type = type;
  736. return 0;
  737. }
  738. static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
  739. {
  740. DASHContext *c = s->priv_data;
  741. AdaptationSet *as = &c->as[as_idx - 1];
  742. OutputStream *os = &c->streams[i];
  743. if (as->media_type != s->streams[i]->codecpar->codec_type) {
  744. av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
  745. return AVERROR(EINVAL);
  746. } else if (os->as_idx) {
  747. av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
  748. return AVERROR(EINVAL);
  749. }
  750. os->as_idx = as_idx;
  751. return 0;
  752. }
  753. static int parse_adaptation_sets(AVFormatContext *s)
  754. {
  755. DASHContext *c = s->priv_data;
  756. const char *p = c->adaptation_sets;
  757. enum { new_set, parse_id, parsing_streams, parse_descriptor } state;
  758. AdaptationSet *as;
  759. int i, n, ret;
  760. // default: one AdaptationSet for each stream
  761. if (!p) {
  762. for (i = 0; i < s->nb_streams; i++) {
  763. if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
  764. return ret;
  765. snprintf(as->id, sizeof(as->id), "%d", i);
  766. c->streams[i].as_idx = c->nb_as;
  767. }
  768. goto end;
  769. }
  770. // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
  771. // option id=0,descriptor=descriptor_str,streams=0,1,2 and so on
  772. // descriptor is useful to the scheme defined by ISO/IEC 23009-1:2014/Amd.2:2015
  773. // descriptor_str should be a self-closing xml tag.
  774. state = new_set;
  775. while (*p) {
  776. if (*p == ' ') {
  777. p++;
  778. continue;
  779. } else if (state == new_set && av_strstart(p, "id=", &p)) {
  780. if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
  781. return ret;
  782. n = strcspn(p, ",");
  783. snprintf(as->id, sizeof(as->id), "%.*s", n, p);
  784. p += n;
  785. if (*p)
  786. p++;
  787. state = parse_id;
  788. } else if (state == parse_id && av_strstart(p, "descriptor=", &p)) {
  789. n = strcspn(p, ">") + 1; //followed by one comma, so plus 1
  790. if (n < strlen(p)) {
  791. as->descriptor = av_strndup(p, n);
  792. } else {
  793. av_log(s, AV_LOG_ERROR, "Parse error, descriptor string should be a self-closing xml tag\n");
  794. return AVERROR(EINVAL);
  795. }
  796. p += n;
  797. if (*p)
  798. p++;
  799. state = parse_descriptor;
  800. } else if ((state == parse_id || state == parse_descriptor) && av_strstart(p, "streams=", &p)) { //descriptor is optional
  801. state = parsing_streams;
  802. } else if (state == parsing_streams) {
  803. AdaptationSet *as = &c->as[c->nb_as - 1];
  804. char idx_str[8], *end_str;
  805. n = strcspn(p, " ,");
  806. snprintf(idx_str, sizeof(idx_str), "%.*s", n, p);
  807. p += n;
  808. // if value is "a" or "v", map all streams of that type
  809. if (as->media_type == AVMEDIA_TYPE_UNKNOWN && (idx_str[0] == 'v' || idx_str[0] == 'a')) {
  810. enum AVMediaType type = (idx_str[0] == 'v') ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
  811. av_log(s, AV_LOG_DEBUG, "Map all streams of type %s\n", idx_str);
  812. for (i = 0; i < s->nb_streams; i++) {
  813. if (s->streams[i]->codecpar->codec_type != type)
  814. continue;
  815. as->media_type = s->streams[i]->codecpar->codec_type;
  816. if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
  817. return ret;
  818. }
  819. } else { // select single stream
  820. i = strtol(idx_str, &end_str, 10);
  821. if (idx_str == end_str || i < 0 || i >= s->nb_streams) {
  822. av_log(s, AV_LOG_ERROR, "Selected stream \"%s\" not found!\n", idx_str);
  823. return AVERROR(EINVAL);
  824. }
  825. av_log(s, AV_LOG_DEBUG, "Map stream %d\n", i);
  826. if (as->media_type == AVMEDIA_TYPE_UNKNOWN) {
  827. as->media_type = s->streams[i]->codecpar->codec_type;
  828. }
  829. if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
  830. return ret;
  831. }
  832. if (*p == ' ')
  833. state = new_set;
  834. if (*p)
  835. p++;
  836. } else {
  837. return AVERROR(EINVAL);
  838. }
  839. }
  840. end:
  841. // check for unassigned streams
  842. for (i = 0; i < s->nb_streams; i++) {
  843. OutputStream *os = &c->streams[i];
  844. if (!os->as_idx) {
  845. av_log(s, AV_LOG_ERROR, "Stream %d is not mapped to an AdaptationSet\n", i);
  846. return AVERROR(EINVAL);
  847. }
  848. }
  849. return 0;
  850. }
  851. static int write_manifest(AVFormatContext *s, int final)
  852. {
  853. DASHContext *c = s->priv_data;
  854. AVIOContext *out;
  855. char temp_filename[1024];
  856. int ret, i;
  857. const char *proto = avio_find_protocol_name(s->url);
  858. int use_rename = proto && !strcmp(proto, "file");
  859. static unsigned int warned_non_file = 0;
  860. AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
  861. AVDictionary *opts = NULL;
  862. if (!use_rename && !warned_non_file++)
  863. av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
  864. snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->url);
  865. set_http_options(&opts, c);
  866. ret = dashenc_io_open(s, &c->mpd_out, temp_filename, &opts);
  867. av_dict_free(&opts);
  868. if (ret < 0) {
  869. return handle_io_open_error(s, ret, temp_filename);
  870. }
  871. out = c->mpd_out;
  872. avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  873. avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
  874. "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
  875. "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
  876. "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
  877. "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
  878. "\ttype=\"%s\"\n", final ? "static" : "dynamic");
  879. if (final) {
  880. avio_printf(out, "\tmediaPresentationDuration=\"");
  881. write_time(out, c->total_duration);
  882. avio_printf(out, "\"\n");
  883. } else {
  884. int64_t update_period = c->last_duration / AV_TIME_BASE;
  885. char now_str[100];
  886. if (c->use_template && !c->use_timeline)
  887. update_period = 500;
  888. avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
  889. avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
  890. if (c->availability_start_time[0])
  891. avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
  892. format_date_now(now_str, sizeof(now_str));
  893. if (now_str[0])
  894. avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
  895. if (c->window_size && c->use_template) {
  896. avio_printf(out, "\ttimeShiftBufferDepth=\"");
  897. write_time(out, c->last_duration * c->window_size);
  898. avio_printf(out, "\"\n");
  899. }
  900. }
  901. avio_printf(out, "\tminBufferTime=\"");
  902. write_time(out, c->last_duration * 2);
  903. avio_printf(out, "\">\n");
  904. avio_printf(out, "\t<ProgramInformation>\n");
  905. if (title) {
  906. char *escaped = xmlescape(title->value);
  907. avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
  908. av_free(escaped);
  909. }
  910. avio_printf(out, "\t</ProgramInformation>\n");
  911. if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
  912. OutputStream *os = &c->streams[0];
  913. int start_index = FFMAX(os->nb_segments - c->window_size, 0);
  914. int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
  915. avio_printf(out, "\t<Period id=\"0\" start=\"");
  916. write_time(out, start_time);
  917. avio_printf(out, "\">\n");
  918. } else {
  919. avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
  920. }
  921. for (i = 0; i < c->nb_as; i++) {
  922. if ((ret = write_adaptation_set(s, out, i, final)) < 0)
  923. return ret;
  924. }
  925. avio_printf(out, "\t</Period>\n");
  926. if (c->utc_timing_url)
  927. avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
  928. avio_printf(out, "</MPD>\n");
  929. avio_flush(out);
  930. dashenc_io_close(s, &c->mpd_out, temp_filename);
  931. if (use_rename) {
  932. if ((ret = avpriv_io_move(temp_filename, s->url)) < 0)
  933. return ret;
  934. }
  935. if (c->hls_playlist) {
  936. char filename_hls[1024];
  937. const char *audio_group = "A1";
  938. char audio_codec_str[128] = "\0";
  939. int is_default = 1;
  940. int max_audio_bitrate = 0;
  941. // Publish master playlist only the configured rate
  942. if (c->master_playlist_created && (!c->master_publish_rate ||
  943. c->streams[0].segment_index % c->master_publish_rate))
  944. return 0;
  945. if (*c->dirname)
  946. snprintf(filename_hls, sizeof(filename_hls), "%smaster.m3u8", c->dirname);
  947. else
  948. snprintf(filename_hls, sizeof(filename_hls), "master.m3u8");
  949. snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", filename_hls);
  950. set_http_options(&opts, c);
  951. ret = dashenc_io_open(s, &c->m3u8_out, temp_filename, &opts);
  952. av_dict_free(&opts);
  953. if (ret < 0) {
  954. return handle_io_open_error(s, ret, temp_filename);
  955. }
  956. ff_hls_write_playlist_version(c->m3u8_out, 7);
  957. for (i = 0; i < s->nb_streams; i++) {
  958. char playlist_file[64];
  959. AVStream *st = s->streams[i];
  960. OutputStream *os = &c->streams[i];
  961. if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
  962. continue;
  963. if (os->segment_type != SEGMENT_TYPE_MP4)
  964. continue;
  965. get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
  966. ff_hls_write_audio_rendition(c->m3u8_out, (char *)audio_group,
  967. playlist_file, NULL, i, is_default);
  968. max_audio_bitrate = FFMAX(st->codecpar->bit_rate +
  969. os->muxer_overhead, max_audio_bitrate);
  970. if (!av_strnstr(audio_codec_str, os->codec_str, sizeof(audio_codec_str))) {
  971. if (strlen(audio_codec_str))
  972. av_strlcat(audio_codec_str, ",", sizeof(audio_codec_str));
  973. av_strlcat(audio_codec_str, os->codec_str, sizeof(audio_codec_str));
  974. }
  975. is_default = 0;
  976. }
  977. for (i = 0; i < s->nb_streams; i++) {
  978. char playlist_file[64];
  979. char codec_str[128];
  980. AVStream *st = s->streams[i];
  981. OutputStream *os = &c->streams[i];
  982. char *agroup = NULL;
  983. char *codec_str_ptr = NULL;
  984. int stream_bitrate = st->codecpar->bit_rate + os->muxer_overhead;
  985. if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
  986. continue;
  987. if (os->segment_type != SEGMENT_TYPE_MP4)
  988. continue;
  989. av_strlcpy(codec_str, os->codec_str, sizeof(codec_str));
  990. if (max_audio_bitrate) {
  991. agroup = (char *)audio_group;
  992. stream_bitrate += max_audio_bitrate;
  993. av_strlcat(codec_str, ",", sizeof(codec_str));
  994. av_strlcat(codec_str, audio_codec_str, sizeof(codec_str));
  995. }
  996. if (st->codecpar->codec_id != AV_CODEC_ID_HEVC) {
  997. codec_str_ptr = codec_str;
  998. }
  999. get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
  1000. ff_hls_write_stream_info(st, c->m3u8_out, stream_bitrate,
  1001. playlist_file, agroup,
  1002. codec_str_ptr, NULL);
  1003. }
  1004. dashenc_io_close(s, &c->m3u8_out, temp_filename);
  1005. if (use_rename)
  1006. if ((ret = avpriv_io_move(temp_filename, filename_hls)) < 0)
  1007. return ret;
  1008. c->master_playlist_created = 1;
  1009. }
  1010. return 0;
  1011. }
  1012. static int dict_copy_entry(AVDictionary **dst, const AVDictionary *src, const char *key)
  1013. {
  1014. AVDictionaryEntry *entry = av_dict_get(src, key, NULL, 0);
  1015. if (entry)
  1016. av_dict_set(dst, key, entry->value, AV_DICT_DONT_OVERWRITE);
  1017. return 0;
  1018. }
  1019. static int dash_init(AVFormatContext *s)
  1020. {
  1021. DASHContext *c = s->priv_data;
  1022. int ret = 0, i;
  1023. char *ptr;
  1024. char basename[1024];
  1025. c->nr_of_streams_to_flush = 0;
  1026. if (c->single_file_name)
  1027. c->single_file = 1;
  1028. if (c->single_file)
  1029. c->use_template = 0;
  1030. #if FF_API_DASH_MIN_SEG_DURATION
  1031. if (c->min_seg_duration != 5000000) {
  1032. av_log(s, AV_LOG_WARNING, "The min_seg_duration option is deprecated and will be removed. Please use the -seg_duration\n");
  1033. c->seg_duration = c->min_seg_duration;
  1034. }
  1035. #endif
  1036. if (c->lhls && s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
  1037. av_log(s, AV_LOG_ERROR,
  1038. "LHLS is experimental, Please set -strict experimental in order to enable it.\n");
  1039. return AVERROR_EXPERIMENTAL;
  1040. }
  1041. if (c->lhls && !c->streaming) {
  1042. av_log(s, AV_LOG_WARNING, "LHLS option will be ignored as streaming is not enabled\n");
  1043. c->lhls = 0;
  1044. }
  1045. if (c->lhls && !c->hls_playlist) {
  1046. av_log(s, AV_LOG_WARNING, "LHLS option will be ignored as hls_playlist is not enabled\n");
  1047. c->lhls = 0;
  1048. }
  1049. if (c->global_sidx && !c->single_file) {
  1050. av_log(s, AV_LOG_WARNING, "Global SIDX option will be ignored as single_file is not enabled\n");
  1051. c->global_sidx = 0;
  1052. }
  1053. if (c->global_sidx && c->streaming) {
  1054. av_log(s, AV_LOG_WARNING, "Global SIDX option will be ignored as streaming is enabled\n");
  1055. c->global_sidx = 0;
  1056. }
  1057. av_strlcpy(c->dirname, s->url, sizeof(c->dirname));
  1058. ptr = strrchr(c->dirname, '/');
  1059. if (ptr) {
  1060. av_strlcpy(basename, &ptr[1], sizeof(basename));
  1061. ptr[1] = '\0';
  1062. } else {
  1063. c->dirname[0] = '\0';
  1064. av_strlcpy(basename, s->url, sizeof(basename));
  1065. }
  1066. ptr = strrchr(basename, '.');
  1067. if (ptr)
  1068. *ptr = '\0';
  1069. c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
  1070. if (!c->streams)
  1071. return AVERROR(ENOMEM);
  1072. if ((ret = parse_adaptation_sets(s)) < 0)
  1073. return ret;
  1074. if ((ret = init_segment_types(s)) < 0)
  1075. return ret;
  1076. for (i = 0; i < s->nb_streams; i++) {
  1077. OutputStream *os = &c->streams[i];
  1078. AdaptationSet *as = &c->as[os->as_idx - 1];
  1079. AVFormatContext *ctx;
  1080. AVStream *st;
  1081. AVDictionary *opts = NULL;
  1082. char filename[1024];
  1083. os->bit_rate = s->streams[i]->codecpar->bit_rate;
  1084. if (!os->bit_rate) {
  1085. int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
  1086. AV_LOG_ERROR : AV_LOG_WARNING;
  1087. av_log(s, level, "No bit rate set for stream %d\n", i);
  1088. if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
  1089. return AVERROR(EINVAL);
  1090. }
  1091. // copy AdaptationSet language and role from stream metadata
  1092. dict_copy_entry(&as->metadata, s->streams[i]->metadata, "language");
  1093. dict_copy_entry(&as->metadata, s->streams[i]->metadata, "role");
  1094. ctx = avformat_alloc_context();
  1095. if (!ctx)
  1096. return AVERROR(ENOMEM);
  1097. if (c->init_seg_name) {
  1098. os->init_seg_name = av_strireplace(c->init_seg_name, "$ext$", os->extension_name);
  1099. if (!os->init_seg_name)
  1100. return AVERROR(ENOMEM);
  1101. }
  1102. if (c->media_seg_name) {
  1103. os->media_seg_name = av_strireplace(c->media_seg_name, "$ext$", os->extension_name);
  1104. if (!os->media_seg_name)
  1105. return AVERROR(ENOMEM);
  1106. }
  1107. if (c->single_file_name) {
  1108. os->single_file_name = av_strireplace(c->single_file_name, "$ext$", os->extension_name);
  1109. if (!os->single_file_name)
  1110. return AVERROR(ENOMEM);
  1111. }
  1112. if (os->segment_type == SEGMENT_TYPE_WEBM) {
  1113. if ((!c->single_file && check_file_extension(os->init_seg_name, os->format_name) != 0) ||
  1114. (!c->single_file && check_file_extension(os->media_seg_name, os->format_name) != 0) ||
  1115. (c->single_file && check_file_extension(os->single_file_name, os->format_name) != 0)) {
  1116. av_log(s, AV_LOG_WARNING,
  1117. "One or many segment file names doesn't end with .webm. "
  1118. "Override -init_seg_name and/or -media_seg_name and/or "
  1119. "-single_file_name to end with the extension .webm\n");
  1120. }
  1121. if (c->streaming) {
  1122. // Streaming not supported as matroskaenc buffers internally before writing the output
  1123. av_log(s, AV_LOG_WARNING, "One or more streams in WebM output format. Streaming option will be ignored\n");
  1124. c->streaming = 0;
  1125. }
  1126. }
  1127. ctx->oformat = av_guess_format(os->format_name, NULL, NULL);
  1128. if (!ctx->oformat)
  1129. return AVERROR_MUXER_NOT_FOUND;
  1130. os->ctx = ctx;
  1131. ctx->interrupt_callback = s->interrupt_callback;
  1132. ctx->opaque = s->opaque;
  1133. ctx->io_close = s->io_close;
  1134. ctx->io_open = s->io_open;
  1135. ctx->strict_std_compliance = s->strict_std_compliance;
  1136. if (!(st = avformat_new_stream(ctx, NULL)))
  1137. return AVERROR(ENOMEM);
  1138. avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
  1139. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  1140. st->time_base = s->streams[i]->time_base;
  1141. st->avg_frame_rate = s->streams[i]->avg_frame_rate;
  1142. ctx->avoid_negative_ts = s->avoid_negative_ts;
  1143. ctx->flags = s->flags;
  1144. if (c->single_file) {
  1145. if (os->single_file_name)
  1146. ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), os->single_file_name, i, 0, os->bit_rate, 0);
  1147. else
  1148. snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.%s", basename, i, os->format_name);
  1149. } else {
  1150. ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), os->init_seg_name, i, 0, os->bit_rate, 0);
  1151. }
  1152. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
  1153. set_http_options(&opts, c);
  1154. if (!c->single_file) {
  1155. if ((ret = avio_open_dyn_buf(&ctx->pb)) < 0)
  1156. return ret;
  1157. ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, &opts);
  1158. } else {
  1159. ctx->url = av_strdup(filename);
  1160. ret = avio_open2(&ctx->pb, filename, AVIO_FLAG_WRITE, NULL, &opts);
  1161. }
  1162. av_dict_free(&opts);
  1163. if (ret < 0)
  1164. return ret;
  1165. os->init_start_pos = 0;
  1166. if (c->format_options_str) {
  1167. ret = av_dict_parse_string(&opts, c->format_options_str, "=", ":", 0);
  1168. if (ret < 0)
  1169. return ret;
  1170. }
  1171. if (os->segment_type == SEGMENT_TYPE_MP4) {
  1172. if (c->streaming)
  1173. // frag_every_frame : Allows lower latency streaming
  1174. // skip_sidx : Reduce bitrate overhead
  1175. // skip_trailer : Avoids growing memory usage with time
  1176. av_dict_set(&opts, "movflags", "frag_every_frame+dash+delay_moov+skip_sidx+skip_trailer", 0);
  1177. else {
  1178. if (c->global_sidx)
  1179. av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov+global_sidx+skip_trailer", 0);
  1180. else
  1181. av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov+skip_trailer", 0);
  1182. }
  1183. } else {
  1184. av_dict_set_int(&opts, "cluster_time_limit", c->seg_duration / 1000, 0);
  1185. av_dict_set_int(&opts, "cluster_size_limit", 5 * 1024 * 1024, 0); // set a large cluster size limit
  1186. av_dict_set_int(&opts, "dash", 1, 0);
  1187. av_dict_set_int(&opts, "dash_track_number", i + 1, 0);
  1188. av_dict_set_int(&opts, "live", 1, 0);
  1189. }
  1190. ret = avformat_init_output(ctx, &opts);
  1191. av_dict_free(&opts);
  1192. if (ret < 0)
  1193. return ret;
  1194. os->ctx_inited = 1;
  1195. avio_flush(ctx->pb);
  1196. av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
  1197. s->streams[i]->time_base = st->time_base;
  1198. // If the muxer wants to shift timestamps, request to have them shifted
  1199. // already before being handed to this muxer, so we don't have mismatches
  1200. // between the MPD and the actual segments.
  1201. s->avoid_negative_ts = ctx->avoid_negative_ts;
  1202. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  1203. AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
  1204. if (avg_frame_rate.num > 0) {
  1205. if (av_cmp_q(avg_frame_rate, as->min_frame_rate) < 0)
  1206. as->min_frame_rate = avg_frame_rate;
  1207. if (av_cmp_q(as->max_frame_rate, avg_frame_rate) < 0)
  1208. as->max_frame_rate = avg_frame_rate;
  1209. } else {
  1210. as->ambiguous_frame_rate = 1;
  1211. }
  1212. c->has_video = 1;
  1213. }
  1214. set_codec_str(s, st->codecpar, &st->avg_frame_rate, os->codec_str,
  1215. sizeof(os->codec_str));
  1216. os->first_pts = AV_NOPTS_VALUE;
  1217. os->max_pts = AV_NOPTS_VALUE;
  1218. os->last_dts = AV_NOPTS_VALUE;
  1219. os->segment_index = 1;
  1220. if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  1221. c->nr_of_streams_to_flush++;
  1222. }
  1223. if (!c->has_video && c->seg_duration <= 0) {
  1224. av_log(s, AV_LOG_WARNING, "no video stream and no seg duration set\n");
  1225. return AVERROR(EINVAL);
  1226. }
  1227. c->nr_of_streams_flushed = 0;
  1228. return 0;
  1229. }
  1230. static int dash_write_header(AVFormatContext *s)
  1231. {
  1232. DASHContext *c = s->priv_data;
  1233. int i, ret;
  1234. for (i = 0; i < s->nb_streams; i++) {
  1235. OutputStream *os = &c->streams[i];
  1236. if ((ret = avformat_write_header(os->ctx, NULL)) < 0)
  1237. return ret;
  1238. // Flush init segment
  1239. // Only for WebM segment, since for mp4 delay_moov is set and
  1240. // the init segment is thus flushed after the first packets.
  1241. if (os->segment_type == SEGMENT_TYPE_WEBM &&
  1242. (ret = flush_init_segment(s, os)) < 0)
  1243. return ret;
  1244. }
  1245. return ret;
  1246. }
  1247. static int add_segment(OutputStream *os, const char *file,
  1248. int64_t time, int64_t duration,
  1249. int64_t start_pos, int64_t range_length,
  1250. int64_t index_length, int next_exp_index)
  1251. {
  1252. int err;
  1253. Segment *seg;
  1254. if (os->nb_segments >= os->segments_size) {
  1255. os->segments_size = (os->segments_size + 1) * 2;
  1256. if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
  1257. os->segments_size)) < 0) {
  1258. os->segments_size = 0;
  1259. os->nb_segments = 0;
  1260. return err;
  1261. }
  1262. }
  1263. seg = av_mallocz(sizeof(*seg));
  1264. if (!seg)
  1265. return AVERROR(ENOMEM);
  1266. av_strlcpy(seg->file, file, sizeof(seg->file));
  1267. seg->time = time;
  1268. seg->duration = duration;
  1269. if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
  1270. seg->duration += seg->time;
  1271. seg->time = 0;
  1272. }
  1273. seg->start_pos = start_pos;
  1274. seg->range_length = range_length;
  1275. seg->index_length = index_length;
  1276. os->segments[os->nb_segments++] = seg;
  1277. os->segment_index++;
  1278. //correcting the segment index if it has fallen behind the expected value
  1279. if (os->segment_index < next_exp_index) {
  1280. av_log(NULL, AV_LOG_WARNING, "Correcting the segment index after file %s: current=%d corrected=%d\n",
  1281. file, os->segment_index, next_exp_index);
  1282. os->segment_index = next_exp_index;
  1283. }
  1284. return 0;
  1285. }
  1286. static void write_styp(AVIOContext *pb)
  1287. {
  1288. avio_wb32(pb, 24);
  1289. ffio_wfourcc(pb, "styp");
  1290. ffio_wfourcc(pb, "msdh");
  1291. avio_wb32(pb, 0); /* minor */
  1292. ffio_wfourcc(pb, "msdh");
  1293. ffio_wfourcc(pb, "msix");
  1294. }
  1295. static void find_index_range(AVFormatContext *s, const char *full_path,
  1296. int64_t pos, int *index_length)
  1297. {
  1298. uint8_t buf[8];
  1299. AVIOContext *pb;
  1300. int ret;
  1301. ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
  1302. if (ret < 0)
  1303. return;
  1304. if (avio_seek(pb, pos, SEEK_SET) != pos) {
  1305. ff_format_io_close(s, &pb);
  1306. return;
  1307. }
  1308. ret = avio_read(pb, buf, 8);
  1309. ff_format_io_close(s, &pb);
  1310. if (ret < 8)
  1311. return;
  1312. if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
  1313. return;
  1314. *index_length = AV_RB32(&buf[0]);
  1315. }
  1316. static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
  1317. AVPacket *pkt, AVRational *frame_rate)
  1318. {
  1319. AVCodecParameters *par = os->ctx->streams[0]->codecpar;
  1320. uint8_t *extradata;
  1321. int ret, extradata_size;
  1322. if (par->extradata_size)
  1323. return 0;
  1324. extradata = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &extradata_size);
  1325. if (!extradata_size)
  1326. return 0;
  1327. ret = ff_alloc_extradata(par, extradata_size);
  1328. if (ret < 0)
  1329. return ret;
  1330. memcpy(par->extradata, extradata, extradata_size);
  1331. set_codec_str(s, par, frame_rate, os->codec_str, sizeof(os->codec_str));
  1332. return 0;
  1333. }
  1334. static void dashenc_delete_file(AVFormatContext *s, char *filename) {
  1335. DASHContext *c = s->priv_data;
  1336. int http_base_proto = ff_is_http_proto(filename);
  1337. if (http_base_proto) {
  1338. AVIOContext *out = NULL;
  1339. AVDictionary *http_opts = NULL;
  1340. set_http_options(&http_opts, c);
  1341. av_dict_set(&http_opts, "method", "DELETE", 0);
  1342. if (dashenc_io_open(s, &out, filename, &http_opts) < 0) {
  1343. av_log(s, AV_LOG_ERROR, "failed to delete %s\n", filename);
  1344. }
  1345. av_dict_free(&http_opts);
  1346. ff_format_io_close(s, &out);
  1347. } else {
  1348. int res = avpriv_io_delete(filename);
  1349. if (res < 0) {
  1350. char errbuf[AV_ERROR_MAX_STRING_SIZE];
  1351. av_strerror(res, errbuf, sizeof(errbuf));
  1352. av_log(s, (res == AVERROR(ENOENT) ? AV_LOG_WARNING : AV_LOG_ERROR), "failed to delete %s: %s\n", filename, errbuf);
  1353. }
  1354. }
  1355. }
  1356. static int dashenc_delete_segment_file(AVFormatContext *s, const char* file)
  1357. {
  1358. DASHContext *c = s->priv_data;
  1359. size_t dirname_len, file_len;
  1360. char filename[1024];
  1361. dirname_len = strlen(c->dirname);
  1362. if (dirname_len >= sizeof(filename)) {
  1363. av_log(s, AV_LOG_WARNING, "Cannot delete segments as the directory path is too long: %"PRIu64" characters: %s\n",
  1364. (uint64_t)dirname_len, c->dirname);
  1365. return AVERROR(ENAMETOOLONG);
  1366. }
  1367. memcpy(filename, c->dirname, dirname_len);
  1368. file_len = strlen(file);
  1369. if ((dirname_len + file_len) >= sizeof(filename)) {
  1370. av_log(s, AV_LOG_WARNING, "Cannot delete segments as the path is too long: %"PRIu64" characters: %s%s\n",
  1371. (uint64_t)(dirname_len + file_len), c->dirname, file);
  1372. return AVERROR(ENAMETOOLONG);
  1373. }
  1374. memcpy(filename + dirname_len, file, file_len + 1); // include the terminating zero
  1375. dashenc_delete_file(s, filename);
  1376. return 0;
  1377. }
  1378. static inline void dashenc_delete_media_segments(AVFormatContext *s, OutputStream *os, int remove_count)
  1379. {
  1380. for (int i = 0; i < remove_count; ++i) {
  1381. dashenc_delete_segment_file(s, os->segments[i]->file);
  1382. // Delete the segment regardless of whether the file was successfully deleted
  1383. av_free(os->segments[i]);
  1384. }
  1385. os->nb_segments -= remove_count;
  1386. memmove(os->segments, os->segments + remove_count, os->nb_segments * sizeof(*os->segments));
  1387. }
  1388. static int dash_flush(AVFormatContext *s, int final, int stream)
  1389. {
  1390. DASHContext *c = s->priv_data;
  1391. int i, ret = 0;
  1392. const char *proto = avio_find_protocol_name(s->url);
  1393. int use_rename = proto && !strcmp(proto, "file");
  1394. int cur_flush_segment_index = 0, next_exp_index = -1;
  1395. if (stream >= 0) {
  1396. cur_flush_segment_index = c->streams[stream].segment_index;
  1397. //finding the next segment's expected index, based on the current pts value
  1398. if (c->use_template && !c->use_timeline && c->index_correction &&
  1399. c->streams[stream].last_pts != AV_NOPTS_VALUE &&
  1400. c->streams[stream].first_pts != AV_NOPTS_VALUE) {
  1401. int64_t pts_diff = av_rescale_q(c->streams[stream].last_pts -
  1402. c->streams[stream].first_pts,
  1403. s->streams[stream]->time_base,
  1404. AV_TIME_BASE_Q);
  1405. next_exp_index = (pts_diff / c->seg_duration) + 1;
  1406. }
  1407. }
  1408. for (i = 0; i < s->nb_streams; i++) {
  1409. OutputStream *os = &c->streams[i];
  1410. AVStream *st = s->streams[i];
  1411. int range_length, index_length = 0;
  1412. if (!os->packets_written)
  1413. continue;
  1414. // Flush the single stream that got a keyframe right now.
  1415. // Flush all audio streams as well, in sync with video keyframes,
  1416. // but not the other video streams.
  1417. if (stream >= 0 && i != stream) {
  1418. if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
  1419. continue;
  1420. // Make sure we don't flush audio streams multiple times, when
  1421. // all video streams are flushed one at a time.
  1422. if (c->has_video && os->segment_index > cur_flush_segment_index)
  1423. continue;
  1424. }
  1425. if (!c->single_file) {
  1426. if (os->segment_type == SEGMENT_TYPE_MP4 && !os->written_len)
  1427. write_styp(os->ctx->pb);
  1428. } else {
  1429. snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname, os->initfile);
  1430. }
  1431. ret = flush_dynbuf(c, os, &range_length);
  1432. if (ret < 0)
  1433. break;
  1434. os->packets_written = 0;
  1435. if (c->single_file) {
  1436. find_index_range(s, os->full_path, os->pos, &index_length);
  1437. } else {
  1438. dashenc_io_close(s, &os->out, os->temp_path);
  1439. if (use_rename) {
  1440. ret = avpriv_io_move(os->temp_path, os->full_path);
  1441. if (ret < 0)
  1442. break;
  1443. }
  1444. }
  1445. if (!os->muxer_overhead)
  1446. os->muxer_overhead = ((int64_t) (range_length - os->total_pkt_size) *
  1447. 8 * AV_TIME_BASE) /
  1448. av_rescale_q(os->max_pts - os->start_pts,
  1449. st->time_base, AV_TIME_BASE_Q);
  1450. os->total_pkt_size = 0;
  1451. if (!os->bit_rate) {
  1452. // calculate average bitrate of first segment
  1453. int64_t bitrate = (int64_t) range_length * 8 * AV_TIME_BASE / av_rescale_q(os->max_pts - os->start_pts,
  1454. st->time_base,
  1455. AV_TIME_BASE_Q);
  1456. if (bitrate >= 0)
  1457. os->bit_rate = bitrate;
  1458. }
  1459. add_segment(os, os->filename, os->start_pts, os->max_pts - os->start_pts, os->pos, range_length, index_length, next_exp_index);
  1460. av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, os->full_path);
  1461. os->pos += range_length;
  1462. }
  1463. if (c->window_size) {
  1464. for (i = 0; i < s->nb_streams; i++) {
  1465. OutputStream *os = &c->streams[i];
  1466. int remove_count = os->nb_segments - c->window_size - c->extra_window_size;
  1467. if (remove_count > 0)
  1468. dashenc_delete_media_segments(s, os, remove_count);
  1469. }
  1470. }
  1471. if (final) {
  1472. for (i = 0; i < s->nb_streams; i++) {
  1473. OutputStream *os = &c->streams[i];
  1474. if (os->ctx && os->ctx_inited) {
  1475. int64_t file_size = avio_tell(os->ctx->pb);
  1476. av_write_trailer(os->ctx);
  1477. if (c->global_sidx) {
  1478. int j, start_index, start_number;
  1479. int64_t sidx_size = avio_tell(os->ctx->pb) - file_size;
  1480. get_start_index_number(os, c, &start_index, &start_number);
  1481. if (start_index >= os->nb_segments ||
  1482. os->segment_type != SEGMENT_TYPE_MP4)
  1483. continue;
  1484. os->init_range_length += sidx_size;
  1485. for (j = start_index; j < os->nb_segments; j++) {
  1486. Segment *seg = os->segments[j];
  1487. seg->start_pos += sidx_size;
  1488. }
  1489. }
  1490. }
  1491. }
  1492. }
  1493. if (ret >= 0) {
  1494. if (c->has_video && !final) {
  1495. c->nr_of_streams_flushed++;
  1496. if (c->nr_of_streams_flushed != c->nr_of_streams_to_flush)
  1497. return ret;
  1498. c->nr_of_streams_flushed = 0;
  1499. }
  1500. ret = write_manifest(s, final);
  1501. }
  1502. return ret;
  1503. }
  1504. static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
  1505. {
  1506. DASHContext *c = s->priv_data;
  1507. AVStream *st = s->streams[pkt->stream_index];
  1508. OutputStream *os = &c->streams[pkt->stream_index];
  1509. int64_t seg_end_duration, elapsed_duration;
  1510. int ret;
  1511. ret = update_stream_extradata(s, os, pkt, &st->avg_frame_rate);
  1512. if (ret < 0)
  1513. return ret;
  1514. // Fill in a heuristic guess of the packet duration, if none is available.
  1515. // The mp4 muxer will do something similar (for the last packet in a fragment)
  1516. // if nothing is set (setting it for the other packets doesn't hurt).
  1517. // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
  1518. // invoke its heuristic (this doesn't have to be identical to that algorithm),
  1519. // so that we know the exact timestamps of fragments.
  1520. if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
  1521. pkt->duration = pkt->dts - os->last_dts;
  1522. os->last_dts = pkt->dts;
  1523. // If forcing the stream to start at 0, the mp4 muxer will set the start
  1524. // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
  1525. if (os->first_pts == AV_NOPTS_VALUE &&
  1526. s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
  1527. pkt->pts -= pkt->dts;
  1528. pkt->dts = 0;
  1529. }
  1530. if (os->first_pts == AV_NOPTS_VALUE)
  1531. os->first_pts = pkt->pts;
  1532. os->last_pts = pkt->pts;
  1533. if (!c->availability_start_time[0]) {
  1534. int64_t start_time_us = av_gettime();
  1535. c->start_time_s = start_time_us / 1000000;
  1536. format_date_now(c->availability_start_time,
  1537. sizeof(c->availability_start_time));
  1538. }
  1539. if (!os->availability_time_offset && pkt->duration) {
  1540. int64_t frame_duration = av_rescale_q(pkt->duration, st->time_base,
  1541. AV_TIME_BASE_Q);
  1542. os->availability_time_offset = ((double) c->seg_duration -
  1543. frame_duration) / AV_TIME_BASE;
  1544. }
  1545. if (c->use_template && !c->use_timeline) {
  1546. elapsed_duration = pkt->pts - os->first_pts;
  1547. seg_end_duration = (int64_t) os->segment_index * c->seg_duration;
  1548. } else {
  1549. elapsed_duration = pkt->pts - os->start_pts;
  1550. seg_end_duration = c->seg_duration;
  1551. }
  1552. if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
  1553. pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
  1554. av_compare_ts(elapsed_duration, st->time_base,
  1555. seg_end_duration, AV_TIME_BASE_Q) >= 0) {
  1556. int64_t prev_duration = c->last_duration;
  1557. c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
  1558. st->time_base,
  1559. AV_TIME_BASE_Q);
  1560. c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
  1561. st->time_base,
  1562. AV_TIME_BASE_Q);
  1563. if ((!c->use_timeline || !c->use_template) && prev_duration) {
  1564. if (c->last_duration < prev_duration*9/10 ||
  1565. c->last_duration > prev_duration*11/10) {
  1566. av_log(s, AV_LOG_WARNING,
  1567. "Segment durations differ too much, enable use_timeline "
  1568. "and use_template, or keep a stricter keyframe interval\n");
  1569. }
  1570. }
  1571. if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
  1572. return ret;
  1573. }
  1574. if (!os->packets_written) {
  1575. // If we wrote a previous segment, adjust the start time of the segment
  1576. // to the end of the previous one (which is the same as the mp4 muxer
  1577. // does). This avoids gaps in the timeline.
  1578. if (os->max_pts != AV_NOPTS_VALUE)
  1579. os->start_pts = os->max_pts;
  1580. else
  1581. os->start_pts = pkt->pts;
  1582. }
  1583. if (os->max_pts == AV_NOPTS_VALUE)
  1584. os->max_pts = pkt->pts + pkt->duration;
  1585. else
  1586. os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
  1587. os->packets_written++;
  1588. os->total_pkt_size += pkt->size;
  1589. if ((ret = ff_write_chained(os->ctx, 0, pkt, s, 0)) < 0)
  1590. return ret;
  1591. if (!os->init_range_length)
  1592. flush_init_segment(s, os);
  1593. //open the output context when the first frame of a segment is ready
  1594. if (!c->single_file && os->packets_written == 1) {
  1595. AVDictionary *opts = NULL;
  1596. const char *proto = avio_find_protocol_name(s->url);
  1597. int use_rename = proto && !strcmp(proto, "file");
  1598. os->filename[0] = os->full_path[0] = os->temp_path[0] = '\0';
  1599. ff_dash_fill_tmpl_params(os->filename, sizeof(os->filename),
  1600. os->media_seg_name, pkt->stream_index,
  1601. os->segment_index, os->bit_rate, os->start_pts);
  1602. snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname,
  1603. os->filename);
  1604. snprintf(os->temp_path, sizeof(os->temp_path),
  1605. use_rename ? "%s.tmp" : "%s", os->full_path);
  1606. set_http_options(&opts, c);
  1607. ret = dashenc_io_open(s, &os->out, os->temp_path, &opts);
  1608. av_dict_free(&opts);
  1609. if (ret < 0) {
  1610. return handle_io_open_error(s, ret, os->temp_path);
  1611. }
  1612. if (c->lhls) {
  1613. char *prefetch_url = use_rename ? NULL : os->filename;
  1614. write_hls_media_playlist(os, s, pkt->stream_index, 0, prefetch_url);
  1615. }
  1616. }
  1617. //write out the data immediately in streaming mode
  1618. if (c->streaming && os->segment_type == SEGMENT_TYPE_MP4) {
  1619. int len = 0;
  1620. uint8_t *buf = NULL;
  1621. if (!os->written_len)
  1622. write_styp(os->ctx->pb);
  1623. avio_flush(os->ctx->pb);
  1624. len = avio_get_dyn_buf (os->ctx->pb, &buf);
  1625. if (os->out) {
  1626. avio_write(os->out, buf + os->written_len, len - os->written_len);
  1627. avio_flush(os->out);
  1628. }
  1629. os->written_len = len;
  1630. }
  1631. return ret;
  1632. }
  1633. static int dash_write_trailer(AVFormatContext *s)
  1634. {
  1635. DASHContext *c = s->priv_data;
  1636. int i;
  1637. if (s->nb_streams > 0) {
  1638. OutputStream *os = &c->streams[0];
  1639. // If no segments have been written so far, try to do a crude
  1640. // guess of the segment duration
  1641. if (!c->last_duration)
  1642. c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
  1643. s->streams[0]->time_base,
  1644. AV_TIME_BASE_Q);
  1645. c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
  1646. s->streams[0]->time_base,
  1647. AV_TIME_BASE_Q);
  1648. }
  1649. dash_flush(s, 1, -1);
  1650. if (c->remove_at_exit) {
  1651. for (i = 0; i < s->nb_streams; ++i) {
  1652. OutputStream *os = &c->streams[i];
  1653. dashenc_delete_media_segments(s, os, os->nb_segments);
  1654. dashenc_delete_segment_file(s, os->initfile);
  1655. if (c->hls_playlist && os->segment_type == SEGMENT_TYPE_MP4) {
  1656. char filename[1024];
  1657. get_hls_playlist_name(filename, sizeof(filename), c->dirname, i);
  1658. dashenc_delete_file(s, filename);
  1659. }
  1660. }
  1661. dashenc_delete_file(s, s->url);
  1662. if (c->hls_playlist && c->master_playlist_created) {
  1663. char filename[1024];
  1664. snprintf(filename, sizeof(filename), "%smaster.m3u8", c->dirname);
  1665. dashenc_delete_file(s, filename);
  1666. }
  1667. }
  1668. return 0;
  1669. }
  1670. static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
  1671. {
  1672. DASHContext *c = s->priv_data;
  1673. OutputStream *os = &c->streams[avpkt->stream_index];
  1674. AVFormatContext *oc = os->ctx;
  1675. if (oc->oformat->check_bitstream) {
  1676. int ret;
  1677. AVPacket pkt = *avpkt;
  1678. pkt.stream_index = 0;
  1679. ret = oc->oformat->check_bitstream(oc, &pkt);
  1680. if (ret == 1) {
  1681. AVStream *st = s->streams[avpkt->stream_index];
  1682. AVStream *ost = oc->streams[0];
  1683. st->internal->bsfcs = ost->internal->bsfcs;
  1684. st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
  1685. ost->internal->bsfcs = NULL;
  1686. ost->internal->nb_bsfcs = 0;
  1687. }
  1688. return ret;
  1689. }
  1690. return 1;
  1691. }
  1692. #define OFFSET(x) offsetof(DASHContext, x)
  1693. #define E AV_OPT_FLAG_ENCODING_PARAM
  1694. static const AVOption options[] = {
  1695. { "adaptation_sets", "Adaptation sets. Syntax: id=0,streams=0,1,2 id=1,streams=3,4 and so on", OFFSET(adaptation_sets), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
  1696. { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
  1697. { "extra_window_size", "number of segments kept outside of the manifest before removing from disk", OFFSET(extra_window_size), AV_OPT_TYPE_INT, { .i64 = 5 }, 0, INT_MAX, E },
  1698. #if FF_API_DASH_MIN_SEG_DURATION
  1699. { "min_seg_duration", "minimum segment duration (in microseconds) (will be deprecated)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT, { .i64 = 5000000 }, 0, INT_MAX, E },
  1700. #endif
  1701. { "seg_duration", "segment duration (in seconds, fractional value can be set)", OFFSET(seg_duration), AV_OPT_TYPE_DURATION, { .i64 = 5000000 }, 0, INT_MAX, E },
  1702. { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
  1703. { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
  1704. { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
  1705. { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
  1706. { "single_file_name", "DASH-templated name to be used for baseURL. Implies storing all segments in one file, accessed using byte ranges", OFFSET(single_file_name), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
  1707. { "init_seg_name", "DASH-templated name to used for the initialization segment", OFFSET(init_seg_name), AV_OPT_TYPE_STRING, {.str = "init-stream$RepresentationID$.$ext$"}, 0, 0, E },
  1708. { "media_seg_name", "DASH-templated name to used for the media segments", OFFSET(media_seg_name), AV_OPT_TYPE_STRING, {.str = "chunk-stream$RepresentationID$-$Number%05d$.$ext$"}, 0, 0, E },
  1709. { "utc_timing_url", "URL of the page that will return the UTC timestamp in ISO format", OFFSET(utc_timing_url), AV_OPT_TYPE_STRING, { 0 }, 0, 0, E },
  1710. { "method", "set the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  1711. { "http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
  1712. { "http_persistent", "Use persistent HTTP connections", OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
  1713. { "hls_playlist", "Generate HLS playlist files(master.m3u8, media_%d.m3u8)", OFFSET(hls_playlist), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
  1714. { "streaming", "Enable/Disable streaming mode of output. Each frame will be moof fragment", OFFSET(streaming), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
  1715. { "timeout", "set timeout for socket I/O operations", OFFSET(timeout), AV_OPT_TYPE_DURATION, { .i64 = -1 }, -1, INT_MAX, .flags = E },
  1716. { "index_correction", "Enable/Disable segment index correction logic", OFFSET(index_correction), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
  1717. { "format_options","set list of options for the container format (mp4/webm) used for dash", OFFSET(format_options_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
  1718. { "global_sidx", "Write global SIDX atom. Applicable only for single file, mp4 output, non-streaming mode", OFFSET(global_sidx), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
  1719. { "dash_segment_type", "set dash segment files type", OFFSET(segment_type_option), AV_OPT_TYPE_INT, {.i64 = SEGMENT_TYPE_AUTO }, 0, SEGMENT_TYPE_NB - 1, E, "segment_type"},
  1720. { "auto", "select segment file format based on codec", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_AUTO }, 0, UINT_MAX, E, "segment_type"},
  1721. { "mp4", "make segment file in ISOBMFF format", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_MP4 }, 0, UINT_MAX, E, "segment_type"},
  1722. { "webm", "make segment file in WebM format", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_WEBM }, 0, UINT_MAX, E, "segment_type"},
  1723. { "ignore_io_errors", "Ignore IO errors during open and write. Useful for long-duration runs with network output", OFFSET(ignore_io_errors), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
  1724. { "lhls", "Enable Low-latency HLS(Experimental). Adds #EXT-X-PREFETCH tag with current segment's URI", OFFSET(lhls), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
  1725. { "master_m3u8_publish_rate", "Publish master playlist every after this many segment intervals", OFFSET(master_publish_rate), AV_OPT_TYPE_INT, {.i64 = 0}, 0, UINT_MAX, E},
  1726. { NULL },
  1727. };
  1728. static const AVClass dash_class = {
  1729. .class_name = "dash muxer",
  1730. .item_name = av_default_item_name,
  1731. .option = options,
  1732. .version = LIBAVUTIL_VERSION_INT,
  1733. };
  1734. AVOutputFormat ff_dash_muxer = {
  1735. .name = "dash",
  1736. .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
  1737. .extensions = "mpd",
  1738. .priv_data_size = sizeof(DASHContext),
  1739. .audio_codec = AV_CODEC_ID_AAC,
  1740. .video_codec = AV_CODEC_ID_H264,
  1741. .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
  1742. .init = dash_init,
  1743. .write_header = dash_write_header,
  1744. .write_packet = dash_write_packet,
  1745. .write_trailer = dash_write_trailer,
  1746. .deinit = dash_free,
  1747. .check_bitstream = dash_check_bitstream,
  1748. .priv_class = &dash_class,
  1749. };