You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2399 lines
94KB

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