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.

1021 lines
39KB

  1. /*
  2. * MPEG-DASH ISO BMFF segmenter
  3. * Copyright (c) 2014 Martin Storsjo
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "config.h"
  22. #if HAVE_UNISTD_H
  23. #include <unistd.h>
  24. #endif
  25. #include "libavutil/avstring.h"
  26. #include "libavutil/intreadwrite.h"
  27. #include "libavutil/mathematics.h"
  28. #include "libavutil/opt.h"
  29. #include "libavutil/time_internal.h"
  30. #include "avc.h"
  31. #include "avformat.h"
  32. #include "avio_internal.h"
  33. #include "internal.h"
  34. #include "isom.h"
  35. #include "os_support.h"
  36. #include "url.h"
  37. // See ISO/IEC 23009-1:2014 5.3.9.4.4
  38. typedef enum {
  39. DASH_TMPL_ID_UNDEFINED = -1,
  40. DASH_TMPL_ID_ESCAPE,
  41. DASH_TMPL_ID_REP_ID,
  42. DASH_TMPL_ID_NUMBER,
  43. DASH_TMPL_ID_BANDWIDTH,
  44. DASH_TMPL_ID_TIME,
  45. } DASHTmplId;
  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 OutputStream {
  55. AVFormatContext *ctx;
  56. int ctx_inited;
  57. uint8_t iobuf[32768];
  58. AVIOContext *out;
  59. int packets_written;
  60. char initfile[1024];
  61. int64_t init_start_pos;
  62. int init_range_length;
  63. int nb_segments, segments_size, segment_index;
  64. Segment **segments;
  65. int64_t first_pts, start_pts, max_pts;
  66. int64_t last_dts;
  67. int bit_rate;
  68. char bandwidth_str[64];
  69. char codec_str[100];
  70. } OutputStream;
  71. typedef struct DASHContext {
  72. const AVClass *class; /* Class for private options. */
  73. int window_size;
  74. int extra_window_size;
  75. int min_seg_duration;
  76. int remove_at_exit;
  77. int use_template;
  78. int use_timeline;
  79. int single_file;
  80. OutputStream *streams;
  81. int has_video, has_audio;
  82. int64_t last_duration;
  83. int64_t total_duration;
  84. char availability_start_time[100];
  85. char dirname[1024];
  86. const char *single_file_name;
  87. const char *init_seg_name;
  88. const char *media_seg_name;
  89. const char *utc_timing_url;
  90. } DASHContext;
  91. static int dash_write(void *opaque, uint8_t *buf, int buf_size)
  92. {
  93. OutputStream *os = opaque;
  94. if (os->out)
  95. avio_write(os->out, buf, buf_size);
  96. return buf_size;
  97. }
  98. // RFC 6381
  99. static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
  100. char *str, int size)
  101. {
  102. const AVCodecTag *tags[2] = { NULL, NULL };
  103. uint32_t tag;
  104. if (par->codec_type == AVMEDIA_TYPE_VIDEO)
  105. tags[0] = ff_codec_movvideo_tags;
  106. else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
  107. tags[0] = ff_codec_movaudio_tags;
  108. else
  109. return;
  110. tag = av_codec_get_tag(tags, par->codec_id);
  111. if (!tag)
  112. return;
  113. if (size < 5)
  114. return;
  115. AV_WL32(str, tag);
  116. str[4] = '\0';
  117. if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
  118. uint32_t oti;
  119. tags[0] = ff_mp4_obj_type;
  120. oti = av_codec_get_tag(tags, par->codec_id);
  121. if (oti)
  122. av_strlcatf(str, size, ".%02"SCNx32, oti);
  123. else
  124. return;
  125. if (tag == MKTAG('m', 'p', '4', 'a')) {
  126. if (par->extradata_size >= 2) {
  127. int aot = par->extradata[0] >> 3;
  128. if (aot == 31)
  129. aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
  130. av_strlcatf(str, size, ".%d", aot);
  131. }
  132. } else if (tag == MKTAG('m', 'p', '4', 'v')) {
  133. // Unimplemented, should output ProfileLevelIndication as a decimal number
  134. av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
  135. }
  136. } else if (!strcmp(str, "avc1")) {
  137. uint8_t *tmpbuf = NULL;
  138. uint8_t *extradata = par->extradata;
  139. int extradata_size = par->extradata_size;
  140. if (!extradata_size)
  141. return;
  142. if (extradata[0] != 1) {
  143. AVIOContext *pb;
  144. if (avio_open_dyn_buf(&pb) < 0)
  145. return;
  146. if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
  147. ffio_free_dyn_buf(&pb);
  148. return;
  149. }
  150. extradata_size = avio_close_dyn_buf(pb, &extradata);
  151. tmpbuf = extradata;
  152. }
  153. if (extradata_size >= 4)
  154. av_strlcatf(str, size, ".%02x%02x%02x",
  155. extradata[1], extradata[2], extradata[3]);
  156. av_free(tmpbuf);
  157. }
  158. }
  159. static void dash_free(AVFormatContext *s)
  160. {
  161. DASHContext *c = s->priv_data;
  162. int i, j;
  163. if (!c->streams)
  164. return;
  165. for (i = 0; i < s->nb_streams; i++) {
  166. OutputStream *os = &c->streams[i];
  167. if (os->ctx && os->ctx_inited)
  168. av_write_trailer(os->ctx);
  169. if (os->ctx && os->ctx->pb)
  170. av_free(os->ctx->pb);
  171. ff_format_io_close(s, &os->out);
  172. if (os->ctx)
  173. avformat_free_context(os->ctx);
  174. for (j = 0; j < os->nb_segments; j++)
  175. av_free(os->segments[j]);
  176. av_free(os->segments);
  177. }
  178. av_freep(&c->streams);
  179. }
  180. static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c)
  181. {
  182. int i, start_index = 0, start_number = 1;
  183. if (c->window_size) {
  184. start_index = FFMAX(os->nb_segments - c->window_size, 0);
  185. start_number = FFMAX(os->segment_index - c->window_size, 1);
  186. }
  187. if (c->use_template) {
  188. int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
  189. avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
  190. if (!c->use_timeline)
  191. avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);
  192. avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
  193. if (c->use_timeline) {
  194. int64_t cur_time = 0;
  195. avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
  196. for (i = start_index; i < os->nb_segments; ) {
  197. Segment *seg = os->segments[i];
  198. int repeat = 0;
  199. avio_printf(out, "\t\t\t\t\t\t<S ");
  200. if (i == start_index || seg->time != cur_time) {
  201. cur_time = seg->time;
  202. avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
  203. }
  204. avio_printf(out, "d=\"%d\" ", seg->duration);
  205. while (i + repeat + 1 < os->nb_segments &&
  206. os->segments[i + repeat + 1]->duration == seg->duration &&
  207. os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
  208. repeat++;
  209. if (repeat > 0)
  210. avio_printf(out, "r=\"%d\" ", repeat);
  211. avio_printf(out, "/>\n");
  212. i += 1 + repeat;
  213. cur_time += (1 + repeat) * seg->duration;
  214. }
  215. avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
  216. }
  217. avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
  218. } else if (c->single_file) {
  219. avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
  220. avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
  221. 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);
  222. for (i = start_index; i < os->nb_segments; i++) {
  223. Segment *seg = os->segments[i];
  224. avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
  225. if (seg->index_length)
  226. avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
  227. avio_printf(out, "/>\n");
  228. }
  229. avio_printf(out, "\t\t\t\t</SegmentList>\n");
  230. } else {
  231. avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
  232. avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
  233. for (i = start_index; i < os->nb_segments; i++) {
  234. Segment *seg = os->segments[i];
  235. avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
  236. }
  237. avio_printf(out, "\t\t\t\t</SegmentList>\n");
  238. }
  239. }
  240. static DASHTmplId dash_read_tmpl_id(const char *identifier, char *format_tag,
  241. size_t format_tag_size, const char **ptr) {
  242. const char *next_ptr;
  243. DASHTmplId id_type = DASH_TMPL_ID_UNDEFINED;
  244. if (av_strstart(identifier, "$$", &next_ptr)) {
  245. id_type = DASH_TMPL_ID_ESCAPE;
  246. *ptr = next_ptr;
  247. } else if (av_strstart(identifier, "$RepresentationID$", &next_ptr)) {
  248. id_type = DASH_TMPL_ID_REP_ID;
  249. // default to basic format, as $RepresentationID$ identifiers
  250. // are not allowed to have custom format-tags.
  251. av_strlcpy(format_tag, "%d", format_tag_size);
  252. *ptr = next_ptr;
  253. } else { // the following identifiers may have an explicit format_tag
  254. if (av_strstart(identifier, "$Number", &next_ptr))
  255. id_type = DASH_TMPL_ID_NUMBER;
  256. else if (av_strstart(identifier, "$Bandwidth", &next_ptr))
  257. id_type = DASH_TMPL_ID_BANDWIDTH;
  258. else if (av_strstart(identifier, "$Time", &next_ptr))
  259. id_type = DASH_TMPL_ID_TIME;
  260. else
  261. id_type = DASH_TMPL_ID_UNDEFINED;
  262. // next parse the dash format-tag and generate a c-string format tag
  263. // (next_ptr now points at the first '%' at the beginning of the format-tag)
  264. if (id_type != DASH_TMPL_ID_UNDEFINED) {
  265. const char *number_format = (id_type == DASH_TMPL_ID_TIME) ? PRId64 : "d";
  266. if (next_ptr[0] == '$') { // no dash format-tag
  267. snprintf(format_tag, format_tag_size, "%%%s", number_format);
  268. *ptr = &next_ptr[1];
  269. } else {
  270. const char *width_ptr;
  271. // only tolerate single-digit width-field (i.e. up to 9-digit width)
  272. if (av_strstart(next_ptr, "%0", &width_ptr) &&
  273. av_isdigit(width_ptr[0]) &&
  274. av_strstart(&width_ptr[1], "d$", &next_ptr)) {
  275. // yes, we're using a format tag to build format_tag.
  276. snprintf(format_tag, format_tag_size, "%s%c%s", "%0", width_ptr[0], number_format);
  277. *ptr = next_ptr;
  278. } else {
  279. av_log(NULL, AV_LOG_WARNING, "Failed to parse format-tag beginning with %s. Expected either a "
  280. "closing '$' character or a format-string like '%%0[width]d', "
  281. "where width must be a single digit\n", next_ptr);
  282. id_type = DASH_TMPL_ID_UNDEFINED;
  283. }
  284. }
  285. }
  286. }
  287. return id_type;
  288. }
  289. static void dash_fill_tmpl_params(char *dst, size_t buffer_size,
  290. const char *template, int rep_id,
  291. int number, int bit_rate,
  292. int64_t time) {
  293. int dst_pos = 0;
  294. const char *t_cur = template;
  295. while (dst_pos < buffer_size - 1 && *t_cur) {
  296. char format_tag[7]; // May be "%d", "%0Xd", or "%0Xlld" (for $Time$), where X is in [0-9]
  297. int n = 0;
  298. DASHTmplId id_type;
  299. const char *t_next = strchr(t_cur, '$'); // copy over everything up to the first '$' character
  300. if (t_next) {
  301. int num_copy_bytes = FFMIN(t_next - t_cur, buffer_size - dst_pos - 1);
  302. av_strlcpy(&dst[dst_pos], t_cur, num_copy_bytes + 1);
  303. // advance
  304. dst_pos += num_copy_bytes;
  305. t_cur = t_next;
  306. } else { // no more DASH identifiers to substitute - just copy the rest over and break
  307. av_strlcpy(&dst[dst_pos], t_cur, buffer_size - dst_pos);
  308. break;
  309. }
  310. if (dst_pos >= buffer_size - 1 || !*t_cur)
  311. break;
  312. // t_cur is now pointing to a '$' character
  313. id_type = dash_read_tmpl_id(t_cur, format_tag, sizeof(format_tag), &t_next);
  314. switch (id_type) {
  315. case DASH_TMPL_ID_ESCAPE:
  316. av_strlcpy(&dst[dst_pos], "$", 2);
  317. n = 1;
  318. break;
  319. case DASH_TMPL_ID_REP_ID:
  320. n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, rep_id);
  321. break;
  322. case DASH_TMPL_ID_NUMBER:
  323. n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, number);
  324. break;
  325. case DASH_TMPL_ID_BANDWIDTH:
  326. n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, bit_rate);
  327. break;
  328. case DASH_TMPL_ID_TIME:
  329. n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, time);
  330. break;
  331. case DASH_TMPL_ID_UNDEFINED:
  332. // copy over one byte and advance
  333. av_strlcpy(&dst[dst_pos], t_cur, 2);
  334. n = 1;
  335. t_next = &t_cur[1];
  336. break;
  337. }
  338. // t_next points just past the processed identifier
  339. // n is the number of bytes that were attempted to be written to dst
  340. // (may have failed to write all because buffer_size).
  341. // advance
  342. dst_pos += FFMIN(n, buffer_size - dst_pos - 1);
  343. t_cur = t_next;
  344. }
  345. }
  346. static char *xmlescape(const char *str) {
  347. int outlen = strlen(str)*3/2 + 6;
  348. char *out = av_realloc(NULL, outlen + 1);
  349. int pos = 0;
  350. if (!out)
  351. return NULL;
  352. for (; *str; str++) {
  353. if (pos + 6 > outlen) {
  354. char *tmp;
  355. outlen = 2 * outlen + 6;
  356. tmp = av_realloc(out, outlen + 1);
  357. if (!tmp) {
  358. av_free(out);
  359. return NULL;
  360. }
  361. out = tmp;
  362. }
  363. if (*str == '&') {
  364. memcpy(&out[pos], "&amp;", 5);
  365. pos += 5;
  366. } else if (*str == '<') {
  367. memcpy(&out[pos], "&lt;", 4);
  368. pos += 4;
  369. } else if (*str == '>') {
  370. memcpy(&out[pos], "&gt;", 4);
  371. pos += 4;
  372. } else if (*str == '\'') {
  373. memcpy(&out[pos], "&apos;", 6);
  374. pos += 6;
  375. } else if (*str == '\"') {
  376. memcpy(&out[pos], "&quot;", 6);
  377. pos += 6;
  378. } else {
  379. out[pos++] = *str;
  380. }
  381. }
  382. out[pos] = '\0';
  383. return out;
  384. }
  385. static void write_time(AVIOContext *out, int64_t time)
  386. {
  387. int seconds = time / AV_TIME_BASE;
  388. int fractions = time % AV_TIME_BASE;
  389. int minutes = seconds / 60;
  390. int hours = minutes / 60;
  391. seconds %= 60;
  392. minutes %= 60;
  393. avio_printf(out, "PT");
  394. if (hours)
  395. avio_printf(out, "%dH", hours);
  396. if (hours || minutes)
  397. avio_printf(out, "%dM", minutes);
  398. avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
  399. }
  400. static void format_date_now(char *buf, int size)
  401. {
  402. time_t t = time(NULL);
  403. struct tm *ptm, tmbuf;
  404. ptm = gmtime_r(&t, &tmbuf);
  405. if (ptm) {
  406. if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", ptm))
  407. buf[0] = '\0';
  408. }
  409. }
  410. static int write_manifest(AVFormatContext *s, int final)
  411. {
  412. DASHContext *c = s->priv_data;
  413. AVIOContext *out;
  414. char temp_filename[1024];
  415. int ret, i, as_id = 0;
  416. AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
  417. snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", s->filename);
  418. ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL);
  419. if (ret < 0) {
  420. av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
  421. return ret;
  422. }
  423. avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  424. avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
  425. "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
  426. "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
  427. "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
  428. "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
  429. "\ttype=\"%s\"\n", final ? "static" : "dynamic");
  430. if (final) {
  431. avio_printf(out, "\tmediaPresentationDuration=\"");
  432. write_time(out, c->total_duration);
  433. avio_printf(out, "\"\n");
  434. } else {
  435. int64_t update_period = c->last_duration / AV_TIME_BASE;
  436. char now_str[100];
  437. if (c->use_template && !c->use_timeline)
  438. update_period = 500;
  439. avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
  440. avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
  441. if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
  442. format_date_now(c->availability_start_time, sizeof(c->availability_start_time));
  443. }
  444. if (c->availability_start_time[0])
  445. avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
  446. format_date_now(now_str, sizeof(now_str));
  447. if (now_str[0])
  448. avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
  449. if (c->window_size && c->use_template) {
  450. avio_printf(out, "\ttimeShiftBufferDepth=\"");
  451. write_time(out, c->last_duration * c->window_size);
  452. avio_printf(out, "\"\n");
  453. }
  454. }
  455. avio_printf(out, "\tminBufferTime=\"");
  456. write_time(out, c->last_duration * 2);
  457. avio_printf(out, "\">\n");
  458. avio_printf(out, "\t<ProgramInformation>\n");
  459. if (title) {
  460. char *escaped = xmlescape(title->value);
  461. avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
  462. av_free(escaped);
  463. }
  464. avio_printf(out, "\t</ProgramInformation>\n");
  465. if (c->utc_timing_url)
  466. avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
  467. if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
  468. OutputStream *os = &c->streams[0];
  469. int start_index = FFMAX(os->nb_segments - c->window_size, 0);
  470. int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
  471. avio_printf(out, "\t<Period id=\"0\" start=\"");
  472. write_time(out, start_time);
  473. avio_printf(out, "\">\n");
  474. } else {
  475. avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
  476. }
  477. if (c->has_video) {
  478. avio_printf(out, "\t\t<AdaptationSet id=\"%d\" contentType=\"video\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n", as_id++);
  479. for (i = 0; i < s->nb_streams; i++) {
  480. AVStream *st = s->streams[i];
  481. OutputStream *os = &c->streams[i];
  482. if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
  483. continue;
  484. avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/mp4\" codecs=\"%s\"%s width=\"%d\" height=\"%d\">\n", i, os->codec_str, os->bandwidth_str, st->codecpar->width, st->codecpar->height);
  485. output_segment_list(&c->streams[i], out, c);
  486. avio_printf(out, "\t\t\t</Representation>\n");
  487. }
  488. avio_printf(out, "\t\t</AdaptationSet>\n");
  489. }
  490. if (c->has_audio) {
  491. avio_printf(out, "\t\t<AdaptationSet id=\"%d\" contentType=\"audio\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n", as_id++);
  492. for (i = 0; i < s->nb_streams; i++) {
  493. AVStream *st = s->streams[i];
  494. OutputStream *os = &c->streams[i];
  495. if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
  496. continue;
  497. avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/mp4\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n", i, os->codec_str, os->bandwidth_str, st->codecpar->sample_rate);
  498. avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n", st->codecpar->channels);
  499. output_segment_list(&c->streams[i], out, c);
  500. avio_printf(out, "\t\t\t</Representation>\n");
  501. }
  502. avio_printf(out, "\t\t</AdaptationSet>\n");
  503. }
  504. avio_printf(out, "\t</Period>\n");
  505. avio_printf(out, "</MPD>\n");
  506. avio_flush(out);
  507. ff_format_io_close(s, &out);
  508. return ff_rename(temp_filename, s->filename);
  509. }
  510. static int dash_write_header(AVFormatContext *s)
  511. {
  512. DASHContext *c = s->priv_data;
  513. int ret = 0, i;
  514. AVOutputFormat *oformat;
  515. char *ptr;
  516. char basename[1024];
  517. if (c->single_file_name)
  518. c->single_file = 1;
  519. if (c->single_file)
  520. c->use_template = 0;
  521. av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
  522. ptr = strrchr(c->dirname, '/');
  523. if (ptr) {
  524. av_strlcpy(basename, &ptr[1], sizeof(basename));
  525. ptr[1] = '\0';
  526. } else {
  527. c->dirname[0] = '\0';
  528. av_strlcpy(basename, s->filename, sizeof(basename));
  529. }
  530. ptr = strrchr(basename, '.');
  531. if (ptr)
  532. *ptr = '\0';
  533. oformat = av_guess_format("mp4", NULL, NULL);
  534. if (!oformat) {
  535. ret = AVERROR_MUXER_NOT_FOUND;
  536. goto fail;
  537. }
  538. c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
  539. if (!c->streams) {
  540. ret = AVERROR(ENOMEM);
  541. goto fail;
  542. }
  543. for (i = 0; i < s->nb_streams; i++) {
  544. OutputStream *os = &c->streams[i];
  545. AVFormatContext *ctx;
  546. AVStream *st;
  547. AVDictionary *opts = NULL;
  548. char filename[1024];
  549. os->bit_rate = s->streams[i]->codecpar->bit_rate;
  550. if (os->bit_rate) {
  551. snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
  552. " bandwidth=\"%d\"", os->bit_rate);
  553. } else {
  554. int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
  555. AV_LOG_ERROR : AV_LOG_WARNING;
  556. av_log(s, level, "No bit rate set for stream %d\n", i);
  557. if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
  558. ret = AVERROR(EINVAL);
  559. goto fail;
  560. }
  561. }
  562. ctx = avformat_alloc_context();
  563. if (!ctx) {
  564. ret = AVERROR(ENOMEM);
  565. goto fail;
  566. }
  567. os->ctx = ctx;
  568. ctx->oformat = oformat;
  569. ctx->interrupt_callback = s->interrupt_callback;
  570. ctx->opaque = s->opaque;
  571. ctx->io_close = s->io_close;
  572. ctx->io_open = s->io_open;
  573. if (!(st = avformat_new_stream(ctx, NULL))) {
  574. ret = AVERROR(ENOMEM);
  575. goto fail;
  576. }
  577. avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
  578. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  579. st->time_base = s->streams[i]->time_base;
  580. ctx->avoid_negative_ts = s->avoid_negative_ts;
  581. ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, dash_write, NULL);
  582. if (!ctx->pb) {
  583. ret = AVERROR(ENOMEM);
  584. goto fail;
  585. }
  586. if (c->single_file) {
  587. if (c->single_file_name)
  588. dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
  589. else
  590. snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
  591. } else {
  592. dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
  593. }
  594. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
  595. ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, NULL);
  596. if (ret < 0)
  597. goto fail;
  598. os->init_start_pos = 0;
  599. av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
  600. if ((ret = avformat_write_header(ctx, &opts)) < 0) {
  601. goto fail;
  602. }
  603. os->ctx_inited = 1;
  604. avio_flush(ctx->pb);
  605. av_dict_free(&opts);
  606. av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
  607. s->streams[i]->time_base = st->time_base;
  608. // If the muxer wants to shift timestamps, request to have them shifted
  609. // already before being handed to this muxer, so we don't have mismatches
  610. // between the MPD and the actual segments.
  611. s->avoid_negative_ts = ctx->avoid_negative_ts;
  612. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  613. c->has_video = 1;
  614. else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  615. c->has_audio = 1;
  616. set_codec_str(s, st->codecpar, os->codec_str, sizeof(os->codec_str));
  617. os->first_pts = AV_NOPTS_VALUE;
  618. os->max_pts = AV_NOPTS_VALUE;
  619. os->last_dts = AV_NOPTS_VALUE;
  620. os->segment_index = 1;
  621. }
  622. if (!c->has_video && c->min_seg_duration <= 0) {
  623. av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
  624. ret = AVERROR(EINVAL);
  625. }
  626. ret = write_manifest(s, 0);
  627. if (!ret)
  628. av_log(s, AV_LOG_VERBOSE, "Manifest written to: %s\n", s->filename);
  629. fail:
  630. if (ret)
  631. dash_free(s);
  632. return ret;
  633. }
  634. static int add_segment(OutputStream *os, const char *file,
  635. int64_t time, int duration,
  636. int64_t start_pos, int64_t range_length,
  637. int64_t index_length)
  638. {
  639. int err;
  640. Segment *seg;
  641. if (os->nb_segments >= os->segments_size) {
  642. os->segments_size = (os->segments_size + 1) * 2;
  643. if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
  644. os->segments_size)) < 0) {
  645. os->segments_size = 0;
  646. os->nb_segments = 0;
  647. return err;
  648. }
  649. }
  650. seg = av_mallocz(sizeof(*seg));
  651. if (!seg)
  652. return AVERROR(ENOMEM);
  653. av_strlcpy(seg->file, file, sizeof(seg->file));
  654. seg->time = time;
  655. seg->duration = duration;
  656. if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
  657. seg->duration += seg->time;
  658. seg->time = 0;
  659. }
  660. seg->start_pos = start_pos;
  661. seg->range_length = range_length;
  662. seg->index_length = index_length;
  663. os->segments[os->nb_segments++] = seg;
  664. os->segment_index++;
  665. return 0;
  666. }
  667. static void write_styp(AVIOContext *pb)
  668. {
  669. avio_wb32(pb, 24);
  670. ffio_wfourcc(pb, "styp");
  671. ffio_wfourcc(pb, "msdh");
  672. avio_wb32(pb, 0); /* minor */
  673. ffio_wfourcc(pb, "msdh");
  674. ffio_wfourcc(pb, "msix");
  675. }
  676. static void find_index_range(AVFormatContext *s, const char *full_path,
  677. int64_t pos, int *index_length)
  678. {
  679. uint8_t buf[8];
  680. AVIOContext *pb;
  681. int ret;
  682. ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
  683. if (ret < 0)
  684. return;
  685. if (avio_seek(pb, pos, SEEK_SET) != pos) {
  686. ff_format_io_close(s, &pb);
  687. return;
  688. }
  689. ret = avio_read(pb, buf, 8);
  690. ff_format_io_close(s, &pb);
  691. if (ret < 8)
  692. return;
  693. if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
  694. return;
  695. *index_length = AV_RB32(&buf[0]);
  696. }
  697. static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
  698. AVCodecParameters *par)
  699. {
  700. uint8_t *extradata;
  701. if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
  702. return 0;
  703. extradata = av_malloc(par->extradata_size);
  704. if (!extradata)
  705. return AVERROR(ENOMEM);
  706. memcpy(extradata, par->extradata, par->extradata_size);
  707. os->ctx->streams[0]->codecpar->extradata = extradata;
  708. os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
  709. set_codec_str(s, par, os->codec_str, sizeof(os->codec_str));
  710. return 0;
  711. }
  712. static int dash_flush(AVFormatContext *s, int final, int stream)
  713. {
  714. DASHContext *c = s->priv_data;
  715. int i, ret = 0;
  716. int cur_flush_segment_index = 0;
  717. if (stream >= 0)
  718. cur_flush_segment_index = c->streams[stream].segment_index;
  719. for (i = 0; i < s->nb_streams; i++) {
  720. OutputStream *os = &c->streams[i];
  721. char filename[1024] = "", full_path[1024], temp_path[1024];
  722. int64_t start_pos;
  723. int range_length, index_length = 0;
  724. if (!os->packets_written)
  725. continue;
  726. // Flush the single stream that got a keyframe right now.
  727. // Flush all audio streams as well, in sync with video keyframes,
  728. // but not the other video streams.
  729. if (stream >= 0 && i != stream) {
  730. if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
  731. continue;
  732. // Make sure we don't flush audio streams multiple times, when
  733. // all video streams are flushed one at a time.
  734. if (c->has_video && os->segment_index > cur_flush_segment_index)
  735. continue;
  736. }
  737. if (!os->init_range_length) {
  738. av_write_frame(os->ctx, NULL);
  739. os->init_range_length = avio_tell(os->ctx->pb);
  740. if (!c->single_file)
  741. ff_format_io_close(s, &os->out);
  742. }
  743. start_pos = avio_tell(os->ctx->pb);
  744. if (!c->single_file) {
  745. dash_fill_tmpl_params(filename, sizeof(filename), c->media_seg_name, i, os->segment_index, os->bit_rate, os->start_pts);
  746. snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
  747. snprintf(temp_path, sizeof(temp_path), "%s.tmp", full_path);
  748. ret = s->io_open(s, &os->out, temp_path, AVIO_FLAG_WRITE, NULL);
  749. if (ret < 0)
  750. break;
  751. write_styp(os->ctx->pb);
  752. } else {
  753. snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, os->initfile);
  754. }
  755. av_write_frame(os->ctx, NULL);
  756. avio_flush(os->ctx->pb);
  757. os->packets_written = 0;
  758. range_length = avio_tell(os->ctx->pb) - start_pos;
  759. if (c->single_file) {
  760. find_index_range(s, full_path, start_pos, &index_length);
  761. } else {
  762. ff_format_io_close(s, &os->out);
  763. ret = ff_rename(temp_path, full_path);
  764. if (ret < 0)
  765. break;
  766. }
  767. if (!os->bit_rate) {
  768. // calculate average bitrate of first segment
  769. int64_t bitrate = (int64_t) range_length * 8 * AV_TIME_BASE / (os->max_pts - os->start_pts);
  770. if (bitrate >= 0) {
  771. os->bit_rate = bitrate;
  772. snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
  773. " bandwidth=\"%d\"", os->bit_rate);
  774. }
  775. }
  776. add_segment(os, filename, os->start_pts, os->max_pts - os->start_pts, start_pos, range_length, index_length);
  777. av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, full_path);
  778. }
  779. if (c->window_size || (final && c->remove_at_exit)) {
  780. for (i = 0; i < s->nb_streams; i++) {
  781. OutputStream *os = &c->streams[i];
  782. int j;
  783. int remove = os->nb_segments - c->window_size - c->extra_window_size;
  784. if (final && c->remove_at_exit)
  785. remove = os->nb_segments;
  786. if (remove > 0) {
  787. for (j = 0; j < remove; j++) {
  788. char filename[1024];
  789. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
  790. unlink(filename);
  791. av_free(os->segments[j]);
  792. }
  793. os->nb_segments -= remove;
  794. memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
  795. }
  796. }
  797. }
  798. if (ret >= 0)
  799. ret = write_manifest(s, final);
  800. return ret;
  801. }
  802. static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
  803. {
  804. DASHContext *c = s->priv_data;
  805. AVStream *st = s->streams[pkt->stream_index];
  806. OutputStream *os = &c->streams[pkt->stream_index];
  807. int ret;
  808. ret = update_stream_extradata(s, os, st->codecpar);
  809. if (ret < 0)
  810. return ret;
  811. // Fill in a heuristic guess of the packet duration, if none is available.
  812. // The mp4 muxer will do something similar (for the last packet in a fragment)
  813. // if nothing is set (setting it for the other packets doesn't hurt).
  814. // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
  815. // invoke its heuristic (this doesn't have to be identical to that algorithm),
  816. // so that we know the exact timestamps of fragments.
  817. if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
  818. pkt->duration = pkt->dts - os->last_dts;
  819. os->last_dts = pkt->dts;
  820. // If forcing the stream to start at 0, the mp4 muxer will set the start
  821. // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
  822. if (os->first_pts == AV_NOPTS_VALUE &&
  823. s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
  824. pkt->pts -= pkt->dts;
  825. pkt->dts = 0;
  826. }
  827. if (os->first_pts == AV_NOPTS_VALUE)
  828. os->first_pts = pkt->pts;
  829. if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
  830. pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
  831. av_compare_ts(pkt->pts - os->start_pts, st->time_base,
  832. c->min_seg_duration, AV_TIME_BASE_Q) >= 0) {
  833. int64_t prev_duration = c->last_duration;
  834. c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
  835. st->time_base,
  836. AV_TIME_BASE_Q);
  837. c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
  838. st->time_base,
  839. AV_TIME_BASE_Q);
  840. if ((!c->use_timeline || !c->use_template) && prev_duration) {
  841. if (c->last_duration < prev_duration*9/10 ||
  842. c->last_duration > prev_duration*11/10) {
  843. av_log(s, AV_LOG_WARNING,
  844. "Segment durations differ too much, enable use_timeline "
  845. "and use_template, or keep a stricter keyframe interval\n");
  846. }
  847. }
  848. if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
  849. return ret;
  850. }
  851. if (!os->packets_written) {
  852. // If we wrote a previous segment, adjust the start time of the segment
  853. // to the end of the previous one (which is the same as the mp4 muxer
  854. // does). This avoids gaps in the timeline.
  855. if (os->max_pts != AV_NOPTS_VALUE)
  856. os->start_pts = os->max_pts;
  857. else
  858. os->start_pts = pkt->pts;
  859. }
  860. if (os->max_pts == AV_NOPTS_VALUE)
  861. os->max_pts = pkt->pts + pkt->duration;
  862. else
  863. os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
  864. os->packets_written++;
  865. return ff_write_chained(os->ctx, 0, pkt, s);
  866. }
  867. static int dash_write_trailer(AVFormatContext *s)
  868. {
  869. DASHContext *c = s->priv_data;
  870. if (s->nb_streams > 0) {
  871. OutputStream *os = &c->streams[0];
  872. // If no segments have been written so far, try to do a crude
  873. // guess of the segment duration
  874. if (!c->last_duration)
  875. c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
  876. s->streams[0]->time_base,
  877. AV_TIME_BASE_Q);
  878. c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
  879. s->streams[0]->time_base,
  880. AV_TIME_BASE_Q);
  881. }
  882. dash_flush(s, 1, -1);
  883. if (c->remove_at_exit) {
  884. char filename[1024];
  885. int i;
  886. for (i = 0; i < s->nb_streams; i++) {
  887. OutputStream *os = &c->streams[i];
  888. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
  889. unlink(filename);
  890. }
  891. unlink(s->filename);
  892. }
  893. dash_free(s);
  894. return 0;
  895. }
  896. #define OFFSET(x) offsetof(DASHContext, x)
  897. #define E AV_OPT_FLAG_ENCODING_PARAM
  898. static const AVOption options[] = {
  899. { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
  900. { "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 },
  901. { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
  902. { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
  903. { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
  904. { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
  905. { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
  906. { "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 },
  907. { "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 },
  908. { "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 },
  909. { "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, AV_OPT_FLAG_ENCODING_PARAM },
  910. { NULL },
  911. };
  912. static const AVClass dash_class = {
  913. .class_name = "dash muxer",
  914. .item_name = av_default_item_name,
  915. .option = options,
  916. .version = LIBAVUTIL_VERSION_INT,
  917. };
  918. AVOutputFormat ff_dash_muxer = {
  919. .name = "dash",
  920. .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
  921. .priv_data_size = sizeof(DASHContext),
  922. .audio_codec = AV_CODEC_ID_AAC,
  923. .video_codec = AV_CODEC_ID_H264,
  924. .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
  925. .write_header = dash_write_header,
  926. .write_packet = dash_write_packet,
  927. .write_trailer = dash_write_trailer,
  928. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  929. .priv_class = &dash_class,
  930. };