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.

965 lines
36KB

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