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.

936 lines
35KB

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