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.

1837 lines
68KB

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