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.

1514 lines
56KB

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