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.

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