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.

795 lines
29KB

  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. typedef struct Segment {
  38. char file[1024];
  39. int64_t start_pos;
  40. int range_length, index_length;
  41. int64_t time;
  42. int duration;
  43. int n;
  44. } Segment;
  45. typedef struct OutputStream {
  46. AVFormatContext *ctx;
  47. int ctx_inited;
  48. uint8_t iobuf[32768];
  49. URLContext *out;
  50. int packets_written;
  51. char initfile[1024];
  52. int64_t init_start_pos;
  53. int init_range_length;
  54. int nb_segments, segments_size, segment_index;
  55. Segment **segments;
  56. int64_t first_dts, start_dts, end_dts;
  57. char bandwidth_str[64];
  58. char codec_str[100];
  59. } OutputStream;
  60. typedef struct DASHContext {
  61. const AVClass *class; /* Class for private options. */
  62. int window_size;
  63. int extra_window_size;
  64. int min_seg_duration;
  65. int remove_at_exit;
  66. int use_template;
  67. int use_timeline;
  68. int single_file;
  69. OutputStream *streams;
  70. int has_video, has_audio;
  71. int last_duration;
  72. int total_duration;
  73. char availability_start_time[100];
  74. char dirname[1024];
  75. } DASHContext;
  76. static int dash_write(void *opaque, uint8_t *buf, int buf_size)
  77. {
  78. OutputStream *os = opaque;
  79. if (os->out)
  80. ffurl_write(os->out, buf, buf_size);
  81. return buf_size;
  82. }
  83. // RFC 6381
  84. static void set_codec_str(AVFormatContext *s, AVCodecContext *codec,
  85. char *str, int size)
  86. {
  87. const AVCodecTag *tags[2] = { NULL, NULL };
  88. uint32_t tag;
  89. if (codec->codec_type == AVMEDIA_TYPE_VIDEO)
  90. tags[0] = ff_codec_movvideo_tags;
  91. else if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
  92. tags[0] = ff_codec_movaudio_tags;
  93. else
  94. return;
  95. tag = av_codec_get_tag(tags, codec->codec_id);
  96. if (!tag)
  97. return;
  98. if (size < 5)
  99. return;
  100. AV_WL32(str, tag);
  101. str[4] = '\0';
  102. if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
  103. uint32_t oti;
  104. tags[0] = ff_mp4_obj_type;
  105. oti = av_codec_get_tag(tags, codec->codec_id);
  106. if (oti)
  107. av_strlcatf(str, size, ".%02x", oti);
  108. else
  109. return;
  110. if (tag == MKTAG('m', 'p', '4', 'a')) {
  111. if (codec->extradata_size >= 2) {
  112. int aot = codec->extradata[0] >> 3;
  113. if (aot == 31)
  114. aot = ((AV_RB16(codec->extradata) >> 5) & 0x3f) + 32;
  115. av_strlcatf(str, size, ".%d", aot);
  116. }
  117. } else if (tag == MKTAG('m', 'p', '4', 'v')) {
  118. // Unimplemented, should output ProfileLevelIndication as a decimal number
  119. av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
  120. }
  121. } else if (!strcmp(str, "avc1")) {
  122. uint8_t *tmpbuf = NULL;
  123. uint8_t *extradata = codec->extradata;
  124. int extradata_size = codec->extradata_size;
  125. if (!extradata_size)
  126. return;
  127. if (extradata[0] != 1) {
  128. AVIOContext *pb;
  129. if (avio_open_dyn_buf(&pb) < 0)
  130. return;
  131. if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
  132. avio_close_dyn_buf(pb, &tmpbuf);
  133. av_free(tmpbuf);
  134. return;
  135. }
  136. extradata_size = avio_close_dyn_buf(pb, &extradata);
  137. tmpbuf = extradata;
  138. }
  139. if (extradata_size >= 4)
  140. av_strlcatf(str, size, ".%02x%02x%02x",
  141. extradata[1], extradata[2], extradata[3]);
  142. av_free(tmpbuf);
  143. }
  144. }
  145. static void dash_free(AVFormatContext *s)
  146. {
  147. DASHContext *c = s->priv_data;
  148. int i, j;
  149. if (!c->streams)
  150. return;
  151. for (i = 0; i < s->nb_streams; i++) {
  152. OutputStream *os = &c->streams[i];
  153. if (os->ctx && os->ctx_inited)
  154. av_write_trailer(os->ctx);
  155. if (os->ctx && os->ctx->pb)
  156. av_free(os->ctx->pb);
  157. ffurl_close(os->out);
  158. os->out = NULL;
  159. if (os->ctx)
  160. avformat_free_context(os->ctx);
  161. for (j = 0; j < os->nb_segments; j++)
  162. av_free(os->segments[j]);
  163. av_free(os->segments);
  164. }
  165. av_freep(&c->streams);
  166. }
  167. static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c)
  168. {
  169. int i, start_index = 0, start_number = 1;
  170. if (c->window_size) {
  171. start_index = FFMAX(os->nb_segments - c->window_size, 0);
  172. start_number = FFMAX(os->segment_index - c->window_size, 1);
  173. }
  174. if (c->use_template) {
  175. int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
  176. avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
  177. if (!c->use_timeline)
  178. avio_printf(out, "duration=\"%d\" ", c->last_duration);
  179. avio_printf(out, "initialization=\"init-stream$RepresentationID$.m4s\" media=\"chunk-stream$RepresentationID$-$Number%%05d$.m4s\" startNumber=\"%d\">\n", c->use_timeline ? start_number : 1);
  180. if (c->use_timeline) {
  181. avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
  182. for (i = start_index; i < os->nb_segments; ) {
  183. Segment *seg = os->segments[i];
  184. int repeat = 0;
  185. avio_printf(out, "\t\t\t\t\t\t<S ");
  186. if (i == start_index)
  187. avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
  188. avio_printf(out, "d=\"%d\" ", seg->duration);
  189. while (i + repeat + 1 < os->nb_segments && os->segments[i + repeat + 1]->duration == seg->duration)
  190. repeat++;
  191. if (repeat > 0)
  192. avio_printf(out, "r=\"%d\" ", repeat);
  193. avio_printf(out, "/>\n");
  194. i += 1 + repeat;
  195. }
  196. avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
  197. }
  198. avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
  199. } else if (c->single_file) {
  200. avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
  201. avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%d\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
  202. 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);
  203. for (i = start_index; i < os->nb_segments; i++) {
  204. Segment *seg = os->segments[i];
  205. avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
  206. if (seg->index_length)
  207. avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
  208. avio_printf(out, "/>\n");
  209. }
  210. avio_printf(out, "\t\t\t\t</SegmentList>\n");
  211. } else {
  212. avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%d\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
  213. avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
  214. for (i = start_index; i < os->nb_segments; i++) {
  215. Segment *seg = os->segments[i];
  216. avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
  217. }
  218. avio_printf(out, "\t\t\t\t</SegmentList>\n");
  219. }
  220. }
  221. static char *xmlescape(const char *str) {
  222. int outlen = strlen(str)*3/2 + 6;
  223. char *out = av_realloc(NULL, outlen + 1);
  224. int pos = 0;
  225. if (!out)
  226. return NULL;
  227. for (; *str; str++) {
  228. if (pos + 6 > outlen) {
  229. char *tmp;
  230. outlen = 2 * outlen + 6;
  231. tmp = av_realloc(out, outlen + 1);
  232. if (!tmp) {
  233. av_free(out);
  234. return NULL;
  235. }
  236. out = tmp;
  237. }
  238. if (*str == '&') {
  239. memcpy(&out[pos], "&amp;", 5);
  240. pos += 5;
  241. } else if (*str == '<') {
  242. memcpy(&out[pos], "&lt;", 4);
  243. pos += 4;
  244. } else if (*str == '>') {
  245. memcpy(&out[pos], "&gt;", 4);
  246. pos += 4;
  247. } else if (*str == '\'') {
  248. memcpy(&out[pos], "&apos;", 6);
  249. pos += 6;
  250. } else if (*str == '\"') {
  251. memcpy(&out[pos], "&quot;", 6);
  252. pos += 6;
  253. } else {
  254. out[pos++] = *str;
  255. }
  256. }
  257. out[pos] = '\0';
  258. return out;
  259. }
  260. static void write_time(AVIOContext *out, int64_t time)
  261. {
  262. int seconds = time / AV_TIME_BASE;
  263. int fractions = time % AV_TIME_BASE;
  264. int minutes = seconds / 60;
  265. int hours = minutes / 60;
  266. seconds %= 60;
  267. minutes %= 60;
  268. avio_printf(out, "PT");
  269. if (hours)
  270. avio_printf(out, "%dH", hours);
  271. if (hours || minutes)
  272. avio_printf(out, "%dM", minutes);
  273. avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
  274. }
  275. static int write_manifest(AVFormatContext *s, int final)
  276. {
  277. DASHContext *c = s->priv_data;
  278. AVIOContext *out;
  279. char temp_filename[1024];
  280. int ret, i;
  281. AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
  282. snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", s->filename);
  283. ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
  284. if (ret < 0) {
  285. av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
  286. return ret;
  287. }
  288. avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  289. avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
  290. "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
  291. "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
  292. "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
  293. "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
  294. "\ttype=\"%s\"\n", final ? "static" : "dynamic");
  295. if (final) {
  296. avio_printf(out, "\tmediaPresentationDuration=\"");
  297. write_time(out, c->total_duration);
  298. avio_printf(out, "\"\n");
  299. } else {
  300. int update_period = c->last_duration / AV_TIME_BASE;
  301. if (c->use_template && !c->use_timeline)
  302. update_period = 500;
  303. avio_printf(out, "\tminimumUpdatePeriod=\"PT%dS\"\n", update_period);
  304. avio_printf(out, "\tsuggestedPresentationDelay=\"PT%dS\"\n", c->last_duration / AV_TIME_BASE);
  305. if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
  306. time_t t = time(NULL);
  307. struct tm *ptm, tmbuf;
  308. ptm = gmtime_r(&t, &tmbuf);
  309. if (ptm) {
  310. if (!strftime(c->availability_start_time, sizeof(c->availability_start_time),
  311. "%Y-%m-%dT%H:%M:%S", ptm))
  312. c->availability_start_time[0] = '\0';
  313. }
  314. }
  315. if (c->availability_start_time[0])
  316. avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
  317. if (c->window_size && c->use_template) {
  318. avio_printf(out, "\ttimeShiftBufferDepth=\"");
  319. write_time(out, c->last_duration * c->window_size);
  320. avio_printf(out, "\"\n");
  321. }
  322. }
  323. avio_printf(out, "\tminBufferTime=\"");
  324. write_time(out, c->last_duration);
  325. avio_printf(out, "\">\n");
  326. avio_printf(out, "\t<ProgramInformation>\n");
  327. if (title) {
  328. char *escaped = xmlescape(title->value);
  329. avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
  330. av_free(escaped);
  331. }
  332. avio_printf(out, "\t</ProgramInformation>\n");
  333. if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
  334. OutputStream *os = &c->streams[0];
  335. int start_index = FFMAX(os->nb_segments - c->window_size, 0);
  336. int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
  337. avio_printf(out, "\t<Period start=\"");
  338. write_time(out, start_time);
  339. avio_printf(out, "\">\n");
  340. } else {
  341. avio_printf(out, "\t<Period start=\"PT0.0S\">\n");
  342. }
  343. if (c->has_video) {
  344. avio_printf(out, "\t\t<AdaptationSet id=\"video\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n");
  345. for (i = 0; i < s->nb_streams; i++) {
  346. AVStream *st = s->streams[i];
  347. OutputStream *os = &c->streams[i];
  348. if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
  349. continue;
  350. 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);
  351. output_segment_list(&c->streams[i], out, c);
  352. avio_printf(out, "\t\t\t</Representation>\n");
  353. }
  354. avio_printf(out, "\t\t</AdaptationSet>\n");
  355. }
  356. if (c->has_audio) {
  357. avio_printf(out, "\t\t<AdaptationSet id=\"audio\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n");
  358. for (i = 0; i < s->nb_streams; i++) {
  359. AVStream *st = s->streams[i];
  360. OutputStream *os = &c->streams[i];
  361. if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
  362. continue;
  363. 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);
  364. avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n", st->codec->channels);
  365. output_segment_list(&c->streams[i], out, c);
  366. avio_printf(out, "\t\t\t</Representation>\n");
  367. }
  368. avio_printf(out, "\t\t</AdaptationSet>\n");
  369. }
  370. avio_printf(out, "\t</Period>\n");
  371. avio_printf(out, "</MPD>\n");
  372. avio_flush(out);
  373. avio_close(out);
  374. return ff_rename(temp_filename, s->filename);
  375. }
  376. static int dash_write_header(AVFormatContext *s)
  377. {
  378. DASHContext *c = s->priv_data;
  379. int ret = 0, i;
  380. AVOutputFormat *oformat;
  381. char *ptr;
  382. char basename[1024];
  383. if (c->single_file)
  384. c->use_template = 0;
  385. av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
  386. ptr = strrchr(c->dirname, '/');
  387. if (ptr) {
  388. av_strlcpy(basename, &ptr[1], sizeof(basename));
  389. ptr[1] = '\0';
  390. } else {
  391. c->dirname[0] = '\0';
  392. av_strlcpy(basename, s->filename, sizeof(basename));
  393. }
  394. ptr = strrchr(basename, '.');
  395. if (ptr)
  396. *ptr = '\0';
  397. oformat = av_guess_format("mp4", NULL, NULL);
  398. if (!oformat) {
  399. ret = AVERROR_MUXER_NOT_FOUND;
  400. goto fail;
  401. }
  402. c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
  403. if (!c->streams) {
  404. ret = AVERROR(ENOMEM);
  405. goto fail;
  406. }
  407. for (i = 0; i < s->nb_streams; i++) {
  408. OutputStream *os = &c->streams[i];
  409. AVFormatContext *ctx;
  410. AVStream *st;
  411. AVDictionary *opts = NULL;
  412. char filename[1024];
  413. if (s->streams[i]->codec->bit_rate) {
  414. snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
  415. " bandwidth=\"%d\"", s->streams[i]->codec->bit_rate);
  416. } else {
  417. int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
  418. AV_LOG_ERROR : AV_LOG_WARNING;
  419. av_log(s, level, "No bit rate set for stream %d\n", i);
  420. if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
  421. ret = AVERROR(EINVAL);
  422. goto fail;
  423. }
  424. }
  425. ctx = avformat_alloc_context();
  426. if (!ctx) {
  427. ret = AVERROR(ENOMEM);
  428. goto fail;
  429. }
  430. os->ctx = ctx;
  431. ctx->oformat = oformat;
  432. ctx->interrupt_callback = s->interrupt_callback;
  433. if (!(st = avformat_new_stream(ctx, NULL))) {
  434. ret = AVERROR(ENOMEM);
  435. goto fail;
  436. }
  437. avcodec_copy_context(st->codec, s->streams[i]->codec);
  438. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  439. st->time_base = s->streams[i]->time_base;
  440. ctx->avoid_negative_ts = s->avoid_negative_ts;
  441. ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, dash_write, NULL);
  442. if (!ctx->pb) {
  443. ret = AVERROR(ENOMEM);
  444. goto fail;
  445. }
  446. if (c->single_file)
  447. snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
  448. else
  449. snprintf(os->initfile, sizeof(os->initfile), "init-stream%d.m4s", i);
  450. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
  451. ret = ffurl_open(&os->out, filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
  452. if (ret < 0)
  453. goto fail;
  454. os->init_start_pos = 0;
  455. av_dict_set(&opts, "movflags", "frag_custom+dash", 0);
  456. if ((ret = avformat_write_header(ctx, &opts)) < 0) {
  457. goto fail;
  458. }
  459. os->ctx_inited = 1;
  460. avio_flush(ctx->pb);
  461. av_dict_free(&opts);
  462. if (c->single_file) {
  463. os->init_range_length = avio_tell(ctx->pb);
  464. } else {
  465. ffurl_close(os->out);
  466. os->out = NULL;
  467. }
  468. s->streams[i]->time_base = st->time_base;
  469. // If the muxer wants to shift timestamps, request to have them shifted
  470. // already before being handed to this muxer, so we don't have mismatches
  471. // between the MPD and the actual segments.
  472. s->avoid_negative_ts = ctx->avoid_negative_ts;
  473. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  474. c->has_video = 1;
  475. else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  476. c->has_audio = 1;
  477. set_codec_str(s, os->ctx->streams[0]->codec, os->codec_str, sizeof(os->codec_str));
  478. os->first_dts = AV_NOPTS_VALUE;
  479. os->segment_index = 1;
  480. }
  481. if (!c->has_video && c->min_seg_duration <= 0) {
  482. av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
  483. ret = AVERROR(EINVAL);
  484. }
  485. ret = write_manifest(s, 0);
  486. fail:
  487. if (ret)
  488. dash_free(s);
  489. return ret;
  490. }
  491. static int add_segment(OutputStream *os, const char *file,
  492. int64_t time, int duration,
  493. int64_t start_pos, int64_t range_length,
  494. int64_t index_length)
  495. {
  496. int err;
  497. Segment *seg;
  498. if (os->nb_segments >= os->segments_size) {
  499. os->segments_size = (os->segments_size + 1) * 2;
  500. if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
  501. os->segments_size)) < 0) {
  502. os->segments_size = 0;
  503. os->nb_segments = 0;
  504. return err;
  505. }
  506. }
  507. seg = av_mallocz(sizeof(*seg));
  508. if (!seg)
  509. return AVERROR(ENOMEM);
  510. av_strlcpy(seg->file, file, sizeof(seg->file));
  511. seg->time = time;
  512. seg->duration = duration;
  513. seg->start_pos = start_pos;
  514. seg->range_length = range_length;
  515. seg->index_length = index_length;
  516. os->segments[os->nb_segments++] = seg;
  517. os->segment_index++;
  518. return 0;
  519. }
  520. static void write_styp(AVIOContext *pb)
  521. {
  522. avio_wb32(pb, 24);
  523. ffio_wfourcc(pb, "styp");
  524. ffio_wfourcc(pb, "msdh");
  525. avio_wb32(pb, 0); /* minor */
  526. ffio_wfourcc(pb, "msdh");
  527. ffio_wfourcc(pb, "msix");
  528. }
  529. static void find_index_range(AVFormatContext *s, const char *dirname,
  530. const char *filename, int64_t pos,
  531. int *index_length)
  532. {
  533. char full_path[1024];
  534. uint8_t buf[8];
  535. URLContext *fd;
  536. int ret;
  537. snprintf(full_path, sizeof(full_path), "%s%s", dirname, filename);
  538. ret = ffurl_open(&fd, full_path, AVIO_FLAG_READ, &s->interrupt_callback, NULL);
  539. if (ret < 0)
  540. return;
  541. if (ffurl_seek(fd, pos, SEEK_SET) != pos) {
  542. ffurl_close(fd);
  543. return;
  544. }
  545. ret = ffurl_read(fd, buf, 8);
  546. ffurl_close(fd);
  547. if (ret < 8)
  548. return;
  549. if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
  550. return;
  551. *index_length = AV_RB32(&buf[0]);
  552. }
  553. static int dash_flush(AVFormatContext *s, int final, int stream)
  554. {
  555. DASHContext *c = s->priv_data;
  556. int i, ret = 0;
  557. int cur_flush_segment_index = 0;
  558. if (stream >= 0)
  559. cur_flush_segment_index = c->streams[stream].segment_index;
  560. for (i = 0; i < s->nb_streams; i++) {
  561. OutputStream *os = &c->streams[i];
  562. char filename[1024] = "", full_path[1024], temp_path[1024];
  563. int64_t start_pos = avio_tell(os->ctx->pb);
  564. int range_length, index_length = 0;
  565. if (!os->packets_written)
  566. continue;
  567. // Flush the single stream that got a keyframe right now.
  568. // Flush all audio streams as well, in sync with video keyframes,
  569. // but not the other video streams.
  570. if (stream >= 0 && i != stream) {
  571. if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
  572. continue;
  573. // Make sure we don't flush audio streams multiple times, when
  574. // all video streams are flushed one at a time.
  575. if (c->has_video && os->segment_index > cur_flush_segment_index)
  576. continue;
  577. }
  578. if (!c->single_file) {
  579. snprintf(filename, sizeof(filename), "chunk-stream%d-%05d.m4s", i, os->segment_index);
  580. snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
  581. snprintf(temp_path, sizeof(temp_path), "%s.tmp", full_path);
  582. ret = ffurl_open(&os->out, temp_path, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
  583. if (ret < 0)
  584. break;
  585. write_styp(os->ctx->pb);
  586. }
  587. av_write_frame(os->ctx, NULL);
  588. avio_flush(os->ctx->pb);
  589. os->packets_written = 0;
  590. range_length = avio_tell(os->ctx->pb) - start_pos;
  591. if (c->single_file) {
  592. find_index_range(s, c->dirname, os->initfile, start_pos, &index_length);
  593. } else {
  594. ffurl_close(os->out);
  595. os->out = NULL;
  596. ret = ff_rename(temp_path, full_path);
  597. if (ret < 0)
  598. break;
  599. }
  600. add_segment(os, filename, os->start_dts, os->end_dts - os->start_dts, start_pos, range_length, index_length);
  601. }
  602. if (c->window_size || (final && c->remove_at_exit)) {
  603. for (i = 0; i < s->nb_streams; i++) {
  604. OutputStream *os = &c->streams[i];
  605. int j;
  606. int remove = os->nb_segments - c->window_size - c->extra_window_size;
  607. if (final && c->remove_at_exit)
  608. remove = os->nb_segments;
  609. if (remove > 0) {
  610. for (j = 0; j < remove; j++) {
  611. char filename[1024];
  612. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
  613. unlink(filename);
  614. av_free(os->segments[j]);
  615. }
  616. os->nb_segments -= remove;
  617. memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
  618. }
  619. }
  620. }
  621. if (ret >= 0)
  622. ret = write_manifest(s, final);
  623. return ret;
  624. }
  625. static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
  626. {
  627. DASHContext *c = s->priv_data;
  628. AVStream *st = s->streams[pkt->stream_index];
  629. OutputStream *os = &c->streams[pkt->stream_index];
  630. int64_t seg_end_duration = (os->segment_index) * (int64_t) c->min_seg_duration;
  631. int ret;
  632. // If forcing the stream to start at 0, the mp4 muxer will set the start
  633. // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
  634. if (os->first_dts == AV_NOPTS_VALUE &&
  635. s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
  636. pkt->pts -= pkt->dts;
  637. pkt->dts = 0;
  638. }
  639. if (os->first_dts == AV_NOPTS_VALUE)
  640. os->first_dts = pkt->dts;
  641. if ((!c->has_video || st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
  642. pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
  643. av_compare_ts(pkt->dts - os->first_dts, st->time_base,
  644. seg_end_duration, AV_TIME_BASE_Q) >= 0) {
  645. int64_t prev_duration = c->last_duration;
  646. c->last_duration = av_rescale_q(pkt->dts - os->start_dts,
  647. st->time_base,
  648. AV_TIME_BASE_Q);
  649. c->total_duration = av_rescale_q(pkt->dts - os->first_dts,
  650. st->time_base,
  651. AV_TIME_BASE_Q);
  652. if ((!c->use_timeline || !c->use_template) && prev_duration) {
  653. if (c->last_duration < prev_duration*9/10 ||
  654. c->last_duration > prev_duration*11/10) {
  655. av_log(s, AV_LOG_WARNING,
  656. "Segment durations differ too much, enable use_timeline "
  657. "and use_template, or keep a stricter keyframe interval\n");
  658. }
  659. }
  660. if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
  661. return ret;
  662. }
  663. if (!os->packets_written)
  664. os->start_dts = pkt->dts;
  665. os->end_dts = pkt->dts + pkt->duration;
  666. os->packets_written++;
  667. return ff_write_chained(os->ctx, 0, pkt, s);
  668. }
  669. static int dash_write_trailer(AVFormatContext *s)
  670. {
  671. DASHContext *c = s->priv_data;
  672. if (s->nb_streams > 0) {
  673. OutputStream *os = &c->streams[0];
  674. // If no segments have been written so far, try to do a crude
  675. // guess of the segment duration
  676. if (!c->last_duration)
  677. c->last_duration = av_rescale_q(os->end_dts - os->start_dts,
  678. s->streams[0]->time_base,
  679. AV_TIME_BASE_Q);
  680. c->total_duration = av_rescale_q(os->end_dts - os->first_dts,
  681. s->streams[0]->time_base,
  682. AV_TIME_BASE_Q);
  683. }
  684. dash_flush(s, 1, -1);
  685. if (c->remove_at_exit) {
  686. char filename[1024];
  687. int i;
  688. for (i = 0; i < s->nb_streams; i++) {
  689. OutputStream *os = &c->streams[i];
  690. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
  691. unlink(filename);
  692. }
  693. unlink(s->filename);
  694. }
  695. dash_free(s);
  696. return 0;
  697. }
  698. #define OFFSET(x) offsetof(DASHContext, x)
  699. #define E AV_OPT_FLAG_ENCODING_PARAM
  700. static const AVOption options[] = {
  701. { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
  702. { "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 },
  703. { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
  704. { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
  705. { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
  706. { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
  707. { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
  708. { NULL },
  709. };
  710. static const AVClass dash_class = {
  711. .class_name = "dash muxer",
  712. .item_name = av_default_item_name,
  713. .option = options,
  714. .version = LIBAVUTIL_VERSION_INT,
  715. };
  716. AVOutputFormat ff_dash_muxer = {
  717. .name = "dash",
  718. .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
  719. .priv_data_size = sizeof(DASHContext),
  720. .audio_codec = AV_CODEC_ID_AAC,
  721. .video_codec = AV_CODEC_ID_H264,
  722. .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
  723. .write_header = dash_write_header,
  724. .write_packet = dash_write_packet,
  725. .write_trailer = dash_write_trailer,
  726. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  727. .priv_class = &dash_class,
  728. };