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.

799 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. const char *write_filename;
  281. int ret, i;
  282. AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
  283. snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", s->filename);
  284. write_filename = USE_RENAME_REPLACE ? temp_filename : s->filename;
  285. ret = avio_open2(&out, write_filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
  286. if (ret < 0) {
  287. av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", write_filename);
  288. return ret;
  289. }
  290. avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  291. avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
  292. "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
  293. "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
  294. "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
  295. "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
  296. "\ttype=\"%s\"\n", final ? "static" : "dynamic");
  297. if (final) {
  298. avio_printf(out, "\tmediaPresentationDuration=\"");
  299. write_time(out, c->total_duration);
  300. avio_printf(out, "\"\n");
  301. } else {
  302. int update_period = c->last_duration / AV_TIME_BASE;
  303. if (c->use_template && !c->use_timeline)
  304. update_period = 500;
  305. avio_printf(out, "\tminimumUpdatePeriod=\"PT%dS\"\n", update_period);
  306. avio_printf(out, "\tsuggestedPresentationDelay=\"PT%dS\"\n", c->last_duration / AV_TIME_BASE);
  307. if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
  308. time_t t = time(NULL);
  309. struct tm *ptm, tmbuf;
  310. ptm = gmtime_r(&t, &tmbuf);
  311. if (ptm) {
  312. if (!strftime(c->availability_start_time, sizeof(c->availability_start_time),
  313. "%Y-%m-%dT%H:%M:%S", ptm))
  314. c->availability_start_time[0] = '\0';
  315. }
  316. }
  317. if (c->availability_start_time[0])
  318. avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
  319. if (c->window_size && c->use_template) {
  320. avio_printf(out, "\ttimeShiftBufferDepth=\"");
  321. write_time(out, c->last_duration * c->window_size);
  322. avio_printf(out, "\"\n");
  323. }
  324. }
  325. avio_printf(out, "\tminBufferTime=\"");
  326. write_time(out, c->last_duration);
  327. avio_printf(out, "\">\n");
  328. avio_printf(out, "\t<ProgramInformation>\n");
  329. if (title) {
  330. char *escaped = xmlescape(title->value);
  331. avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
  332. av_free(escaped);
  333. }
  334. avio_printf(out, "\t</ProgramInformation>\n");
  335. if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
  336. OutputStream *os = &c->streams[0];
  337. int start_index = FFMAX(os->nb_segments - c->window_size, 0);
  338. int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
  339. avio_printf(out, "\t<Period start=\"");
  340. write_time(out, start_time);
  341. avio_printf(out, "\">\n");
  342. } else {
  343. avio_printf(out, "\t<Period start=\"PT0.0S\">\n");
  344. }
  345. if (c->has_video) {
  346. avio_printf(out, "\t\t<AdaptationSet id=\"video\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n");
  347. for (i = 0; i < s->nb_streams; i++) {
  348. AVStream *st = s->streams[i];
  349. OutputStream *os = &c->streams[i];
  350. if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
  351. continue;
  352. 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);
  353. output_segment_list(&c->streams[i], out, c);
  354. avio_printf(out, "\t\t\t</Representation>\n");
  355. }
  356. avio_printf(out, "\t\t</AdaptationSet>\n");
  357. }
  358. if (c->has_audio) {
  359. avio_printf(out, "\t\t<AdaptationSet id=\"audio\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n");
  360. for (i = 0; i < s->nb_streams; i++) {
  361. AVStream *st = s->streams[i];
  362. OutputStream *os = &c->streams[i];
  363. if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
  364. continue;
  365. 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);
  366. avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n", st->codec->channels);
  367. output_segment_list(&c->streams[i], out, c);
  368. avio_printf(out, "\t\t\t</Representation>\n");
  369. }
  370. avio_printf(out, "\t\t</AdaptationSet>\n");
  371. }
  372. avio_printf(out, "\t</Period>\n");
  373. avio_printf(out, "</MPD>\n");
  374. avio_flush(out);
  375. avio_close(out);
  376. return USE_RENAME_REPLACE ? ff_rename(temp_filename, s->filename) : 0;
  377. }
  378. static int dash_write_header(AVFormatContext *s)
  379. {
  380. DASHContext *c = s->priv_data;
  381. int ret = 0, i;
  382. AVOutputFormat *oformat;
  383. char *ptr;
  384. char basename[1024];
  385. if (c->single_file)
  386. c->use_template = 0;
  387. av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
  388. ptr = strrchr(c->dirname, '/');
  389. if (ptr) {
  390. av_strlcpy(basename, &ptr[1], sizeof(basename));
  391. ptr[1] = '\0';
  392. } else {
  393. c->dirname[0] = '\0';
  394. av_strlcpy(basename, s->filename, sizeof(basename));
  395. }
  396. ptr = strrchr(basename, '.');
  397. if (ptr)
  398. *ptr = '\0';
  399. oformat = av_guess_format("mp4", NULL, NULL);
  400. if (!oformat) {
  401. ret = AVERROR_MUXER_NOT_FOUND;
  402. goto fail;
  403. }
  404. c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
  405. if (!c->streams) {
  406. ret = AVERROR(ENOMEM);
  407. goto fail;
  408. }
  409. for (i = 0; i < s->nb_streams; i++) {
  410. OutputStream *os = &c->streams[i];
  411. AVFormatContext *ctx;
  412. AVStream *st;
  413. AVDictionary *opts = NULL;
  414. char filename[1024];
  415. if (s->streams[i]->codec->bit_rate) {
  416. snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
  417. " bandwidth=\"%d\"", s->streams[i]->codec->bit_rate);
  418. } else {
  419. int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
  420. AV_LOG_ERROR : AV_LOG_WARNING;
  421. av_log(s, level, "No bit rate set for stream %d\n", i);
  422. if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
  423. ret = AVERROR(EINVAL);
  424. goto fail;
  425. }
  426. }
  427. ctx = avformat_alloc_context();
  428. if (!ctx) {
  429. ret = AVERROR(ENOMEM);
  430. goto fail;
  431. }
  432. os->ctx = ctx;
  433. ctx->oformat = oformat;
  434. ctx->interrupt_callback = s->interrupt_callback;
  435. if (!(st = avformat_new_stream(ctx, NULL))) {
  436. ret = AVERROR(ENOMEM);
  437. goto fail;
  438. }
  439. avcodec_copy_context(st->codec, s->streams[i]->codec);
  440. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  441. st->time_base = s->streams[i]->time_base;
  442. ctx->avoid_negative_ts = s->avoid_negative_ts;
  443. ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, dash_write, NULL);
  444. if (!ctx->pb) {
  445. ret = AVERROR(ENOMEM);
  446. goto fail;
  447. }
  448. if (c->single_file)
  449. snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
  450. else
  451. snprintf(os->initfile, sizeof(os->initfile), "init-stream%d.m4s", i);
  452. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
  453. ret = ffurl_open(&os->out, filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
  454. if (ret < 0)
  455. goto fail;
  456. os->init_start_pos = 0;
  457. av_dict_set(&opts, "movflags", "frag_custom+dash", 0);
  458. if ((ret = avformat_write_header(ctx, &opts)) < 0) {
  459. goto fail;
  460. }
  461. os->ctx_inited = 1;
  462. avio_flush(ctx->pb);
  463. av_dict_free(&opts);
  464. if (c->single_file) {
  465. os->init_range_length = avio_tell(ctx->pb);
  466. } else {
  467. ffurl_close(os->out);
  468. os->out = NULL;
  469. }
  470. s->streams[i]->time_base = st->time_base;
  471. // If the muxer wants to shift timestamps, request to have them shifted
  472. // already before being handed to this muxer, so we don't have mismatches
  473. // between the MPD and the actual segments.
  474. s->avoid_negative_ts = ctx->avoid_negative_ts;
  475. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  476. c->has_video = 1;
  477. else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  478. c->has_audio = 1;
  479. set_codec_str(s, os->ctx->streams[0]->codec, os->codec_str, sizeof(os->codec_str));
  480. os->first_dts = AV_NOPTS_VALUE;
  481. os->segment_index = 1;
  482. }
  483. if (!c->has_video && c->min_seg_duration <= 0) {
  484. av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
  485. ret = AVERROR(EINVAL);
  486. }
  487. ret = write_manifest(s, 0);
  488. fail:
  489. if (ret)
  490. dash_free(s);
  491. return ret;
  492. }
  493. static int add_segment(OutputStream *os, const char *file,
  494. int64_t time, int duration,
  495. int64_t start_pos, int64_t range_length,
  496. int64_t index_length)
  497. {
  498. int err;
  499. Segment *seg;
  500. if (os->nb_segments >= os->segments_size) {
  501. os->segments_size = (os->segments_size + 1) * 2;
  502. if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
  503. os->segments_size)) < 0) {
  504. os->segments_size = 0;
  505. os->nb_segments = 0;
  506. return err;
  507. }
  508. }
  509. seg = av_mallocz(sizeof(*seg));
  510. if (!seg)
  511. return AVERROR(ENOMEM);
  512. av_strlcpy(seg->file, file, sizeof(seg->file));
  513. seg->time = time;
  514. seg->duration = duration;
  515. seg->start_pos = start_pos;
  516. seg->range_length = range_length;
  517. seg->index_length = index_length;
  518. os->segments[os->nb_segments++] = seg;
  519. os->segment_index++;
  520. return 0;
  521. }
  522. static void write_styp(AVIOContext *pb)
  523. {
  524. avio_wb32(pb, 24);
  525. ffio_wfourcc(pb, "styp");
  526. ffio_wfourcc(pb, "msdh");
  527. avio_wb32(pb, 0); /* minor */
  528. ffio_wfourcc(pb, "msdh");
  529. ffio_wfourcc(pb, "msix");
  530. }
  531. static void find_index_range(AVFormatContext *s, const char *dirname,
  532. const char *filename, int64_t pos,
  533. int *index_length)
  534. {
  535. char full_path[1024];
  536. uint8_t buf[8];
  537. URLContext *fd;
  538. int ret;
  539. snprintf(full_path, sizeof(full_path), "%s%s", dirname, filename);
  540. ret = ffurl_open(&fd, full_path, AVIO_FLAG_READ, &s->interrupt_callback, NULL);
  541. if (ret < 0)
  542. return;
  543. if (ffurl_seek(fd, pos, SEEK_SET) != pos) {
  544. ffurl_close(fd);
  545. return;
  546. }
  547. ret = ffurl_read(fd, buf, 8);
  548. ffurl_close(fd);
  549. if (ret < 8)
  550. return;
  551. if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
  552. return;
  553. *index_length = AV_RB32(&buf[0]);
  554. }
  555. static int dash_flush(AVFormatContext *s, int final, int stream)
  556. {
  557. DASHContext *c = s->priv_data;
  558. int i, ret = 0;
  559. int cur_flush_segment_index = 0;
  560. if (stream >= 0)
  561. cur_flush_segment_index = c->streams[stream].segment_index;
  562. for (i = 0; i < s->nb_streams; i++) {
  563. OutputStream *os = &c->streams[i];
  564. char filename[1024] = "", full_path[1024], temp_path[1024];
  565. const char *write_path;
  566. int64_t start_pos = avio_tell(os->ctx->pb);
  567. int range_length, index_length = 0;
  568. if (!os->packets_written)
  569. continue;
  570. // Flush the single stream that got a keyframe right now.
  571. // Flush all audio streams as well, in sync with video keyframes,
  572. // but not the other video streams.
  573. if (stream >= 0 && i != stream) {
  574. if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
  575. continue;
  576. // Make sure we don't flush audio streams multiple times, when
  577. // all video streams are flushed one at a time.
  578. if (c->has_video && os->segment_index > cur_flush_segment_index)
  579. continue;
  580. }
  581. if (!c->single_file) {
  582. snprintf(filename, sizeof(filename), "chunk-stream%d-%05d.m4s", i, os->segment_index);
  583. snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
  584. snprintf(temp_path, sizeof(temp_path), "%s.tmp", full_path);
  585. write_path = USE_RENAME_REPLACE ? temp_path : full_path;
  586. ret = ffurl_open(&os->out, write_path, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
  587. if (ret < 0)
  588. break;
  589. write_styp(os->ctx->pb);
  590. }
  591. av_write_frame(os->ctx, NULL);
  592. avio_flush(os->ctx->pb);
  593. os->packets_written = 0;
  594. range_length = avio_tell(os->ctx->pb) - start_pos;
  595. if (c->single_file) {
  596. find_index_range(s, c->dirname, os->initfile, start_pos, &index_length);
  597. } else {
  598. ffurl_close(os->out);
  599. os->out = NULL;
  600. ret = USE_RENAME_REPLACE ? ff_rename(temp_path, full_path) : 0;
  601. if (ret < 0)
  602. break;
  603. }
  604. add_segment(os, filename, os->start_dts, os->end_dts - os->start_dts, start_pos, range_length, index_length);
  605. }
  606. if (c->window_size || (final && c->remove_at_exit)) {
  607. for (i = 0; i < s->nb_streams; i++) {
  608. OutputStream *os = &c->streams[i];
  609. int j;
  610. int remove = os->nb_segments - c->window_size - c->extra_window_size;
  611. if (final && c->remove_at_exit)
  612. remove = os->nb_segments;
  613. if (remove > 0) {
  614. for (j = 0; j < remove; j++) {
  615. char filename[1024];
  616. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
  617. unlink(filename);
  618. av_free(os->segments[j]);
  619. }
  620. os->nb_segments -= remove;
  621. memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
  622. }
  623. }
  624. }
  625. if (ret >= 0)
  626. ret = write_manifest(s, final);
  627. return ret;
  628. }
  629. static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
  630. {
  631. DASHContext *c = s->priv_data;
  632. AVStream *st = s->streams[pkt->stream_index];
  633. OutputStream *os = &c->streams[pkt->stream_index];
  634. int64_t seg_end_duration = (os->segment_index) * (int64_t) c->min_seg_duration;
  635. int ret;
  636. // If forcing the stream to start at 0, the mp4 muxer will set the start
  637. // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
  638. if (os->first_dts == AV_NOPTS_VALUE &&
  639. s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
  640. pkt->pts -= pkt->dts;
  641. pkt->dts = 0;
  642. }
  643. if (os->first_dts == AV_NOPTS_VALUE)
  644. os->first_dts = pkt->dts;
  645. if ((!c->has_video || st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
  646. pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
  647. av_compare_ts(pkt->dts - os->first_dts, st->time_base,
  648. seg_end_duration, AV_TIME_BASE_Q) >= 0) {
  649. int64_t prev_duration = c->last_duration;
  650. c->last_duration = av_rescale_q(pkt->dts - os->start_dts,
  651. st->time_base,
  652. AV_TIME_BASE_Q);
  653. c->total_duration = av_rescale_q(pkt->dts - os->first_dts,
  654. st->time_base,
  655. AV_TIME_BASE_Q);
  656. if ((!c->use_timeline || !c->use_template) && prev_duration) {
  657. if (c->last_duration < prev_duration*9/10 ||
  658. c->last_duration > prev_duration*11/10) {
  659. av_log(s, AV_LOG_WARNING,
  660. "Segment durations differ too much, enable use_timeline "
  661. "and use_template, or keep a stricter keyframe interval\n");
  662. }
  663. }
  664. if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
  665. return ret;
  666. }
  667. if (!os->packets_written)
  668. os->start_dts = pkt->dts;
  669. os->end_dts = pkt->dts + pkt->duration;
  670. os->packets_written++;
  671. return ff_write_chained(os->ctx, 0, pkt, s);
  672. }
  673. static int dash_write_trailer(AVFormatContext *s)
  674. {
  675. DASHContext *c = s->priv_data;
  676. if (s->nb_streams > 0) {
  677. OutputStream *os = &c->streams[0];
  678. // If no segments have been written so far, try to do a crude
  679. // guess of the segment duration
  680. if (!c->last_duration)
  681. c->last_duration = av_rescale_q(os->end_dts - os->start_dts,
  682. s->streams[0]->time_base,
  683. AV_TIME_BASE_Q);
  684. c->total_duration = av_rescale_q(os->end_dts - os->first_dts,
  685. s->streams[0]->time_base,
  686. AV_TIME_BASE_Q);
  687. }
  688. dash_flush(s, 1, -1);
  689. if (c->remove_at_exit) {
  690. char filename[1024];
  691. int i;
  692. for (i = 0; i < s->nb_streams; i++) {
  693. OutputStream *os = &c->streams[i];
  694. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
  695. unlink(filename);
  696. }
  697. unlink(s->filename);
  698. }
  699. dash_free(s);
  700. return 0;
  701. }
  702. #define OFFSET(x) offsetof(DASHContext, x)
  703. #define E AV_OPT_FLAG_ENCODING_PARAM
  704. static const AVOption options[] = {
  705. { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
  706. { "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 },
  707. { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
  708. { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
  709. { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
  710. { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
  711. { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
  712. { NULL },
  713. };
  714. static const AVClass dash_class = {
  715. .class_name = "dash muxer",
  716. .item_name = av_default_item_name,
  717. .option = options,
  718. .version = LIBAVUTIL_VERSION_INT,
  719. };
  720. AVOutputFormat ff_dash_muxer = {
  721. .name = "dash",
  722. .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
  723. .priv_data_size = sizeof(DASHContext),
  724. .audio_codec = AV_CODEC_ID_AAC,
  725. .video_codec = AV_CODEC_ID_H264,
  726. .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
  727. .write_header = dash_write_header,
  728. .write_packet = dash_write_packet,
  729. .write_trailer = dash_write_trailer,
  730. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  731. .priv_class = &dash_class,
  732. };