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.

1622 lines
60KB

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