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.

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