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.

948 lines
36KB

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