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.

2399 lines
93KB

  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/parseutils.h"
  33. #include "libavutil/rational.h"
  34. #include "libavutil/time.h"
  35. #include "libavutil/time_internal.h"
  36. #include "av1.h"
  37. #include "avc.h"
  38. #include "avformat.h"
  39. #include "avio_internal.h"
  40. #include "hlsplaylist.h"
  41. #if CONFIG_HTTP_PROTOCOL
  42. #include "http.h"
  43. #endif
  44. #include "internal.h"
  45. #include "isom.h"
  46. #include "os_support.h"
  47. #include "url.h"
  48. #include "vpcc.h"
  49. #include "dash.h"
  50. typedef enum {
  51. SEGMENT_TYPE_AUTO = 0,
  52. SEGMENT_TYPE_MP4,
  53. SEGMENT_TYPE_WEBM,
  54. SEGMENT_TYPE_NB
  55. } SegmentType;
  56. enum {
  57. FRAG_TYPE_NONE = 0,
  58. FRAG_TYPE_EVERY_FRAME,
  59. FRAG_TYPE_DURATION,
  60. FRAG_TYPE_PFRAMES,
  61. FRAG_TYPE_NB
  62. };
  63. #define MPD_PROFILE_DASH 1
  64. #define MPD_PROFILE_DVB 2
  65. typedef struct Segment {
  66. char file[1024];
  67. int64_t start_pos;
  68. int range_length, index_length;
  69. int64_t time;
  70. double prog_date_time;
  71. int64_t duration;
  72. int n;
  73. } Segment;
  74. typedef struct AdaptationSet {
  75. int id;
  76. char *descriptor;
  77. int64_t seg_duration;
  78. int64_t frag_duration;
  79. int frag_type;
  80. enum AVMediaType media_type;
  81. AVDictionary *metadata;
  82. AVRational min_frame_rate, max_frame_rate;
  83. int ambiguous_frame_rate;
  84. int64_t max_frag_duration;
  85. int max_width, max_height;
  86. int nb_streams;
  87. AVRational par;
  88. int trick_idx;
  89. } AdaptationSet;
  90. typedef struct OutputStream {
  91. AVFormatContext *ctx;
  92. int ctx_inited, as_idx;
  93. AVIOContext *out;
  94. AVCodecParserContext *parser;
  95. AVCodecContext *parser_avctx;
  96. int packets_written;
  97. char initfile[1024];
  98. int64_t init_start_pos, pos;
  99. int init_range_length;
  100. int nb_segments, segments_size, segment_index;
  101. int64_t seg_duration;
  102. int64_t frag_duration;
  103. int64_t last_duration;
  104. Segment **segments;
  105. int64_t first_pts, start_pts, max_pts;
  106. int64_t last_dts, last_pts;
  107. int last_flags;
  108. int bit_rate;
  109. SegmentType segment_type; /* segment type selected for this particular stream */
  110. const char *format_name;
  111. const char *extension_name;
  112. const char *single_file_name; /* file names selected for this particular stream */
  113. const char *init_seg_name;
  114. const char *media_seg_name;
  115. char codec_str[100];
  116. int written_len;
  117. char filename[1024];
  118. char full_path[1024];
  119. char temp_path[1024];
  120. double availability_time_offset;
  121. AVProducerReferenceTime producer_reference_time;
  122. char producer_reference_time_str[100];
  123. int total_pkt_size;
  124. int64_t total_pkt_duration;
  125. int muxer_overhead;
  126. int frag_type;
  127. int64_t gop_size;
  128. AVRational sar;
  129. int coding_dependency;
  130. } OutputStream;
  131. typedef struct DASHContext {
  132. const AVClass *class; /* Class for private options. */
  133. char *adaptation_sets;
  134. AdaptationSet *as;
  135. int nb_as;
  136. int window_size;
  137. int extra_window_size;
  138. #if FF_API_DASH_MIN_SEG_DURATION
  139. int min_seg_duration;
  140. #endif
  141. int64_t seg_duration;
  142. int64_t frag_duration;
  143. int remove_at_exit;
  144. int use_template;
  145. int use_timeline;
  146. int single_file;
  147. OutputStream *streams;
  148. int has_video;
  149. int64_t last_duration;
  150. int64_t total_duration;
  151. char availability_start_time[100];
  152. time_t start_time_s;
  153. int64_t presentation_time_offset;
  154. char dirname[1024];
  155. const char *single_file_name; /* file names as specified in options */
  156. const char *init_seg_name;
  157. const char *media_seg_name;
  158. const char *utc_timing_url;
  159. const char *method;
  160. const char *user_agent;
  161. AVDictionary *http_opts;
  162. int hls_playlist;
  163. int http_persistent;
  164. int master_playlist_created;
  165. AVIOContext *mpd_out;
  166. AVIOContext *m3u8_out;
  167. int streaming;
  168. int64_t timeout;
  169. int index_correction;
  170. AVDictionary *format_options;
  171. int global_sidx;
  172. SegmentType segment_type_option; /* segment type as specified in options */
  173. int ignore_io_errors;
  174. int lhls;
  175. int ldash;
  176. int master_publish_rate;
  177. int nr_of_streams_to_flush;
  178. int nr_of_streams_flushed;
  179. int frag_type;
  180. int write_prft;
  181. int64_t max_gop_size;
  182. int64_t max_segment_duration;
  183. int profile;
  184. int64_t target_latency;
  185. int target_latency_refid;
  186. AVRational min_playback_rate;
  187. AVRational max_playback_rate;
  188. } DASHContext;
  189. static struct codec_string {
  190. int id;
  191. const char *str;
  192. } codecs[] = {
  193. { AV_CODEC_ID_VP8, "vp8" },
  194. { AV_CODEC_ID_VP9, "vp9" },
  195. { AV_CODEC_ID_VORBIS, "vorbis" },
  196. { AV_CODEC_ID_OPUS, "opus" },
  197. { AV_CODEC_ID_FLAC, "flac" },
  198. { 0, NULL }
  199. };
  200. static struct format_string {
  201. SegmentType segment_type;
  202. const char *str;
  203. } formats[] = {
  204. { SEGMENT_TYPE_AUTO, "auto" },
  205. { SEGMENT_TYPE_MP4, "mp4" },
  206. { SEGMENT_TYPE_WEBM, "webm" },
  207. { 0, NULL }
  208. };
  209. static int dashenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
  210. AVDictionary **options) {
  211. DASHContext *c = s->priv_data;
  212. int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
  213. int err = AVERROR_MUXER_NOT_FOUND;
  214. if (!*pb || !http_base_proto || !c->http_persistent) {
  215. err = s->io_open(s, pb, filename, AVIO_FLAG_WRITE, options);
  216. #if CONFIG_HTTP_PROTOCOL
  217. } else {
  218. URLContext *http_url_context = ffio_geturlcontext(*pb);
  219. av_assert0(http_url_context);
  220. err = ff_http_do_new_request(http_url_context, filename);
  221. if (err < 0)
  222. ff_format_io_close(s, pb);
  223. #endif
  224. }
  225. return err;
  226. }
  227. static void dashenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename) {
  228. DASHContext *c = s->priv_data;
  229. int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
  230. if (!*pb)
  231. return;
  232. if (!http_base_proto || !c->http_persistent) {
  233. ff_format_io_close(s, pb);
  234. #if CONFIG_HTTP_PROTOCOL
  235. } else {
  236. URLContext *http_url_context = ffio_geturlcontext(*pb);
  237. av_assert0(http_url_context);
  238. avio_flush(*pb);
  239. ffurl_shutdown(http_url_context, AVIO_FLAG_WRITE);
  240. #endif
  241. }
  242. }
  243. static const char *get_format_str(SegmentType segment_type) {
  244. int i;
  245. for (i = 0; i < SEGMENT_TYPE_NB; i++)
  246. if (formats[i].segment_type == segment_type)
  247. return formats[i].str;
  248. return NULL;
  249. }
  250. static const char *get_extension_str(SegmentType type, int single_file)
  251. {
  252. switch (type) {
  253. case SEGMENT_TYPE_MP4: return single_file ? "mp4" : "m4s";
  254. case SEGMENT_TYPE_WEBM: return "webm";
  255. default: return NULL;
  256. }
  257. }
  258. static int handle_io_open_error(AVFormatContext *s, int err, char *url) {
  259. DASHContext *c = s->priv_data;
  260. char errbuf[AV_ERROR_MAX_STRING_SIZE];
  261. av_strerror(err, errbuf, sizeof(errbuf));
  262. av_log(s, c->ignore_io_errors ? AV_LOG_WARNING : AV_LOG_ERROR,
  263. "Unable to open %s for writing: %s\n", url, errbuf);
  264. return c->ignore_io_errors ? 0 : err;
  265. }
  266. static inline SegmentType select_segment_type(SegmentType segment_type, enum AVCodecID codec_id)
  267. {
  268. if (segment_type == SEGMENT_TYPE_AUTO) {
  269. if (codec_id == AV_CODEC_ID_OPUS || codec_id == AV_CODEC_ID_VORBIS ||
  270. codec_id == AV_CODEC_ID_VP8 || codec_id == AV_CODEC_ID_VP9) {
  271. segment_type = SEGMENT_TYPE_WEBM;
  272. } else {
  273. segment_type = SEGMENT_TYPE_MP4;
  274. }
  275. }
  276. return segment_type;
  277. }
  278. static int init_segment_types(AVFormatContext *s)
  279. {
  280. DASHContext *c = s->priv_data;
  281. int has_mp4_streams = 0;
  282. for (int i = 0; i < s->nb_streams; ++i) {
  283. OutputStream *os = &c->streams[i];
  284. SegmentType segment_type = select_segment_type(
  285. c->segment_type_option, s->streams[i]->codecpar->codec_id);
  286. os->segment_type = segment_type;
  287. os->format_name = get_format_str(segment_type);
  288. if (!os->format_name) {
  289. av_log(s, AV_LOG_ERROR, "Could not select DASH segment type for stream %d\n", i);
  290. return AVERROR_MUXER_NOT_FOUND;
  291. }
  292. os->extension_name = get_extension_str(segment_type, c->single_file);
  293. if (!os->extension_name) {
  294. av_log(s, AV_LOG_ERROR, "Could not get extension type for stream %d\n", i);
  295. return AVERROR_MUXER_NOT_FOUND;
  296. }
  297. has_mp4_streams |= segment_type == SEGMENT_TYPE_MP4;
  298. }
  299. if (c->hls_playlist && !has_mp4_streams) {
  300. av_log(s, AV_LOG_WARNING, "No mp4 streams, disabling HLS manifest generation\n");
  301. c->hls_playlist = 0;
  302. }
  303. return 0;
  304. }
  305. static int check_file_extension(const char *filename, const char *extension) {
  306. char *dot;
  307. if (!filename || !extension)
  308. return -1;
  309. dot = strrchr(filename, '.');
  310. if (dot && !strcmp(dot + 1, extension))
  311. return 0;
  312. return -1;
  313. }
  314. static void set_vp9_codec_str(AVFormatContext *s, AVCodecParameters *par,
  315. AVRational *frame_rate, char *str, int size) {
  316. VPCC vpcc;
  317. int ret = ff_isom_get_vpcc_features(s, par, frame_rate, &vpcc);
  318. if (ret == 0) {
  319. av_strlcatf(str, size, "vp09.%02d.%02d.%02d",
  320. vpcc.profile, vpcc.level, vpcc.bitdepth);
  321. } else {
  322. // Default to just vp9 in case of error while finding out profile or level
  323. av_log(s, AV_LOG_WARNING, "Could not find VP9 profile and/or level\n");
  324. av_strlcpy(str, "vp9", size);
  325. }
  326. return;
  327. }
  328. static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
  329. AVRational *frame_rate, char *str, int size)
  330. {
  331. const AVCodecTag *tags[2] = { NULL, NULL };
  332. uint32_t tag;
  333. int i;
  334. // common Webm codecs are not part of RFC 6381
  335. for (i = 0; codecs[i].id; i++)
  336. if (codecs[i].id == par->codec_id) {
  337. if (codecs[i].id == AV_CODEC_ID_VP9) {
  338. set_vp9_codec_str(s, par, frame_rate, str, size);
  339. } else {
  340. av_strlcpy(str, codecs[i].str, size);
  341. }
  342. return;
  343. }
  344. // for codecs part of RFC 6381
  345. if (par->codec_type == AVMEDIA_TYPE_VIDEO)
  346. tags[0] = ff_codec_movvideo_tags;
  347. else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
  348. tags[0] = ff_codec_movaudio_tags;
  349. else
  350. return;
  351. tag = par->codec_tag;
  352. if (!tag)
  353. tag = av_codec_get_tag(tags, par->codec_id);
  354. if (!tag)
  355. return;
  356. if (size < 5)
  357. return;
  358. AV_WL32(str, tag);
  359. str[4] = '\0';
  360. if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
  361. uint32_t oti;
  362. tags[0] = ff_mp4_obj_type;
  363. oti = av_codec_get_tag(tags, par->codec_id);
  364. if (oti)
  365. av_strlcatf(str, size, ".%02"PRIx32, oti);
  366. else
  367. return;
  368. if (tag == MKTAG('m', 'p', '4', 'a')) {
  369. if (par->extradata_size >= 2) {
  370. int aot = par->extradata[0] >> 3;
  371. if (aot == 31)
  372. aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
  373. av_strlcatf(str, size, ".%d", aot);
  374. }
  375. } else if (tag == MKTAG('m', 'p', '4', 'v')) {
  376. // Unimplemented, should output ProfileLevelIndication as a decimal number
  377. av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
  378. }
  379. } else if (!strcmp(str, "avc1")) {
  380. uint8_t *tmpbuf = NULL;
  381. uint8_t *extradata = par->extradata;
  382. int extradata_size = par->extradata_size;
  383. if (!extradata_size)
  384. return;
  385. if (extradata[0] != 1) {
  386. AVIOContext *pb;
  387. if (avio_open_dyn_buf(&pb) < 0)
  388. return;
  389. if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
  390. ffio_free_dyn_buf(&pb);
  391. return;
  392. }
  393. extradata_size = avio_close_dyn_buf(pb, &extradata);
  394. tmpbuf = extradata;
  395. }
  396. if (extradata_size >= 4)
  397. av_strlcatf(str, size, ".%02x%02x%02x",
  398. extradata[1], extradata[2], extradata[3]);
  399. av_free(tmpbuf);
  400. } else if (!strcmp(str, "av01")) {
  401. AV1SequenceParameters seq;
  402. if (!par->extradata_size)
  403. return;
  404. if (ff_av1_parse_seq_header(&seq, par->extradata, par->extradata_size) < 0)
  405. return;
  406. av_strlcatf(str, size, ".%01u.%02u%s.%02u",
  407. seq.profile, seq.level, seq.tier ? "H" : "M", seq.bitdepth);
  408. if (seq.color_description_present_flag)
  409. av_strlcatf(str, size, ".%01u.%01u%01u%01u.%02u.%02u.%02u.%01u",
  410. seq.monochrome,
  411. seq.chroma_subsampling_x, seq.chroma_subsampling_y, seq.chroma_sample_position,
  412. seq.color_primaries, seq.transfer_characteristics, seq.matrix_coefficients,
  413. seq.color_range);
  414. }
  415. }
  416. static int flush_dynbuf(DASHContext *c, OutputStream *os, int *range_length)
  417. {
  418. uint8_t *buffer;
  419. if (!os->ctx->pb) {
  420. return AVERROR(EINVAL);
  421. }
  422. // flush
  423. av_write_frame(os->ctx, NULL);
  424. avio_flush(os->ctx->pb);
  425. if (!c->single_file) {
  426. // write out to file
  427. *range_length = avio_close_dyn_buf(os->ctx->pb, &buffer);
  428. os->ctx->pb = NULL;
  429. if (os->out)
  430. avio_write(os->out, buffer + os->written_len, *range_length - os->written_len);
  431. os->written_len = 0;
  432. av_free(buffer);
  433. // re-open buffer
  434. return avio_open_dyn_buf(&os->ctx->pb);
  435. } else {
  436. *range_length = avio_tell(os->ctx->pb) - os->pos;
  437. return 0;
  438. }
  439. }
  440. static void set_http_options(AVDictionary **options, DASHContext *c)
  441. {
  442. if (c->method)
  443. av_dict_set(options, "method", c->method, 0);
  444. av_dict_copy(options, c->http_opts, 0);
  445. if (c->user_agent)
  446. av_dict_set(options, "user_agent", c->user_agent, 0);
  447. if (c->http_persistent)
  448. av_dict_set_int(options, "multiple_requests", 1, 0);
  449. if (c->timeout >= 0)
  450. av_dict_set_int(options, "timeout", c->timeout, 0);
  451. }
  452. static void get_hls_playlist_name(char *playlist_name, int string_size,
  453. const char *base_url, int id) {
  454. if (base_url)
  455. snprintf(playlist_name, string_size, "%smedia_%d.m3u8", base_url, id);
  456. else
  457. snprintf(playlist_name, string_size, "media_%d.m3u8", id);
  458. }
  459. static void get_start_index_number(OutputStream *os, DASHContext *c,
  460. int *start_index, int *start_number) {
  461. *start_index = 0;
  462. *start_number = 1;
  463. if (c->window_size) {
  464. *start_index = FFMAX(os->nb_segments - c->window_size, 0);
  465. *start_number = FFMAX(os->segment_index - c->window_size, 1);
  466. }
  467. }
  468. static void write_hls_media_playlist(OutputStream *os, AVFormatContext *s,
  469. int representation_id, int final,
  470. char *prefetch_url) {
  471. DASHContext *c = s->priv_data;
  472. int timescale = os->ctx->streams[0]->time_base.den;
  473. char temp_filename_hls[1024];
  474. char filename_hls[1024];
  475. AVDictionary *http_opts = NULL;
  476. int target_duration = 0;
  477. int ret = 0;
  478. const char *proto = avio_find_protocol_name(c->dirname);
  479. int use_rename = proto && !strcmp(proto, "file");
  480. int i, start_index, start_number;
  481. double prog_date_time = 0;
  482. get_start_index_number(os, c, &start_index, &start_number);
  483. if (!c->hls_playlist || start_index >= os->nb_segments ||
  484. os->segment_type != SEGMENT_TYPE_MP4)
  485. return;
  486. get_hls_playlist_name(filename_hls, sizeof(filename_hls),
  487. c->dirname, representation_id);
  488. snprintf(temp_filename_hls, sizeof(temp_filename_hls), use_rename ? "%s.tmp" : "%s", filename_hls);
  489. set_http_options(&http_opts, c);
  490. ret = dashenc_io_open(s, &c->m3u8_out, temp_filename_hls, &http_opts);
  491. av_dict_free(&http_opts);
  492. if (ret < 0) {
  493. handle_io_open_error(s, ret, temp_filename_hls);
  494. return;
  495. }
  496. for (i = start_index; i < os->nb_segments; i++) {
  497. Segment *seg = os->segments[i];
  498. double duration = (double) seg->duration / timescale;
  499. if (target_duration <= duration)
  500. target_duration = lrint(duration);
  501. }
  502. ff_hls_write_playlist_header(c->m3u8_out, 6, -1, target_duration,
  503. start_number, PLAYLIST_TYPE_NONE, 0);
  504. ff_hls_write_init_file(c->m3u8_out, os->initfile, c->single_file,
  505. os->init_range_length, os->init_start_pos);
  506. for (i = start_index; i < os->nb_segments; i++) {
  507. Segment *seg = os->segments[i];
  508. if (prog_date_time == 0) {
  509. if (os->nb_segments == 1)
  510. prog_date_time = c->start_time_s;
  511. else
  512. prog_date_time = seg->prog_date_time;
  513. }
  514. seg->prog_date_time = prog_date_time;
  515. ret = ff_hls_write_file_entry(c->m3u8_out, 0, c->single_file,
  516. (double) seg->duration / timescale, 0,
  517. seg->range_length, seg->start_pos, NULL,
  518. c->single_file ? os->initfile : seg->file,
  519. &prog_date_time, 0, 0, 0);
  520. if (ret < 0) {
  521. av_log(os->ctx, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
  522. }
  523. }
  524. if (prefetch_url)
  525. avio_printf(c->m3u8_out, "#EXT-X-PREFETCH:%s\n", prefetch_url);
  526. if (final)
  527. ff_hls_write_end_list(c->m3u8_out);
  528. dashenc_io_close(s, &c->m3u8_out, temp_filename_hls);
  529. if (use_rename)
  530. ff_rename(temp_filename_hls, filename_hls, os->ctx);
  531. }
  532. static int flush_init_segment(AVFormatContext *s, OutputStream *os)
  533. {
  534. DASHContext *c = s->priv_data;
  535. int ret, range_length;
  536. ret = flush_dynbuf(c, os, &range_length);
  537. if (ret < 0)
  538. return ret;
  539. os->pos = os->init_range_length = range_length;
  540. if (!c->single_file) {
  541. char filename[1024];
  542. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
  543. dashenc_io_close(s, &os->out, filename);
  544. }
  545. return 0;
  546. }
  547. static void dash_free(AVFormatContext *s)
  548. {
  549. DASHContext *c = s->priv_data;
  550. int i, j;
  551. if (c->as) {
  552. for (i = 0; i < c->nb_as; i++) {
  553. av_dict_free(&c->as[i].metadata);
  554. av_freep(&c->as[i].descriptor);
  555. }
  556. av_freep(&c->as);
  557. c->nb_as = 0;
  558. }
  559. if (!c->streams)
  560. return;
  561. for (i = 0; i < s->nb_streams; i++) {
  562. OutputStream *os = &c->streams[i];
  563. if (os->ctx && os->ctx->pb) {
  564. if (!c->single_file)
  565. ffio_free_dyn_buf(&os->ctx->pb);
  566. else
  567. avio_close(os->ctx->pb);
  568. }
  569. ff_format_io_close(s, &os->out);
  570. avformat_free_context(os->ctx);
  571. avcodec_free_context(&os->parser_avctx);
  572. av_parser_close(os->parser);
  573. for (j = 0; j < os->nb_segments; j++)
  574. av_free(os->segments[j]);
  575. av_free(os->segments);
  576. av_freep(&os->single_file_name);
  577. av_freep(&os->init_seg_name);
  578. av_freep(&os->media_seg_name);
  579. }
  580. av_freep(&c->streams);
  581. ff_format_io_close(s, &c->mpd_out);
  582. ff_format_io_close(s, &c->m3u8_out);
  583. }
  584. static void output_segment_list(OutputStream *os, AVIOContext *out, AVFormatContext *s,
  585. int representation_id, int final)
  586. {
  587. DASHContext *c = s->priv_data;
  588. int i, start_index, start_number;
  589. get_start_index_number(os, c, &start_index, &start_number);
  590. if (c->use_template) {
  591. int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
  592. avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
  593. if (!c->use_timeline) {
  594. avio_printf(out, "duration=\"%"PRId64"\" ", os->seg_duration);
  595. if (c->streaming && os->availability_time_offset)
  596. avio_printf(out, "availabilityTimeOffset=\"%.3f\" ",
  597. os->availability_time_offset);
  598. }
  599. if (c->streaming && os->availability_time_offset && !final)
  600. avio_printf(out, "availabilityTimeComplete=\"false\" ");
  601. avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\"", os->init_seg_name, os->media_seg_name, c->use_timeline ? start_number : 1);
  602. if (c->presentation_time_offset)
  603. avio_printf(out, " presentationTimeOffset=\"%"PRId64"\"", c->presentation_time_offset);
  604. avio_printf(out, ">\n");
  605. if (c->use_timeline) {
  606. int64_t cur_time = 0;
  607. avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
  608. for (i = start_index; i < os->nb_segments; ) {
  609. Segment *seg = os->segments[i];
  610. int repeat = 0;
  611. avio_printf(out, "\t\t\t\t\t\t<S ");
  612. if (i == start_index || seg->time != cur_time) {
  613. cur_time = seg->time;
  614. avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
  615. }
  616. avio_printf(out, "d=\"%"PRId64"\" ", seg->duration);
  617. while (i + repeat + 1 < os->nb_segments &&
  618. os->segments[i + repeat + 1]->duration == seg->duration &&
  619. os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
  620. repeat++;
  621. if (repeat > 0)
  622. avio_printf(out, "r=\"%d\" ", repeat);
  623. avio_printf(out, "/>\n");
  624. i += 1 + repeat;
  625. cur_time += (1 + repeat) * seg->duration;
  626. }
  627. avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
  628. }
  629. avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
  630. } else if (c->single_file) {
  631. avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
  632. avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, FFMIN(os->seg_duration, os->last_duration), start_number);
  633. 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);
  634. for (i = start_index; i < os->nb_segments; i++) {
  635. Segment *seg = os->segments[i];
  636. avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
  637. if (seg->index_length)
  638. avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
  639. avio_printf(out, "/>\n");
  640. }
  641. avio_printf(out, "\t\t\t\t</SegmentList>\n");
  642. } else {
  643. avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, FFMIN(os->seg_duration, os->last_duration), start_number);
  644. avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
  645. for (i = start_index; i < os->nb_segments; i++) {
  646. Segment *seg = os->segments[i];
  647. avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
  648. }
  649. avio_printf(out, "\t\t\t\t</SegmentList>\n");
  650. }
  651. if (!c->lhls || final) {
  652. write_hls_media_playlist(os, s, representation_id, final, NULL);
  653. }
  654. }
  655. static char *xmlescape(const char *str) {
  656. int outlen = strlen(str)*3/2 + 6;
  657. char *out = av_realloc(NULL, outlen + 1);
  658. int pos = 0;
  659. if (!out)
  660. return NULL;
  661. for (; *str; str++) {
  662. if (pos + 6 > outlen) {
  663. char *tmp;
  664. outlen = 2 * outlen + 6;
  665. tmp = av_realloc(out, outlen + 1);
  666. if (!tmp) {
  667. av_free(out);
  668. return NULL;
  669. }
  670. out = tmp;
  671. }
  672. if (*str == '&') {
  673. memcpy(&out[pos], "&amp;", 5);
  674. pos += 5;
  675. } else if (*str == '<') {
  676. memcpy(&out[pos], "&lt;", 4);
  677. pos += 4;
  678. } else if (*str == '>') {
  679. memcpy(&out[pos], "&gt;", 4);
  680. pos += 4;
  681. } else if (*str == '\'') {
  682. memcpy(&out[pos], "&apos;", 6);
  683. pos += 6;
  684. } else if (*str == '\"') {
  685. memcpy(&out[pos], "&quot;", 6);
  686. pos += 6;
  687. } else {
  688. out[pos++] = *str;
  689. }
  690. }
  691. out[pos] = '\0';
  692. return out;
  693. }
  694. static void write_time(AVIOContext *out, int64_t time)
  695. {
  696. int seconds = time / AV_TIME_BASE;
  697. int fractions = time % AV_TIME_BASE;
  698. int minutes = seconds / 60;
  699. int hours = minutes / 60;
  700. seconds %= 60;
  701. minutes %= 60;
  702. avio_printf(out, "PT");
  703. if (hours)
  704. avio_printf(out, "%dH", hours);
  705. if (hours || minutes)
  706. avio_printf(out, "%dM", minutes);
  707. avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
  708. }
  709. static void format_date(char *buf, int size, int64_t time_us)
  710. {
  711. struct tm *ptm, tmbuf;
  712. int64_t time_ms = time_us / 1000;
  713. const time_t time_s = time_ms / 1000;
  714. int millisec = time_ms - (time_s * 1000);
  715. ptm = gmtime_r(&time_s, &tmbuf);
  716. if (ptm) {
  717. int len;
  718. if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%S", ptm)) {
  719. buf[0] = '\0';
  720. return;
  721. }
  722. len = strlen(buf);
  723. snprintf(buf + len, size - len, ".%03dZ", millisec);
  724. }
  725. }
  726. static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index,
  727. int final)
  728. {
  729. DASHContext *c = s->priv_data;
  730. AdaptationSet *as = &c->as[as_index];
  731. AVDictionaryEntry *lang, *role;
  732. int i;
  733. avio_printf(out, "\t\t<AdaptationSet id=\"%d\" contentType=\"%s\" startWithSAP=\"1\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
  734. as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
  735. 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)
  736. avio_printf(out, " maxFrameRate=\"%d/%d\"", as->max_frame_rate.num, as->max_frame_rate.den);
  737. else 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))
  738. avio_printf(out, " frameRate=\"%d/%d\"", as->max_frame_rate.num, as->max_frame_rate.den);
  739. if (as->media_type == AVMEDIA_TYPE_VIDEO) {
  740. avio_printf(out, " maxWidth=\"%d\" maxHeight=\"%d\"", as->max_width, as->max_height);
  741. avio_printf(out, " par=\"%d:%d\"", as->par.num, as->par.den);
  742. }
  743. lang = av_dict_get(as->metadata, "language", NULL, 0);
  744. if (lang)
  745. avio_printf(out, " lang=\"%s\"", lang->value);
  746. avio_printf(out, ">\n");
  747. if (!final && c->ldash && as->max_frag_duration && !(c->profile & MPD_PROFILE_DVB))
  748. avio_printf(out, "\t\t\t<Resync dT=\"%"PRId64"\" type=\"0\"/>\n", as->max_frag_duration);
  749. if (as->trick_idx >= 0)
  750. avio_printf(out, "\t\t\t<EssentialProperty id=\"%d\" schemeIdUri=\"http://dashif.org/guidelines/trickmode\" value=\"%d\"/>\n", as->id, as->trick_idx);
  751. role = av_dict_get(as->metadata, "role", NULL, 0);
  752. if (role)
  753. avio_printf(out, "\t\t\t<Role schemeIdUri=\"urn:mpeg:dash:role:2011\" value=\"%s\"/>\n", role->value);
  754. if (as->descriptor)
  755. avio_printf(out, "\t\t\t%s\n", as->descriptor);
  756. for (i = 0; i < s->nb_streams; i++) {
  757. AVStream *st = s->streams[i];
  758. OutputStream *os = &c->streams[i];
  759. char bandwidth_str[64] = {'\0'};
  760. if (os->as_idx - 1 != as_index)
  761. continue;
  762. if (os->bit_rate > 0)
  763. snprintf(bandwidth_str, sizeof(bandwidth_str), " bandwidth=\"%d\"",
  764. os->bit_rate);
  765. if (as->media_type == AVMEDIA_TYPE_VIDEO) {
  766. avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/%s\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"",
  767. i, os->format_name, os->codec_str, bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
  768. if (st->codecpar->field_order == AV_FIELD_UNKNOWN)
  769. avio_printf(out, " scanType=\"unknown\"");
  770. else if (st->codecpar->field_order != AV_FIELD_PROGRESSIVE)
  771. avio_printf(out, " scanType=\"interlaced\"");
  772. avio_printf(out, " sar=\"%d:%d\"", os->sar.num, os->sar.den);
  773. if (st->avg_frame_rate.num && av_cmp_q(as->min_frame_rate, as->max_frame_rate) < 0)
  774. avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
  775. if (as->trick_idx >= 0) {
  776. AdaptationSet *tas = &c->as[as->trick_idx];
  777. if (!as->ambiguous_frame_rate && !tas->ambiguous_frame_rate)
  778. avio_printf(out, " maxPlayoutRate=\"%d\"", FFMAX((int)av_q2d(av_div_q(tas->min_frame_rate, as->min_frame_rate)), 1));
  779. }
  780. if (!os->coding_dependency)
  781. avio_printf(out, " codingDependency=\"false\"");
  782. avio_printf(out, ">\n");
  783. } else {
  784. avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/%s\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
  785. i, os->format_name, os->codec_str, bandwidth_str, s->streams[i]->codecpar->sample_rate);
  786. avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
  787. s->streams[i]->codecpar->channels);
  788. }
  789. if (!final && c->write_prft && os->producer_reference_time_str[0]) {
  790. avio_printf(out, "\t\t\t\t<ProducerReferenceTime id=\"%d\" inband=\"true\" type=\"%s\" wallClockTime=\"%s\" presentationTime=\"%"PRId64"\">\n",
  791. i, os->producer_reference_time.flags ? "captured" : "encoder", os->producer_reference_time_str, c->presentation_time_offset);
  792. avio_printf(out, "\t\t\t\t\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
  793. avio_printf(out, "\t\t\t\t</ProducerReferenceTime>\n");
  794. }
  795. if (!final && c->ldash && os->gop_size && os->frag_type != FRAG_TYPE_NONE && !(c->profile & MPD_PROFILE_DVB) &&
  796. (os->frag_type != FRAG_TYPE_DURATION || os->frag_duration != os->seg_duration))
  797. avio_printf(out, "\t\t\t\t<Resync dT=\"%"PRId64"\" type=\"1\"/>\n", os->gop_size);
  798. output_segment_list(os, out, s, i, final);
  799. avio_printf(out, "\t\t\t</Representation>\n");
  800. }
  801. avio_printf(out, "\t\t</AdaptationSet>\n");
  802. return 0;
  803. }
  804. static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
  805. {
  806. DASHContext *c = s->priv_data;
  807. void *mem;
  808. if (c->profile & MPD_PROFILE_DVB && (c->nb_as + 1) > 16) {
  809. av_log(s, AV_LOG_ERROR, "DVB-DASH profile allows a max of 16 Adaptation Sets\n");
  810. return AVERROR(EINVAL);
  811. }
  812. mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
  813. if (!mem)
  814. return AVERROR(ENOMEM);
  815. c->as = mem;
  816. ++c->nb_as;
  817. *as = &c->as[c->nb_as - 1];
  818. memset(*as, 0, sizeof(**as));
  819. (*as)->media_type = type;
  820. (*as)->frag_type = -1;
  821. (*as)->trick_idx = -1;
  822. return 0;
  823. }
  824. static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
  825. {
  826. DASHContext *c = s->priv_data;
  827. AdaptationSet *as = &c->as[as_idx - 1];
  828. OutputStream *os = &c->streams[i];
  829. if (as->media_type != s->streams[i]->codecpar->codec_type) {
  830. av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
  831. return AVERROR(EINVAL);
  832. } else if (os->as_idx) {
  833. av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
  834. return AVERROR(EINVAL);
  835. }
  836. if (c->profile & MPD_PROFILE_DVB && (as->nb_streams + 1) > 16) {
  837. av_log(s, AV_LOG_ERROR, "DVB-DASH profile allows a max of 16 Representations per Adaptation Set\n");
  838. return AVERROR(EINVAL);
  839. }
  840. os->as_idx = as_idx;
  841. ++as->nb_streams;
  842. return 0;
  843. }
  844. static int parse_adaptation_sets(AVFormatContext *s)
  845. {
  846. DASHContext *c = s->priv_data;
  847. const char *p = c->adaptation_sets;
  848. enum { new_set, parse_default, parsing_streams, parse_seg_duration, parse_frag_duration } state;
  849. AdaptationSet *as;
  850. int i, n, ret;
  851. // default: one AdaptationSet for each stream
  852. if (!p) {
  853. for (i = 0; i < s->nb_streams; i++) {
  854. if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
  855. return ret;
  856. as->id = i;
  857. c->streams[i].as_idx = c->nb_as;
  858. ++as->nb_streams;
  859. }
  860. goto end;
  861. }
  862. // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
  863. // option id=0,descriptor=descriptor_str,streams=0,1,2 and so on
  864. // option id=0,seg_duration=2.5,frag_duration=0.5,streams=0,1,2
  865. // id=1,trick_id=0,seg_duration=10,frag_type=none,streams=3 and so on
  866. // descriptor is useful to the scheme defined by ISO/IEC 23009-1:2014/Amd.2:2015
  867. // descriptor_str should be a self-closing xml tag.
  868. // seg_duration and frag_duration have the same syntax as the global options of
  869. // the same name, and the former have precedence over them if set.
  870. state = new_set;
  871. while (*p) {
  872. if (*p == ' ') {
  873. p++;
  874. continue;
  875. } else if (state == new_set && av_strstart(p, "id=", &p)) {
  876. char id_str[10], *end_str;
  877. n = strcspn(p, ",");
  878. snprintf(id_str, sizeof(id_str), "%.*s", n, p);
  879. i = strtol(id_str, &end_str, 10);
  880. if (id_str == end_str || i < 0 || i > c->nb_as) {
  881. av_log(s, AV_LOG_ERROR, "\"%s\" is not a valid value for an AdaptationSet id\n", id_str);
  882. return AVERROR(EINVAL);
  883. }
  884. if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
  885. return ret;
  886. as->id = i;
  887. p += n;
  888. if (*p)
  889. p++;
  890. state = parse_default;
  891. } else if (state != new_set && av_strstart(p, "seg_duration=", &p)) {
  892. state = parse_seg_duration;
  893. } else if (state != new_set && av_strstart(p, "frag_duration=", &p)) {
  894. state = parse_frag_duration;
  895. } else if (state == parse_seg_duration || state == parse_frag_duration) {
  896. char str[32];
  897. int64_t usecs = 0;
  898. n = strcspn(p, ",");
  899. snprintf(str, sizeof(str), "%.*s", n, p);
  900. p += n;
  901. if (*p)
  902. p++;
  903. ret = av_parse_time(&usecs, str, 1);
  904. if (ret < 0) {
  905. av_log(s, AV_LOG_ERROR, "Unable to parse option value \"%s\" as duration\n", str);
  906. return ret;
  907. }
  908. if (state == parse_seg_duration)
  909. as->seg_duration = usecs;
  910. else
  911. as->frag_duration = usecs;
  912. state = parse_default;
  913. } else if (state != new_set && av_strstart(p, "frag_type=", &p)) {
  914. char type_str[16];
  915. n = strcspn(p, ",");
  916. snprintf(type_str, sizeof(type_str), "%.*s", n, p);
  917. p += n;
  918. if (*p)
  919. p++;
  920. if (!strcmp(type_str, "duration"))
  921. as->frag_type = FRAG_TYPE_DURATION;
  922. else if (!strcmp(type_str, "pframes"))
  923. as->frag_type = FRAG_TYPE_PFRAMES;
  924. else if (!strcmp(type_str, "every_frame"))
  925. as->frag_type = FRAG_TYPE_EVERY_FRAME;
  926. else if (!strcmp(type_str, "none"))
  927. as->frag_type = FRAG_TYPE_NONE;
  928. else {
  929. av_log(s, AV_LOG_ERROR, "Unable to parse option value \"%s\" as fragment type\n", type_str);
  930. return ret;
  931. }
  932. state = parse_default;
  933. } else if (state != new_set && av_strstart(p, "descriptor=", &p)) {
  934. n = strcspn(p, ">") + 1; //followed by one comma, so plus 1
  935. if (n < strlen(p)) {
  936. as->descriptor = av_strndup(p, n);
  937. } else {
  938. av_log(s, AV_LOG_ERROR, "Parse error, descriptor string should be a self-closing xml tag\n");
  939. return AVERROR(EINVAL);
  940. }
  941. p += n;
  942. if (*p)
  943. p++;
  944. state = parse_default;
  945. } else if ((state != new_set) && av_strstart(p, "trick_id=", &p)) {
  946. char trick_id_str[10], *end_str;
  947. n = strcspn(p, ",");
  948. snprintf(trick_id_str, sizeof(trick_id_str), "%.*s", n, p);
  949. p += n;
  950. as->trick_idx = strtol(trick_id_str, &end_str, 10);
  951. if (trick_id_str == end_str || as->trick_idx < 0)
  952. return AVERROR(EINVAL);
  953. if (*p)
  954. p++;
  955. state = parse_default;
  956. } else if ((state != new_set) && av_strstart(p, "streams=", &p)) { //descriptor and durations are optional
  957. state = parsing_streams;
  958. } else if (state == parsing_streams) {
  959. AdaptationSet *as = &c->as[c->nb_as - 1];
  960. char idx_str[8], *end_str;
  961. n = strcspn(p, " ,");
  962. snprintf(idx_str, sizeof(idx_str), "%.*s", n, p);
  963. p += n;
  964. // if value is "a" or "v", map all streams of that type
  965. if (as->media_type == AVMEDIA_TYPE_UNKNOWN && (idx_str[0] == 'v' || idx_str[0] == 'a')) {
  966. enum AVMediaType type = (idx_str[0] == 'v') ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
  967. av_log(s, AV_LOG_DEBUG, "Map all streams of type %s\n", idx_str);
  968. for (i = 0; i < s->nb_streams; i++) {
  969. if (s->streams[i]->codecpar->codec_type != type)
  970. continue;
  971. as->media_type = s->streams[i]->codecpar->codec_type;
  972. if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
  973. return ret;
  974. }
  975. } else { // select single stream
  976. i = strtol(idx_str, &end_str, 10);
  977. if (idx_str == end_str || i < 0 || i >= s->nb_streams) {
  978. av_log(s, AV_LOG_ERROR, "Selected stream \"%s\" not found!\n", idx_str);
  979. return AVERROR(EINVAL);
  980. }
  981. av_log(s, AV_LOG_DEBUG, "Map stream %d\n", i);
  982. if (as->media_type == AVMEDIA_TYPE_UNKNOWN) {
  983. as->media_type = s->streams[i]->codecpar->codec_type;
  984. }
  985. if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
  986. return ret;
  987. }
  988. if (*p == ' ')
  989. state = new_set;
  990. if (*p)
  991. p++;
  992. } else {
  993. return AVERROR(EINVAL);
  994. }
  995. }
  996. end:
  997. // check for unassigned streams
  998. for (i = 0; i < s->nb_streams; i++) {
  999. OutputStream *os = &c->streams[i];
  1000. if (!os->as_idx) {
  1001. av_log(s, AV_LOG_ERROR, "Stream %d is not mapped to an AdaptationSet\n", i);
  1002. return AVERROR(EINVAL);
  1003. }
  1004. }
  1005. // check references for trick mode AdaptationSet
  1006. for (i = 0; i < c->nb_as; i++) {
  1007. as = &c->as[i];
  1008. if (as->trick_idx < 0)
  1009. continue;
  1010. for (n = 0; n < c->nb_as; n++) {
  1011. if (c->as[n].id == as->trick_idx)
  1012. break;
  1013. }
  1014. if (n >= c->nb_as) {
  1015. av_log(s, AV_LOG_ERROR, "reference AdaptationSet id \"%d\" not found for trick mode AdaptationSet id \"%d\"\n", as->trick_idx, as->id);
  1016. return AVERROR(EINVAL);
  1017. }
  1018. }
  1019. return 0;
  1020. }
  1021. static int write_manifest(AVFormatContext *s, int final)
  1022. {
  1023. DASHContext *c = s->priv_data;
  1024. AVIOContext *out;
  1025. char temp_filename[1024];
  1026. int ret, i;
  1027. const char *proto = avio_find_protocol_name(s->url);
  1028. int use_rename = proto && !strcmp(proto, "file");
  1029. static unsigned int warned_non_file = 0;
  1030. AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
  1031. AVDictionary *opts = NULL;
  1032. if (!use_rename && !warned_non_file++)
  1033. av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
  1034. snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->url);
  1035. set_http_options(&opts, c);
  1036. ret = dashenc_io_open(s, &c->mpd_out, temp_filename, &opts);
  1037. av_dict_free(&opts);
  1038. if (ret < 0) {
  1039. return handle_io_open_error(s, ret, temp_filename);
  1040. }
  1041. out = c->mpd_out;
  1042. avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  1043. avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
  1044. "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
  1045. "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
  1046. "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
  1047. "\tprofiles=\"");
  1048. if (c->profile & MPD_PROFILE_DASH)
  1049. avio_printf(out, "%s%s", "urn:mpeg:dash:profile:isoff-live:2011", c->profile & MPD_PROFILE_DVB ? "," : "\"\n");
  1050. if (c->profile & MPD_PROFILE_DVB)
  1051. avio_printf(out, "%s", "urn:dvb:dash:profile:dvb-dash:2014\"\n");
  1052. avio_printf(out, "\ttype=\"%s\"\n",
  1053. final ? "static" : "dynamic");
  1054. if (final) {
  1055. avio_printf(out, "\tmediaPresentationDuration=\"");
  1056. write_time(out, c->total_duration);
  1057. avio_printf(out, "\"\n");
  1058. } else {
  1059. int64_t update_period = c->last_duration / AV_TIME_BASE;
  1060. char now_str[100];
  1061. if (c->use_template && !c->use_timeline)
  1062. update_period = 500;
  1063. avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
  1064. if (!c->ldash)
  1065. avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
  1066. if (c->availability_start_time[0])
  1067. avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
  1068. format_date(now_str, sizeof(now_str), av_gettime());
  1069. if (now_str[0])
  1070. avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
  1071. if (c->window_size && c->use_template) {
  1072. avio_printf(out, "\ttimeShiftBufferDepth=\"");
  1073. write_time(out, c->last_duration * c->window_size);
  1074. avio_printf(out, "\"\n");
  1075. }
  1076. }
  1077. avio_printf(out, "\tmaxSegmentDuration=\"");
  1078. write_time(out, c->max_segment_duration);
  1079. avio_printf(out, "\"\n");
  1080. avio_printf(out, "\tminBufferTime=\"");
  1081. write_time(out, c->ldash && c->max_gop_size ? c->max_gop_size : c->last_duration * 2);
  1082. avio_printf(out, "\">\n");
  1083. avio_printf(out, "\t<ProgramInformation>\n");
  1084. if (title) {
  1085. char *escaped = xmlescape(title->value);
  1086. avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
  1087. av_free(escaped);
  1088. }
  1089. avio_printf(out, "\t</ProgramInformation>\n");
  1090. avio_printf(out, "\t<ServiceDescription id=\"0\">\n");
  1091. if (!final && c->target_latency && c->target_latency_refid >= 0) {
  1092. avio_printf(out, "\t\t<Latency target=\"%"PRId64"\"", c->target_latency / 1000);
  1093. if (s->nb_streams > 1)
  1094. avio_printf(out, " referenceId=\"%d\"", c->target_latency_refid);
  1095. avio_printf(out, "/>\n");
  1096. }
  1097. if (av_cmp_q(c->min_playback_rate, (AVRational) {1, 1}) ||
  1098. av_cmp_q(c->max_playback_rate, (AVRational) {1, 1}))
  1099. avio_printf(out, "\t\t<PlaybackRate min=\"%.2f\" max=\"%.2f\"/>\n",
  1100. av_q2d(c->min_playback_rate), av_q2d(c->max_playback_rate));
  1101. avio_printf(out, "\t</ServiceDescription>\n");
  1102. if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
  1103. OutputStream *os = &c->streams[0];
  1104. int start_index = FFMAX(os->nb_segments - c->window_size, 0);
  1105. int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
  1106. avio_printf(out, "\t<Period id=\"0\" start=\"");
  1107. write_time(out, start_time);
  1108. avio_printf(out, "\">\n");
  1109. } else {
  1110. avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
  1111. }
  1112. for (i = 0; i < c->nb_as; i++) {
  1113. if ((ret = write_adaptation_set(s, out, i, final)) < 0)
  1114. return ret;
  1115. }
  1116. avio_printf(out, "\t</Period>\n");
  1117. if (c->utc_timing_url)
  1118. avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
  1119. avio_printf(out, "</MPD>\n");
  1120. avio_flush(out);
  1121. dashenc_io_close(s, &c->mpd_out, temp_filename);
  1122. if (use_rename) {
  1123. if ((ret = ff_rename(temp_filename, s->url, s)) < 0)
  1124. return ret;
  1125. }
  1126. if (c->hls_playlist) {
  1127. char filename_hls[1024];
  1128. const char *audio_group = "A1";
  1129. char audio_codec_str[128] = "\0";
  1130. int is_default = 1;
  1131. int max_audio_bitrate = 0;
  1132. // Publish master playlist only the configured rate
  1133. if (c->master_playlist_created && (!c->master_publish_rate ||
  1134. c->streams[0].segment_index % c->master_publish_rate))
  1135. return 0;
  1136. if (*c->dirname)
  1137. snprintf(filename_hls, sizeof(filename_hls), "%smaster.m3u8", c->dirname);
  1138. else
  1139. snprintf(filename_hls, sizeof(filename_hls), "master.m3u8");
  1140. snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", filename_hls);
  1141. set_http_options(&opts, c);
  1142. ret = dashenc_io_open(s, &c->m3u8_out, temp_filename, &opts);
  1143. av_dict_free(&opts);
  1144. if (ret < 0) {
  1145. return handle_io_open_error(s, ret, temp_filename);
  1146. }
  1147. ff_hls_write_playlist_version(c->m3u8_out, 7);
  1148. for (i = 0; i < s->nb_streams; i++) {
  1149. char playlist_file[64];
  1150. AVStream *st = s->streams[i];
  1151. OutputStream *os = &c->streams[i];
  1152. if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
  1153. continue;
  1154. if (os->segment_type != SEGMENT_TYPE_MP4)
  1155. continue;
  1156. get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
  1157. ff_hls_write_audio_rendition(c->m3u8_out, (char *)audio_group,
  1158. playlist_file, NULL, i, is_default);
  1159. max_audio_bitrate = FFMAX(st->codecpar->bit_rate +
  1160. os->muxer_overhead, max_audio_bitrate);
  1161. if (!av_strnstr(audio_codec_str, os->codec_str, sizeof(audio_codec_str))) {
  1162. if (strlen(audio_codec_str))
  1163. av_strlcat(audio_codec_str, ",", sizeof(audio_codec_str));
  1164. av_strlcat(audio_codec_str, os->codec_str, sizeof(audio_codec_str));
  1165. }
  1166. is_default = 0;
  1167. }
  1168. for (i = 0; i < s->nb_streams; i++) {
  1169. char playlist_file[64];
  1170. char codec_str[128];
  1171. AVStream *st = s->streams[i];
  1172. OutputStream *os = &c->streams[i];
  1173. char *agroup = NULL;
  1174. char *codec_str_ptr = NULL;
  1175. int stream_bitrate = st->codecpar->bit_rate + os->muxer_overhead;
  1176. if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
  1177. continue;
  1178. if (os->segment_type != SEGMENT_TYPE_MP4)
  1179. continue;
  1180. av_strlcpy(codec_str, os->codec_str, sizeof(codec_str));
  1181. if (max_audio_bitrate) {
  1182. agroup = (char *)audio_group;
  1183. stream_bitrate += max_audio_bitrate;
  1184. av_strlcat(codec_str, ",", sizeof(codec_str));
  1185. av_strlcat(codec_str, audio_codec_str, sizeof(codec_str));
  1186. }
  1187. if (st->codecpar->codec_id != AV_CODEC_ID_HEVC) {
  1188. codec_str_ptr = codec_str;
  1189. }
  1190. get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
  1191. ff_hls_write_stream_info(st, c->m3u8_out, stream_bitrate,
  1192. playlist_file, agroup,
  1193. codec_str_ptr, NULL, NULL);
  1194. }
  1195. dashenc_io_close(s, &c->m3u8_out, temp_filename);
  1196. if (use_rename)
  1197. if ((ret = ff_rename(temp_filename, filename_hls, s)) < 0)
  1198. return ret;
  1199. c->master_playlist_created = 1;
  1200. }
  1201. return 0;
  1202. }
  1203. static int dict_copy_entry(AVDictionary **dst, const AVDictionary *src, const char *key)
  1204. {
  1205. AVDictionaryEntry *entry = av_dict_get(src, key, NULL, 0);
  1206. if (entry)
  1207. av_dict_set(dst, key, entry->value, AV_DICT_DONT_OVERWRITE);
  1208. return 0;
  1209. }
  1210. static int dash_init(AVFormatContext *s)
  1211. {
  1212. DASHContext *c = s->priv_data;
  1213. int ret = 0, i;
  1214. char *ptr;
  1215. char basename[1024];
  1216. c->nr_of_streams_to_flush = 0;
  1217. if (c->single_file_name)
  1218. c->single_file = 1;
  1219. if (c->single_file)
  1220. c->use_template = 0;
  1221. if (!c->profile) {
  1222. av_log(s, AV_LOG_ERROR, "At least one profile must be enabled.\n");
  1223. return AVERROR(EINVAL);
  1224. }
  1225. #if FF_API_DASH_MIN_SEG_DURATION
  1226. if (c->min_seg_duration != 5000000) {
  1227. av_log(s, AV_LOG_WARNING, "The min_seg_duration option is deprecated and will be removed. Please use the -seg_duration\n");
  1228. c->seg_duration = c->min_seg_duration;
  1229. }
  1230. #endif
  1231. if (c->lhls && s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
  1232. av_log(s, AV_LOG_ERROR,
  1233. "LHLS is experimental, Please set -strict experimental in order to enable it.\n");
  1234. return AVERROR_EXPERIMENTAL;
  1235. }
  1236. if (c->lhls && !c->streaming) {
  1237. av_log(s, AV_LOG_WARNING, "LHLS option will be ignored as streaming is not enabled\n");
  1238. c->lhls = 0;
  1239. }
  1240. if (c->lhls && !c->hls_playlist) {
  1241. av_log(s, AV_LOG_WARNING, "LHLS option will be ignored as hls_playlist is not enabled\n");
  1242. c->lhls = 0;
  1243. }
  1244. if (c->ldash && !c->streaming) {
  1245. av_log(s, AV_LOG_WARNING, "LDash option will be ignored as streaming is not enabled\n");
  1246. c->ldash = 0;
  1247. }
  1248. if (c->target_latency && !c->streaming) {
  1249. av_log(s, AV_LOG_WARNING, "Target latency option will be ignored as streaming is not enabled\n");
  1250. c->target_latency = 0;
  1251. }
  1252. if (c->global_sidx && !c->single_file) {
  1253. av_log(s, AV_LOG_WARNING, "Global SIDX option will be ignored as single_file is not enabled\n");
  1254. c->global_sidx = 0;
  1255. }
  1256. if (c->global_sidx && c->streaming) {
  1257. av_log(s, AV_LOG_WARNING, "Global SIDX option will be ignored as streaming is enabled\n");
  1258. c->global_sidx = 0;
  1259. }
  1260. if (c->frag_type == FRAG_TYPE_NONE && c->streaming) {
  1261. av_log(s, AV_LOG_VERBOSE, "Changing frag_type from none to every_frame as streaming is enabled\n");
  1262. c->frag_type = FRAG_TYPE_EVERY_FRAME;
  1263. }
  1264. if (c->write_prft < 0) {
  1265. c->write_prft = c->ldash;
  1266. if (c->ldash)
  1267. av_log(s, AV_LOG_VERBOSE, "Enabling Producer Reference Time element for Low Latency mode\n");
  1268. }
  1269. if (c->write_prft && !c->utc_timing_url) {
  1270. av_log(s, AV_LOG_WARNING, "Producer Reference Time element option will be ignored as utc_timing_url is not set\n");
  1271. c->write_prft = 0;
  1272. }
  1273. if (c->write_prft && !c->streaming) {
  1274. av_log(s, AV_LOG_WARNING, "Producer Reference Time element option will be ignored as streaming is not enabled\n");
  1275. c->write_prft = 0;
  1276. }
  1277. if (c->ldash && !c->write_prft) {
  1278. av_log(s, AV_LOG_WARNING, "Low Latency mode enabled without Producer Reference Time element option! Resulting manifest may not be complaint\n");
  1279. }
  1280. if (c->target_latency && !c->write_prft) {
  1281. av_log(s, AV_LOG_WARNING, "Target latency option will be ignored as Producer Reference Time element will not be written\n");
  1282. c->target_latency = 0;
  1283. }
  1284. if (av_cmp_q(c->max_playback_rate, c->min_playback_rate) < 0) {
  1285. av_log(s, AV_LOG_WARNING, "Minimum playback rate value is higer than the Maximum. Both will be ignored\n");
  1286. c->min_playback_rate = c->max_playback_rate = (AVRational) {1, 1};
  1287. }
  1288. av_strlcpy(c->dirname, s->url, sizeof(c->dirname));
  1289. ptr = strrchr(c->dirname, '/');
  1290. if (ptr) {
  1291. av_strlcpy(basename, &ptr[1], sizeof(basename));
  1292. ptr[1] = '\0';
  1293. } else {
  1294. c->dirname[0] = '\0';
  1295. av_strlcpy(basename, s->url, sizeof(basename));
  1296. }
  1297. ptr = strrchr(basename, '.');
  1298. if (ptr)
  1299. *ptr = '\0';
  1300. c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
  1301. if (!c->streams)
  1302. return AVERROR(ENOMEM);
  1303. if ((ret = parse_adaptation_sets(s)) < 0)
  1304. return ret;
  1305. if ((ret = init_segment_types(s)) < 0)
  1306. return ret;
  1307. for (i = 0; i < s->nb_streams; i++) {
  1308. OutputStream *os = &c->streams[i];
  1309. AdaptationSet *as = &c->as[os->as_idx - 1];
  1310. AVFormatContext *ctx;
  1311. AVStream *st;
  1312. AVDictionary *opts = NULL;
  1313. char filename[1024];
  1314. os->bit_rate = s->streams[i]->codecpar->bit_rate;
  1315. if (!os->bit_rate) {
  1316. int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
  1317. AV_LOG_ERROR : AV_LOG_WARNING;
  1318. av_log(s, level, "No bit rate set for stream %d\n", i);
  1319. if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
  1320. return AVERROR(EINVAL);
  1321. }
  1322. // copy AdaptationSet language and role from stream metadata
  1323. dict_copy_entry(&as->metadata, s->streams[i]->metadata, "language");
  1324. dict_copy_entry(&as->metadata, s->streams[i]->metadata, "role");
  1325. if (c->init_seg_name) {
  1326. os->init_seg_name = av_strireplace(c->init_seg_name, "$ext$", os->extension_name);
  1327. if (!os->init_seg_name)
  1328. return AVERROR(ENOMEM);
  1329. }
  1330. if (c->media_seg_name) {
  1331. os->media_seg_name = av_strireplace(c->media_seg_name, "$ext$", os->extension_name);
  1332. if (!os->media_seg_name)
  1333. return AVERROR(ENOMEM);
  1334. }
  1335. if (c->single_file_name) {
  1336. os->single_file_name = av_strireplace(c->single_file_name, "$ext$", os->extension_name);
  1337. if (!os->single_file_name)
  1338. return AVERROR(ENOMEM);
  1339. }
  1340. if (os->segment_type == SEGMENT_TYPE_WEBM) {
  1341. if ((!c->single_file && check_file_extension(os->init_seg_name, os->format_name) != 0) ||
  1342. (!c->single_file && check_file_extension(os->media_seg_name, os->format_name) != 0) ||
  1343. (c->single_file && check_file_extension(os->single_file_name, os->format_name) != 0)) {
  1344. av_log(s, AV_LOG_WARNING,
  1345. "One or many segment file names doesn't end with .webm. "
  1346. "Override -init_seg_name and/or -media_seg_name and/or "
  1347. "-single_file_name to end with the extension .webm\n");
  1348. }
  1349. if (c->streaming) {
  1350. // Streaming not supported as matroskaenc buffers internally before writing the output
  1351. av_log(s, AV_LOG_WARNING, "One or more streams in WebM output format. Streaming option will be ignored\n");
  1352. c->streaming = 0;
  1353. }
  1354. }
  1355. os->ctx = ctx = avformat_alloc_context();
  1356. if (!ctx)
  1357. return AVERROR(ENOMEM);
  1358. ctx->oformat = av_guess_format(os->format_name, NULL, NULL);
  1359. if (!ctx->oformat)
  1360. return AVERROR_MUXER_NOT_FOUND;
  1361. ctx->interrupt_callback = s->interrupt_callback;
  1362. ctx->opaque = s->opaque;
  1363. ctx->io_close = s->io_close;
  1364. ctx->io_open = s->io_open;
  1365. ctx->strict_std_compliance = s->strict_std_compliance;
  1366. if (!(st = avformat_new_stream(ctx, NULL)))
  1367. return AVERROR(ENOMEM);
  1368. avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
  1369. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  1370. st->time_base = s->streams[i]->time_base;
  1371. st->avg_frame_rate = s->streams[i]->avg_frame_rate;
  1372. ctx->avoid_negative_ts = s->avoid_negative_ts;
  1373. ctx->flags = s->flags;
  1374. os->parser = av_parser_init(st->codecpar->codec_id);
  1375. if (os->parser) {
  1376. os->parser_avctx = avcodec_alloc_context3(NULL);
  1377. if (!os->parser_avctx)
  1378. return AVERROR(ENOMEM);
  1379. ret = avcodec_parameters_to_context(os->parser_avctx, st->codecpar);
  1380. if (ret < 0)
  1381. return ret;
  1382. // We only want to parse frame headers
  1383. os->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
  1384. }
  1385. if (c->single_file) {
  1386. if (os->single_file_name)
  1387. ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), os->single_file_name, i, 0, os->bit_rate, 0);
  1388. else
  1389. snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.%s", basename, i, os->format_name);
  1390. } else {
  1391. ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), os->init_seg_name, i, 0, os->bit_rate, 0);
  1392. }
  1393. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
  1394. set_http_options(&opts, c);
  1395. if (!c->single_file) {
  1396. if ((ret = avio_open_dyn_buf(&ctx->pb)) < 0)
  1397. return ret;
  1398. ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, &opts);
  1399. } else {
  1400. ctx->url = av_strdup(filename);
  1401. ret = avio_open2(&ctx->pb, filename, AVIO_FLAG_WRITE, NULL, &opts);
  1402. }
  1403. av_dict_free(&opts);
  1404. if (ret < 0)
  1405. return ret;
  1406. os->init_start_pos = 0;
  1407. av_dict_copy(&opts, c->format_options, 0);
  1408. if (!as->seg_duration)
  1409. as->seg_duration = c->seg_duration;
  1410. if (!as->frag_duration)
  1411. as->frag_duration = c->frag_duration;
  1412. if (as->frag_type < 0)
  1413. as->frag_type = c->frag_type;
  1414. os->seg_duration = as->seg_duration;
  1415. os->frag_duration = as->frag_duration;
  1416. os->frag_type = as->frag_type;
  1417. c->max_segment_duration = FFMAX(c->max_segment_duration, as->seg_duration);
  1418. if (c->profile & MPD_PROFILE_DVB && (os->seg_duration > 15000000 || os->seg_duration < 960000)) {
  1419. av_log(s, AV_LOG_ERROR, "Segment duration %"PRId64" is outside the allowed range for DVB-DASH profile\n", os->seg_duration);
  1420. return AVERROR(EINVAL);
  1421. }
  1422. if (os->frag_type == FRAG_TYPE_DURATION && !os->frag_duration) {
  1423. av_log(s, AV_LOG_WARNING, "frag_type set to duration for stream %d but no frag_duration set\n", i);
  1424. os->frag_type = c->streaming ? FRAG_TYPE_EVERY_FRAME : FRAG_TYPE_NONE;
  1425. }
  1426. if (os->frag_type == FRAG_TYPE_DURATION && os->frag_duration > os->seg_duration) {
  1427. av_log(s, AV_LOG_ERROR, "Fragment duration %"PRId64" is longer than Segment duration %"PRId64"\n", os->frag_duration, os->seg_duration);
  1428. return AVERROR(EINVAL);
  1429. }
  1430. if (os->frag_type == FRAG_TYPE_PFRAMES && (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO || !os->parser)) {
  1431. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && !os->parser)
  1432. av_log(s, AV_LOG_WARNING, "frag_type set to P-Frame reordering, but no parser found for stream %d\n", i);
  1433. os->frag_type = c->streaming ? FRAG_TYPE_EVERY_FRAME : FRAG_TYPE_NONE;
  1434. }
  1435. if (os->frag_type != FRAG_TYPE_PFRAMES && as->trick_idx < 0)
  1436. // Set this now if a parser isn't used
  1437. os->coding_dependency = 1;
  1438. if (os->segment_type == SEGMENT_TYPE_MP4) {
  1439. if (c->streaming)
  1440. // skip_sidx : Reduce bitrate overhead
  1441. // skip_trailer : Avoids growing memory usage with time
  1442. av_dict_set(&opts, "movflags", "+dash+delay_moov+skip_sidx+skip_trailer", AV_DICT_APPEND);
  1443. else {
  1444. if (c->global_sidx)
  1445. av_dict_set(&opts, "movflags", "+dash+delay_moov+global_sidx+skip_trailer", AV_DICT_APPEND);
  1446. else
  1447. av_dict_set(&opts, "movflags", "+dash+delay_moov+skip_trailer", AV_DICT_APPEND);
  1448. }
  1449. if (os->frag_type == FRAG_TYPE_EVERY_FRAME)
  1450. av_dict_set(&opts, "movflags", "+frag_every_frame", AV_DICT_APPEND);
  1451. else
  1452. av_dict_set(&opts, "movflags", "+frag_custom", AV_DICT_APPEND);
  1453. if (os->frag_type == FRAG_TYPE_DURATION)
  1454. av_dict_set_int(&opts, "frag_duration", os->frag_duration, 0);
  1455. if (c->write_prft)
  1456. av_dict_set(&opts, "write_prft", "wallclock", 0);
  1457. } else {
  1458. av_dict_set_int(&opts, "cluster_time_limit", c->seg_duration / 1000, 0);
  1459. av_dict_set_int(&opts, "cluster_size_limit", 5 * 1024 * 1024, 0); // set a large cluster size limit
  1460. av_dict_set_int(&opts, "dash", 1, 0);
  1461. av_dict_set_int(&opts, "dash_track_number", i + 1, 0);
  1462. av_dict_set_int(&opts, "live", 1, 0);
  1463. }
  1464. ret = avformat_init_output(ctx, &opts);
  1465. av_dict_free(&opts);
  1466. if (ret < 0)
  1467. return ret;
  1468. os->ctx_inited = 1;
  1469. avio_flush(ctx->pb);
  1470. av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
  1471. s->streams[i]->time_base = st->time_base;
  1472. // If the muxer wants to shift timestamps, request to have them shifted
  1473. // already before being handed to this muxer, so we don't have mismatches
  1474. // between the MPD and the actual segments.
  1475. s->avoid_negative_ts = ctx->avoid_negative_ts;
  1476. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  1477. AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
  1478. AVRational par;
  1479. if (avg_frame_rate.num > 0) {
  1480. if (av_cmp_q(avg_frame_rate, as->min_frame_rate) < 0)
  1481. as->min_frame_rate = avg_frame_rate;
  1482. if (av_cmp_q(as->max_frame_rate, avg_frame_rate) < 0)
  1483. as->max_frame_rate = avg_frame_rate;
  1484. } else {
  1485. as->ambiguous_frame_rate = 1;
  1486. }
  1487. if (st->codecpar->width > as->max_width)
  1488. as->max_width = st->codecpar->width;
  1489. if (st->codecpar->height > as->max_height)
  1490. as->max_height = st->codecpar->height;
  1491. if (st->sample_aspect_ratio.num)
  1492. os->sar = st->sample_aspect_ratio;
  1493. else
  1494. os->sar = (AVRational){1,1};
  1495. av_reduce(&par.num, &par.den,
  1496. st->codecpar->width * (int64_t)os->sar.num,
  1497. st->codecpar->height * (int64_t)os->sar.den,
  1498. 1024 * 1024);
  1499. if (as->par.num && av_cmp_q(par, as->par)) {
  1500. av_log(s, AV_LOG_ERROR, "Conflicting stream par values in Adaptation Set %d\n", os->as_idx);
  1501. return AVERROR(EINVAL);
  1502. }
  1503. as->par = par;
  1504. c->has_video = 1;
  1505. }
  1506. set_codec_str(s, st->codecpar, &st->avg_frame_rate, os->codec_str,
  1507. sizeof(os->codec_str));
  1508. os->first_pts = AV_NOPTS_VALUE;
  1509. os->max_pts = AV_NOPTS_VALUE;
  1510. os->last_dts = AV_NOPTS_VALUE;
  1511. os->segment_index = 1;
  1512. if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  1513. c->nr_of_streams_to_flush++;
  1514. }
  1515. if (!c->has_video && c->seg_duration <= 0) {
  1516. av_log(s, AV_LOG_WARNING, "no video stream and no seg duration set\n");
  1517. return AVERROR(EINVAL);
  1518. }
  1519. if (!c->has_video && c->frag_type == FRAG_TYPE_PFRAMES)
  1520. av_log(s, AV_LOG_WARNING, "no video stream and P-frame fragmentation set\n");
  1521. c->nr_of_streams_flushed = 0;
  1522. c->target_latency_refid = -1;
  1523. return 0;
  1524. }
  1525. static int dash_write_header(AVFormatContext *s)
  1526. {
  1527. DASHContext *c = s->priv_data;
  1528. int i, ret;
  1529. for (i = 0; i < s->nb_streams; i++) {
  1530. OutputStream *os = &c->streams[i];
  1531. if ((ret = avformat_write_header(os->ctx, NULL)) < 0)
  1532. return ret;
  1533. // Flush init segment
  1534. // Only for WebM segment, since for mp4 delay_moov is set and
  1535. // the init segment is thus flushed after the first packets.
  1536. if (os->segment_type == SEGMENT_TYPE_WEBM &&
  1537. (ret = flush_init_segment(s, os)) < 0)
  1538. return ret;
  1539. }
  1540. return ret;
  1541. }
  1542. static int add_segment(OutputStream *os, const char *file,
  1543. int64_t time, int64_t duration,
  1544. int64_t start_pos, int64_t range_length,
  1545. int64_t index_length, int next_exp_index)
  1546. {
  1547. int err;
  1548. Segment *seg;
  1549. if (os->nb_segments >= os->segments_size) {
  1550. os->segments_size = (os->segments_size + 1) * 2;
  1551. if ((err = av_reallocp_array(&os->segments, sizeof(*os->segments),
  1552. os->segments_size)) < 0) {
  1553. os->segments_size = 0;
  1554. os->nb_segments = 0;
  1555. return err;
  1556. }
  1557. }
  1558. seg = av_mallocz(sizeof(*seg));
  1559. if (!seg)
  1560. return AVERROR(ENOMEM);
  1561. av_strlcpy(seg->file, file, sizeof(seg->file));
  1562. seg->time = time;
  1563. seg->duration = duration;
  1564. if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
  1565. seg->duration += seg->time;
  1566. seg->time = 0;
  1567. }
  1568. seg->start_pos = start_pos;
  1569. seg->range_length = range_length;
  1570. seg->index_length = index_length;
  1571. os->segments[os->nb_segments++] = seg;
  1572. os->segment_index++;
  1573. //correcting the segment index if it has fallen behind the expected value
  1574. if (os->segment_index < next_exp_index) {
  1575. av_log(NULL, AV_LOG_WARNING, "Correcting the segment index after file %s: current=%d corrected=%d\n",
  1576. file, os->segment_index, next_exp_index);
  1577. os->segment_index = next_exp_index;
  1578. }
  1579. return 0;
  1580. }
  1581. static void write_styp(AVIOContext *pb)
  1582. {
  1583. avio_wb32(pb, 24);
  1584. ffio_wfourcc(pb, "styp");
  1585. ffio_wfourcc(pb, "msdh");
  1586. avio_wb32(pb, 0); /* minor */
  1587. ffio_wfourcc(pb, "msdh");
  1588. ffio_wfourcc(pb, "msix");
  1589. }
  1590. static void find_index_range(AVFormatContext *s, const char *full_path,
  1591. int64_t pos, int *index_length)
  1592. {
  1593. uint8_t buf[8];
  1594. AVIOContext *pb;
  1595. int ret;
  1596. ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
  1597. if (ret < 0)
  1598. return;
  1599. if (avio_seek(pb, pos, SEEK_SET) != pos) {
  1600. ff_format_io_close(s, &pb);
  1601. return;
  1602. }
  1603. ret = avio_read(pb, buf, 8);
  1604. ff_format_io_close(s, &pb);
  1605. if (ret < 8)
  1606. return;
  1607. if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
  1608. return;
  1609. *index_length = AV_RB32(&buf[0]);
  1610. }
  1611. static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
  1612. AVPacket *pkt, AVRational *frame_rate)
  1613. {
  1614. AVCodecParameters *par = os->ctx->streams[0]->codecpar;
  1615. uint8_t *extradata;
  1616. int ret, extradata_size;
  1617. if (par->extradata_size)
  1618. return 0;
  1619. extradata = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &extradata_size);
  1620. if (!extradata_size)
  1621. return 0;
  1622. ret = ff_alloc_extradata(par, extradata_size);
  1623. if (ret < 0)
  1624. return ret;
  1625. memcpy(par->extradata, extradata, extradata_size);
  1626. set_codec_str(s, par, frame_rate, os->codec_str, sizeof(os->codec_str));
  1627. return 0;
  1628. }
  1629. static void dashenc_delete_file(AVFormatContext *s, char *filename) {
  1630. DASHContext *c = s->priv_data;
  1631. int http_base_proto = ff_is_http_proto(filename);
  1632. if (http_base_proto) {
  1633. AVIOContext *out = NULL;
  1634. AVDictionary *http_opts = NULL;
  1635. set_http_options(&http_opts, c);
  1636. av_dict_set(&http_opts, "method", "DELETE", 0);
  1637. if (dashenc_io_open(s, &out, filename, &http_opts) < 0) {
  1638. av_log(s, AV_LOG_ERROR, "failed to delete %s\n", filename);
  1639. }
  1640. av_dict_free(&http_opts);
  1641. ff_format_io_close(s, &out);
  1642. } else {
  1643. int res = avpriv_io_delete(filename);
  1644. if (res < 0) {
  1645. char errbuf[AV_ERROR_MAX_STRING_SIZE];
  1646. av_strerror(res, errbuf, sizeof(errbuf));
  1647. av_log(s, (res == AVERROR(ENOENT) ? AV_LOG_WARNING : AV_LOG_ERROR), "failed to delete %s: %s\n", filename, errbuf);
  1648. }
  1649. }
  1650. }
  1651. static int dashenc_delete_segment_file(AVFormatContext *s, const char* file)
  1652. {
  1653. DASHContext *c = s->priv_data;
  1654. AVBPrint buf;
  1655. av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
  1656. av_bprintf(&buf, "%s%s", c->dirname, file);
  1657. if (!av_bprint_is_complete(&buf)) {
  1658. av_bprint_finalize(&buf, NULL);
  1659. av_log(s, AV_LOG_WARNING, "Out of memory for filename\n");
  1660. return AVERROR(ENOMEM);
  1661. }
  1662. dashenc_delete_file(s, buf.str);
  1663. av_bprint_finalize(&buf, NULL);
  1664. return 0;
  1665. }
  1666. static inline void dashenc_delete_media_segments(AVFormatContext *s, OutputStream *os, int remove_count)
  1667. {
  1668. for (int i = 0; i < remove_count; ++i) {
  1669. dashenc_delete_segment_file(s, os->segments[i]->file);
  1670. // Delete the segment regardless of whether the file was successfully deleted
  1671. av_free(os->segments[i]);
  1672. }
  1673. os->nb_segments -= remove_count;
  1674. memmove(os->segments, os->segments + remove_count, os->nb_segments * sizeof(*os->segments));
  1675. }
  1676. static int dash_flush(AVFormatContext *s, int final, int stream)
  1677. {
  1678. DASHContext *c = s->priv_data;
  1679. int i, ret = 0;
  1680. const char *proto = avio_find_protocol_name(s->url);
  1681. int use_rename = proto && !strcmp(proto, "file");
  1682. int cur_flush_segment_index = 0, next_exp_index = -1;
  1683. if (stream >= 0) {
  1684. cur_flush_segment_index = c->streams[stream].segment_index;
  1685. //finding the next segment's expected index, based on the current pts value
  1686. if (c->use_template && !c->use_timeline && c->index_correction &&
  1687. c->streams[stream].last_pts != AV_NOPTS_VALUE &&
  1688. c->streams[stream].first_pts != AV_NOPTS_VALUE) {
  1689. int64_t pts_diff = av_rescale_q(c->streams[stream].last_pts -
  1690. c->streams[stream].first_pts,
  1691. s->streams[stream]->time_base,
  1692. AV_TIME_BASE_Q);
  1693. next_exp_index = (pts_diff / c->streams[stream].seg_duration) + 1;
  1694. }
  1695. }
  1696. for (i = 0; i < s->nb_streams; i++) {
  1697. OutputStream *os = &c->streams[i];
  1698. AVStream *st = s->streams[i];
  1699. int range_length, index_length = 0;
  1700. int64_t duration;
  1701. if (!os->packets_written)
  1702. continue;
  1703. // Flush the single stream that got a keyframe right now.
  1704. // Flush all audio streams as well, in sync with video keyframes,
  1705. // but not the other video streams.
  1706. if (stream >= 0 && i != stream) {
  1707. if (s->streams[stream]->codecpar->codec_type != AVMEDIA_TYPE_VIDEO &&
  1708. s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
  1709. continue;
  1710. if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
  1711. continue;
  1712. // Make sure we don't flush audio streams multiple times, when
  1713. // all video streams are flushed one at a time.
  1714. if (c->has_video && os->segment_index > cur_flush_segment_index)
  1715. continue;
  1716. }
  1717. if (c->single_file)
  1718. snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname, os->initfile);
  1719. ret = flush_dynbuf(c, os, &range_length);
  1720. if (ret < 0)
  1721. break;
  1722. os->packets_written = 0;
  1723. if (c->single_file) {
  1724. find_index_range(s, os->full_path, os->pos, &index_length);
  1725. } else {
  1726. dashenc_io_close(s, &os->out, os->temp_path);
  1727. if (use_rename) {
  1728. ret = ff_rename(os->temp_path, os->full_path, os->ctx);
  1729. if (ret < 0)
  1730. break;
  1731. }
  1732. }
  1733. duration = av_rescale_q(os->max_pts - os->start_pts, st->time_base, AV_TIME_BASE_Q);
  1734. os->last_duration = FFMAX(os->last_duration, duration);
  1735. if (!os->muxer_overhead && os->max_pts > os->start_pts)
  1736. os->muxer_overhead = ((int64_t) (range_length - os->total_pkt_size) *
  1737. 8 * AV_TIME_BASE) / duration;
  1738. os->total_pkt_size = 0;
  1739. os->total_pkt_duration = 0;
  1740. if (!os->bit_rate) {
  1741. // calculate average bitrate of first segment
  1742. int64_t bitrate = (int64_t) range_length * 8 * (c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE) / duration;
  1743. if (bitrate >= 0)
  1744. os->bit_rate = bitrate;
  1745. }
  1746. add_segment(os, os->filename, os->start_pts, os->max_pts - os->start_pts, os->pos, range_length, index_length, next_exp_index);
  1747. av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, os->full_path);
  1748. os->pos += range_length;
  1749. }
  1750. if (c->window_size) {
  1751. for (i = 0; i < s->nb_streams; i++) {
  1752. OutputStream *os = &c->streams[i];
  1753. int remove_count = os->nb_segments - c->window_size - c->extra_window_size;
  1754. if (remove_count > 0)
  1755. dashenc_delete_media_segments(s, os, remove_count);
  1756. }
  1757. }
  1758. if (final) {
  1759. for (i = 0; i < s->nb_streams; i++) {
  1760. OutputStream *os = &c->streams[i];
  1761. if (os->ctx && os->ctx_inited) {
  1762. int64_t file_size = avio_tell(os->ctx->pb);
  1763. av_write_trailer(os->ctx);
  1764. if (c->global_sidx) {
  1765. int j, start_index, start_number;
  1766. int64_t sidx_size = avio_tell(os->ctx->pb) - file_size;
  1767. get_start_index_number(os, c, &start_index, &start_number);
  1768. if (start_index >= os->nb_segments ||
  1769. os->segment_type != SEGMENT_TYPE_MP4)
  1770. continue;
  1771. os->init_range_length += sidx_size;
  1772. for (j = start_index; j < os->nb_segments; j++) {
  1773. Segment *seg = os->segments[j];
  1774. seg->start_pos += sidx_size;
  1775. }
  1776. }
  1777. }
  1778. }
  1779. }
  1780. if (ret >= 0) {
  1781. if (c->has_video && !final) {
  1782. c->nr_of_streams_flushed++;
  1783. if (c->nr_of_streams_flushed != c->nr_of_streams_to_flush)
  1784. return ret;
  1785. c->nr_of_streams_flushed = 0;
  1786. }
  1787. ret = write_manifest(s, final);
  1788. }
  1789. return ret;
  1790. }
  1791. static int dash_parse_prft(DASHContext *c, AVPacket *pkt)
  1792. {
  1793. OutputStream *os = &c->streams[pkt->stream_index];
  1794. AVProducerReferenceTime *prft;
  1795. int side_data_size;
  1796. prft = (AVProducerReferenceTime *)av_packet_get_side_data(pkt, AV_PKT_DATA_PRFT, &side_data_size);
  1797. if (!prft || side_data_size != sizeof(AVProducerReferenceTime) || (prft->flags && prft->flags != 24)) {
  1798. // No encoder generated or user provided capture time AVProducerReferenceTime side data. Instead
  1799. // of letting the mov muxer generate one, do it here so we can also use it for the manifest.
  1800. prft = (AVProducerReferenceTime *)av_packet_new_side_data(pkt, AV_PKT_DATA_PRFT,
  1801. sizeof(AVProducerReferenceTime));
  1802. if (!prft)
  1803. return AVERROR(ENOMEM);
  1804. prft->wallclock = av_gettime();
  1805. prft->flags = 24;
  1806. }
  1807. if (os->first_pts == AV_NOPTS_VALUE) {
  1808. os->producer_reference_time = *prft;
  1809. if (c->target_latency_refid < 0)
  1810. c->target_latency_refid = pkt->stream_index;
  1811. }
  1812. return 0;
  1813. }
  1814. static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
  1815. {
  1816. DASHContext *c = s->priv_data;
  1817. AVStream *st = s->streams[pkt->stream_index];
  1818. OutputStream *os = &c->streams[pkt->stream_index];
  1819. AdaptationSet *as = &c->as[os->as_idx - 1];
  1820. int64_t seg_end_duration, elapsed_duration;
  1821. int ret;
  1822. ret = update_stream_extradata(s, os, pkt, &st->avg_frame_rate);
  1823. if (ret < 0)
  1824. return ret;
  1825. // Fill in a heuristic guess of the packet duration, if none is available.
  1826. // The mp4 muxer will do something similar (for the last packet in a fragment)
  1827. // if nothing is set (setting it for the other packets doesn't hurt).
  1828. // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
  1829. // invoke its heuristic (this doesn't have to be identical to that algorithm),
  1830. // so that we know the exact timestamps of fragments.
  1831. if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
  1832. pkt->duration = pkt->dts - os->last_dts;
  1833. os->last_dts = pkt->dts;
  1834. // If forcing the stream to start at 0, the mp4 muxer will set the start
  1835. // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
  1836. if (os->first_pts == AV_NOPTS_VALUE &&
  1837. s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
  1838. pkt->pts -= pkt->dts;
  1839. pkt->dts = 0;
  1840. }
  1841. if (c->write_prft) {
  1842. ret = dash_parse_prft(c, pkt);
  1843. if (ret < 0)
  1844. return ret;
  1845. }
  1846. if (os->first_pts == AV_NOPTS_VALUE) {
  1847. os->first_pts = pkt->pts;
  1848. }
  1849. os->last_pts = pkt->pts;
  1850. if (!c->availability_start_time[0]) {
  1851. int64_t start_time_us = av_gettime();
  1852. c->start_time_s = start_time_us / 1000000;
  1853. format_date(c->availability_start_time,
  1854. sizeof(c->availability_start_time), start_time_us);
  1855. }
  1856. if (!os->packets_written)
  1857. os->availability_time_offset = 0;
  1858. if (!os->availability_time_offset &&
  1859. ((os->frag_type == FRAG_TYPE_DURATION && os->seg_duration != os->frag_duration) ||
  1860. (os->frag_type == FRAG_TYPE_EVERY_FRAME && pkt->duration))) {
  1861. AdaptationSet *as = &c->as[os->as_idx - 1];
  1862. int64_t frame_duration = 0;
  1863. switch (os->frag_type) {
  1864. case FRAG_TYPE_DURATION:
  1865. frame_duration = os->frag_duration;
  1866. break;
  1867. case FRAG_TYPE_EVERY_FRAME:
  1868. frame_duration = av_rescale_q(pkt->duration, st->time_base, AV_TIME_BASE_Q);
  1869. break;
  1870. }
  1871. os->availability_time_offset = ((double) os->seg_duration -
  1872. frame_duration) / AV_TIME_BASE;
  1873. as->max_frag_duration = FFMAX(frame_duration, as->max_frag_duration);
  1874. }
  1875. if (c->use_template && !c->use_timeline) {
  1876. elapsed_duration = pkt->pts - os->first_pts;
  1877. seg_end_duration = (int64_t) os->segment_index * os->seg_duration;
  1878. } else {
  1879. elapsed_duration = pkt->pts - os->start_pts;
  1880. seg_end_duration = os->seg_duration;
  1881. }
  1882. if (os->parser &&
  1883. (os->frag_type == FRAG_TYPE_PFRAMES ||
  1884. as->trick_idx >= 0)) {
  1885. // Parse the packets only in scenarios where it's needed
  1886. uint8_t *data;
  1887. int size;
  1888. av_parser_parse2(os->parser, os->parser_avctx,
  1889. &data, &size, pkt->data, pkt->size,
  1890. pkt->pts, pkt->dts, pkt->pos);
  1891. os->coding_dependency |= os->parser->pict_type != AV_PICTURE_TYPE_I;
  1892. }
  1893. if (pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
  1894. av_compare_ts(elapsed_duration, st->time_base,
  1895. seg_end_duration, AV_TIME_BASE_Q) >= 0) {
  1896. if (!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  1897. c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
  1898. st->time_base,
  1899. AV_TIME_BASE_Q);
  1900. c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
  1901. st->time_base,
  1902. AV_TIME_BASE_Q);
  1903. if ((!c->use_timeline || !c->use_template) && os->last_duration) {
  1904. if (c->last_duration < os->last_duration*9/10 ||
  1905. c->last_duration > os->last_duration*11/10) {
  1906. av_log(s, AV_LOG_WARNING,
  1907. "Segment durations differ too much, enable use_timeline "
  1908. "and use_template, or keep a stricter keyframe interval\n");
  1909. }
  1910. }
  1911. }
  1912. if (c->write_prft && os->producer_reference_time.wallclock && !os->producer_reference_time_str[0])
  1913. format_date(os->producer_reference_time_str,
  1914. sizeof(os->producer_reference_time_str),
  1915. os->producer_reference_time.wallclock);
  1916. if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
  1917. return ret;
  1918. }
  1919. if (!os->packets_written) {
  1920. // If we wrote a previous segment, adjust the start time of the segment
  1921. // to the end of the previous one (which is the same as the mp4 muxer
  1922. // does). This avoids gaps in the timeline.
  1923. if (os->max_pts != AV_NOPTS_VALUE)
  1924. os->start_pts = os->max_pts;
  1925. else
  1926. os->start_pts = pkt->pts;
  1927. }
  1928. if (os->max_pts == AV_NOPTS_VALUE)
  1929. os->max_pts = pkt->pts + pkt->duration;
  1930. else
  1931. os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
  1932. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  1933. os->frag_type == FRAG_TYPE_PFRAMES &&
  1934. os->packets_written) {
  1935. av_assert0(os->parser);
  1936. if ((os->parser->pict_type == AV_PICTURE_TYPE_P &&
  1937. st->codecpar->video_delay &&
  1938. !(os->last_flags & AV_PKT_FLAG_KEY)) ||
  1939. pkt->flags & AV_PKT_FLAG_KEY) {
  1940. ret = av_write_frame(os->ctx, NULL);
  1941. if (ret < 0)
  1942. return ret;
  1943. if (!os->availability_time_offset) {
  1944. int64_t frag_duration = av_rescale_q(os->total_pkt_duration, st->time_base,
  1945. AV_TIME_BASE_Q);
  1946. os->availability_time_offset = ((double) os->seg_duration -
  1947. frag_duration) / AV_TIME_BASE;
  1948. as->max_frag_duration = FFMAX(frag_duration, as->max_frag_duration);
  1949. }
  1950. }
  1951. }
  1952. if (pkt->flags & AV_PKT_FLAG_KEY && (os->packets_written || os->nb_segments) && !os->gop_size && as->trick_idx < 0) {
  1953. os->gop_size = os->last_duration + av_rescale_q(os->total_pkt_duration, st->time_base, AV_TIME_BASE_Q);
  1954. c->max_gop_size = FFMAX(c->max_gop_size, os->gop_size);
  1955. }
  1956. if ((ret = ff_write_chained(os->ctx, 0, pkt, s, 0)) < 0)
  1957. return ret;
  1958. os->packets_written++;
  1959. os->total_pkt_size += pkt->size;
  1960. os->total_pkt_duration += pkt->duration;
  1961. os->last_flags = pkt->flags;
  1962. if (!os->init_range_length)
  1963. flush_init_segment(s, os);
  1964. //open the output context when the first frame of a segment is ready
  1965. if (!c->single_file && os->packets_written == 1) {
  1966. AVDictionary *opts = NULL;
  1967. const char *proto = avio_find_protocol_name(s->url);
  1968. int use_rename = proto && !strcmp(proto, "file");
  1969. if (os->segment_type == SEGMENT_TYPE_MP4)
  1970. write_styp(os->ctx->pb);
  1971. os->filename[0] = os->full_path[0] = os->temp_path[0] = '\0';
  1972. ff_dash_fill_tmpl_params(os->filename, sizeof(os->filename),
  1973. os->media_seg_name, pkt->stream_index,
  1974. os->segment_index, os->bit_rate, os->start_pts);
  1975. snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname,
  1976. os->filename);
  1977. snprintf(os->temp_path, sizeof(os->temp_path),
  1978. use_rename ? "%s.tmp" : "%s", os->full_path);
  1979. set_http_options(&opts, c);
  1980. ret = dashenc_io_open(s, &os->out, os->temp_path, &opts);
  1981. av_dict_free(&opts);
  1982. if (ret < 0) {
  1983. return handle_io_open_error(s, ret, os->temp_path);
  1984. }
  1985. if (c->lhls) {
  1986. char *prefetch_url = use_rename ? NULL : os->filename;
  1987. write_hls_media_playlist(os, s, pkt->stream_index, 0, prefetch_url);
  1988. }
  1989. }
  1990. //write out the data immediately in streaming mode
  1991. if (c->streaming && os->segment_type == SEGMENT_TYPE_MP4) {
  1992. int len = 0;
  1993. uint8_t *buf = NULL;
  1994. avio_flush(os->ctx->pb);
  1995. len = avio_get_dyn_buf (os->ctx->pb, &buf);
  1996. if (os->out) {
  1997. avio_write(os->out, buf + os->written_len, len - os->written_len);
  1998. avio_flush(os->out);
  1999. }
  2000. os->written_len = len;
  2001. }
  2002. return ret;
  2003. }
  2004. static int dash_write_trailer(AVFormatContext *s)
  2005. {
  2006. DASHContext *c = s->priv_data;
  2007. int i;
  2008. if (s->nb_streams > 0) {
  2009. OutputStream *os = &c->streams[0];
  2010. // If no segments have been written so far, try to do a crude
  2011. // guess of the segment duration
  2012. if (!c->last_duration)
  2013. c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
  2014. s->streams[0]->time_base,
  2015. AV_TIME_BASE_Q);
  2016. c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
  2017. s->streams[0]->time_base,
  2018. AV_TIME_BASE_Q);
  2019. }
  2020. dash_flush(s, 1, -1);
  2021. if (c->remove_at_exit) {
  2022. for (i = 0; i < s->nb_streams; ++i) {
  2023. OutputStream *os = &c->streams[i];
  2024. dashenc_delete_media_segments(s, os, os->nb_segments);
  2025. dashenc_delete_segment_file(s, os->initfile);
  2026. if (c->hls_playlist && os->segment_type == SEGMENT_TYPE_MP4) {
  2027. char filename[1024];
  2028. get_hls_playlist_name(filename, sizeof(filename), c->dirname, i);
  2029. dashenc_delete_file(s, filename);
  2030. }
  2031. }
  2032. dashenc_delete_file(s, s->url);
  2033. if (c->hls_playlist && c->master_playlist_created) {
  2034. char filename[1024];
  2035. snprintf(filename, sizeof(filename), "%smaster.m3u8", c->dirname);
  2036. dashenc_delete_file(s, filename);
  2037. }
  2038. }
  2039. return 0;
  2040. }
  2041. static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
  2042. {
  2043. DASHContext *c = s->priv_data;
  2044. OutputStream *os = &c->streams[avpkt->stream_index];
  2045. AVFormatContext *oc = os->ctx;
  2046. if (oc->oformat->check_bitstream) {
  2047. int ret;
  2048. AVPacket pkt = *avpkt;
  2049. pkt.stream_index = 0;
  2050. ret = oc->oformat->check_bitstream(oc, &pkt);
  2051. if (ret == 1) {
  2052. AVStream *st = s->streams[avpkt->stream_index];
  2053. AVStream *ost = oc->streams[0];
  2054. st->internal->bsfc = ost->internal->bsfc;
  2055. ost->internal->bsfc = NULL;
  2056. }
  2057. return ret;
  2058. }
  2059. return 1;
  2060. }
  2061. #define OFFSET(x) offsetof(DASHContext, x)
  2062. #define E AV_OPT_FLAG_ENCODING_PARAM
  2063. static const AVOption options[] = {
  2064. { "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 },
  2065. { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
  2066. { "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 },
  2067. #if FF_API_DASH_MIN_SEG_DURATION
  2068. { "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 },
  2069. #endif
  2070. { "seg_duration", "segment duration (in seconds, fractional value can be set)", OFFSET(seg_duration), AV_OPT_TYPE_DURATION, { .i64 = 5000000 }, 0, INT_MAX, E },
  2071. { "frag_duration", "fragment duration (in seconds, fractional value can be set)", OFFSET(frag_duration), AV_OPT_TYPE_DURATION, { .i64 = 0 }, 0, INT_MAX, E },
  2072. { "frag_type", "set type of interval for fragments", OFFSET(frag_type), AV_OPT_TYPE_INT, {.i64 = FRAG_TYPE_NONE }, 0, FRAG_TYPE_NB - 1, E, "frag_type"},
  2073. { "none", "one fragment per segment", 0, AV_OPT_TYPE_CONST, {.i64 = FRAG_TYPE_NONE }, 0, UINT_MAX, E, "frag_type"},
  2074. { "every_frame", "fragment at every frame", 0, AV_OPT_TYPE_CONST, {.i64 = FRAG_TYPE_EVERY_FRAME }, 0, UINT_MAX, E, "frag_type"},
  2075. { "duration", "fragment at specific time intervals", 0, AV_OPT_TYPE_CONST, {.i64 = FRAG_TYPE_DURATION }, 0, UINT_MAX, E, "frag_type"},
  2076. { "pframes", "fragment at keyframes and following P-Frame reordering (Video only, experimental)", 0, AV_OPT_TYPE_CONST, {.i64 = FRAG_TYPE_PFRAMES }, 0, UINT_MAX, E, "frag_type"},
  2077. { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
  2078. { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
  2079. { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
  2080. { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
  2081. { "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 },
  2082. { "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 },
  2083. { "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 },
  2084. { "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 },
  2085. { "method", "set the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  2086. { "http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
  2087. { "http_persistent", "Use persistent HTTP connections", OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
  2088. { "hls_playlist", "Generate HLS playlist files(master.m3u8, media_%d.m3u8)", OFFSET(hls_playlist), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
  2089. { "streaming", "Enable/Disable streaming mode of output. Each frame will be moof fragment", OFFSET(streaming), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
  2090. { "timeout", "set timeout for socket I/O operations", OFFSET(timeout), AV_OPT_TYPE_DURATION, { .i64 = -1 }, -1, INT_MAX, .flags = E },
  2091. { "index_correction", "Enable/Disable segment index correction logic", OFFSET(index_correction), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
  2092. { "format_options","set list of options for the container format (mp4/webm) used for dash", OFFSET(format_options), AV_OPT_TYPE_DICT, {.str = NULL}, 0, 0, E},
  2093. { "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 },
  2094. { "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"},
  2095. { "auto", "select segment file format based on codec", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_AUTO }, 0, UINT_MAX, E, "segment_type"},
  2096. { "mp4", "make segment file in ISOBMFF format", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_MP4 }, 0, UINT_MAX, E, "segment_type"},
  2097. { "webm", "make segment file in WebM format", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_WEBM }, 0, UINT_MAX, E, "segment_type"},
  2098. { "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 },
  2099. { "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 },
  2100. { "ldash", "Enable Low-latency dash. Constrains the value of a few elements", OFFSET(ldash), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
  2101. { "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},
  2102. { "write_prft", "Write producer reference time element", OFFSET(write_prft), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, E},
  2103. { "mpd_profile", "Set profiles. Elements and values used in the manifest may be constrained by them", OFFSET(profile), AV_OPT_TYPE_FLAGS, {.i64 = MPD_PROFILE_DASH }, 0, UINT_MAX, E, "mpd_profile"},
  2104. { "dash", "MPEG-DASH ISO Base media file format live profile", 0, AV_OPT_TYPE_CONST, {.i64 = MPD_PROFILE_DASH }, 0, UINT_MAX, E, "mpd_profile"},
  2105. { "dvb_dash", "DVB-DASH profile", 0, AV_OPT_TYPE_CONST, {.i64 = MPD_PROFILE_DVB }, 0, UINT_MAX, E, "mpd_profile"},
  2106. { "http_opts", "HTTP protocol options", OFFSET(http_opts), AV_OPT_TYPE_DICT, { .str = NULL }, 0, 0, E },
  2107. { "target_latency", "Set desired target latency for Low-latency dash", OFFSET(target_latency), AV_OPT_TYPE_DURATION, { .i64 = 0 }, 0, INT_MAX, E },
  2108. { "min_playback_rate", "Set desired minimum playback rate", OFFSET(min_playback_rate), AV_OPT_TYPE_RATIONAL, { .dbl = 1.0 }, 0.5, 1.5, E },
  2109. { "max_playback_rate", "Set desired maximum playback rate", OFFSET(max_playback_rate), AV_OPT_TYPE_RATIONAL, { .dbl = 1.0 }, 0.5, 1.5, E },
  2110. { NULL },
  2111. };
  2112. static const AVClass dash_class = {
  2113. .class_name = "dash muxer",
  2114. .item_name = av_default_item_name,
  2115. .option = options,
  2116. .version = LIBAVUTIL_VERSION_INT,
  2117. };
  2118. AVOutputFormat ff_dash_muxer = {
  2119. .name = "dash",
  2120. .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
  2121. .extensions = "mpd",
  2122. .priv_data_size = sizeof(DASHContext),
  2123. .audio_codec = AV_CODEC_ID_AAC,
  2124. .video_codec = AV_CODEC_ID_H264,
  2125. .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
  2126. .init = dash_init,
  2127. .write_header = dash_write_header,
  2128. .write_packet = dash_write_packet,
  2129. .write_trailer = dash_write_trailer,
  2130. .deinit = dash_free,
  2131. .check_bitstream = dash_check_bitstream,
  2132. .priv_class = &dash_class,
  2133. };