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.

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