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.

1493 lines
55KB

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