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.

1035 lines
39KB

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