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.

802 lines
29KB

  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/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, s) : 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. int bit_rate = s->streams[i]->codec->bit_rate ?
  416. s->streams[i]->codec->bit_rate :
  417. s->streams[i]->codec->rc_max_rate;
  418. if (bit_rate) {
  419. snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
  420. " bandwidth=\"%d\"", bit_rate);
  421. } else {
  422. int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
  423. AV_LOG_ERROR : AV_LOG_WARNING;
  424. av_log(s, level, "No bit rate set for stream %d\n", i);
  425. if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
  426. ret = AVERROR(EINVAL);
  427. goto fail;
  428. }
  429. }
  430. ctx = avformat_alloc_context();
  431. if (!ctx) {
  432. ret = AVERROR(ENOMEM);
  433. goto fail;
  434. }
  435. os->ctx = ctx;
  436. ctx->oformat = oformat;
  437. ctx->interrupt_callback = s->interrupt_callback;
  438. if (!(st = avformat_new_stream(ctx, NULL))) {
  439. ret = AVERROR(ENOMEM);
  440. goto fail;
  441. }
  442. avcodec_copy_context(st->codec, s->streams[i]->codec);
  443. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  444. st->time_base = s->streams[i]->time_base;
  445. ctx->avoid_negative_ts = s->avoid_negative_ts;
  446. ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, dash_write, NULL);
  447. if (!ctx->pb) {
  448. ret = AVERROR(ENOMEM);
  449. goto fail;
  450. }
  451. if (c->single_file)
  452. snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
  453. else
  454. snprintf(os->initfile, sizeof(os->initfile), "init-stream%d.m4s", i);
  455. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
  456. ret = ffurl_open(&os->out, filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
  457. if (ret < 0)
  458. goto fail;
  459. os->init_start_pos = 0;
  460. av_dict_set(&opts, "movflags", "frag_custom+dash", 0);
  461. if ((ret = avformat_write_header(ctx, &opts)) < 0) {
  462. goto fail;
  463. }
  464. os->ctx_inited = 1;
  465. avio_flush(ctx->pb);
  466. av_dict_free(&opts);
  467. if (c->single_file) {
  468. os->init_range_length = avio_tell(ctx->pb);
  469. } else {
  470. ffurl_close(os->out);
  471. os->out = NULL;
  472. }
  473. s->streams[i]->time_base = st->time_base;
  474. // If the muxer wants to shift timestamps, request to have them shifted
  475. // already before being handed to this muxer, so we don't have mismatches
  476. // between the MPD and the actual segments.
  477. s->avoid_negative_ts = ctx->avoid_negative_ts;
  478. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  479. c->has_video = 1;
  480. else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  481. c->has_audio = 1;
  482. set_codec_str(s, os->ctx->streams[0]->codec, os->codec_str, sizeof(os->codec_str));
  483. os->first_dts = AV_NOPTS_VALUE;
  484. os->segment_index = 1;
  485. }
  486. if (!c->has_video && c->min_seg_duration <= 0) {
  487. av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
  488. ret = AVERROR(EINVAL);
  489. }
  490. ret = write_manifest(s, 0);
  491. fail:
  492. if (ret)
  493. dash_free(s);
  494. return ret;
  495. }
  496. static int add_segment(OutputStream *os, const char *file,
  497. int64_t time, int duration,
  498. int64_t start_pos, int64_t range_length,
  499. int64_t index_length)
  500. {
  501. int err;
  502. Segment *seg;
  503. if (os->nb_segments >= os->segments_size) {
  504. os->segments_size = (os->segments_size + 1) * 2;
  505. if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
  506. os->segments_size)) < 0) {
  507. os->segments_size = 0;
  508. os->nb_segments = 0;
  509. return err;
  510. }
  511. }
  512. seg = av_mallocz(sizeof(*seg));
  513. if (!seg)
  514. return AVERROR(ENOMEM);
  515. av_strlcpy(seg->file, file, sizeof(seg->file));
  516. seg->time = time;
  517. seg->duration = duration;
  518. seg->start_pos = start_pos;
  519. seg->range_length = range_length;
  520. seg->index_length = index_length;
  521. os->segments[os->nb_segments++] = seg;
  522. os->segment_index++;
  523. return 0;
  524. }
  525. static void write_styp(AVIOContext *pb)
  526. {
  527. avio_wb32(pb, 24);
  528. ffio_wfourcc(pb, "styp");
  529. ffio_wfourcc(pb, "msdh");
  530. avio_wb32(pb, 0); /* minor */
  531. ffio_wfourcc(pb, "msdh");
  532. ffio_wfourcc(pb, "msix");
  533. }
  534. static void find_index_range(AVFormatContext *s, const char *dirname,
  535. const char *filename, int64_t pos,
  536. int *index_length)
  537. {
  538. char full_path[1024];
  539. uint8_t buf[8];
  540. URLContext *fd;
  541. int ret;
  542. snprintf(full_path, sizeof(full_path), "%s%s", dirname, filename);
  543. ret = ffurl_open(&fd, full_path, AVIO_FLAG_READ, &s->interrupt_callback, NULL);
  544. if (ret < 0)
  545. return;
  546. if (ffurl_seek(fd, pos, SEEK_SET) != pos) {
  547. ffurl_close(fd);
  548. return;
  549. }
  550. ret = ffurl_read(fd, buf, 8);
  551. ffurl_close(fd);
  552. if (ret < 8)
  553. return;
  554. if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
  555. return;
  556. *index_length = AV_RB32(&buf[0]);
  557. }
  558. static int dash_flush(AVFormatContext *s, int final, int stream)
  559. {
  560. DASHContext *c = s->priv_data;
  561. int i, ret = 0;
  562. int cur_flush_segment_index = 0;
  563. if (stream >= 0)
  564. cur_flush_segment_index = c->streams[stream].segment_index;
  565. for (i = 0; i < s->nb_streams; i++) {
  566. OutputStream *os = &c->streams[i];
  567. char filename[1024] = "", full_path[1024], temp_path[1024];
  568. const char *write_path;
  569. int64_t start_pos = avio_tell(os->ctx->pb);
  570. int range_length, index_length = 0;
  571. if (!os->packets_written)
  572. continue;
  573. // Flush the single stream that got a keyframe right now.
  574. // Flush all audio streams as well, in sync with video keyframes,
  575. // but not the other video streams.
  576. if (stream >= 0 && i != stream) {
  577. if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
  578. continue;
  579. // Make sure we don't flush audio streams multiple times, when
  580. // all video streams are flushed one at a time.
  581. if (c->has_video && os->segment_index > cur_flush_segment_index)
  582. continue;
  583. }
  584. if (!c->single_file) {
  585. snprintf(filename, sizeof(filename), "chunk-stream%d-%05d.m4s", i, os->segment_index);
  586. snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
  587. snprintf(temp_path, sizeof(temp_path), "%s.tmp", full_path);
  588. write_path = USE_RENAME_REPLACE ? temp_path : full_path;
  589. ret = ffurl_open(&os->out, write_path, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
  590. if (ret < 0)
  591. break;
  592. write_styp(os->ctx->pb);
  593. }
  594. av_write_frame(os->ctx, NULL);
  595. avio_flush(os->ctx->pb);
  596. os->packets_written = 0;
  597. range_length = avio_tell(os->ctx->pb) - start_pos;
  598. if (c->single_file) {
  599. find_index_range(s, c->dirname, os->initfile, start_pos, &index_length);
  600. } else {
  601. ffurl_close(os->out);
  602. os->out = NULL;
  603. ret = USE_RENAME_REPLACE ? ff_rename(temp_path, full_path, s) : 0;
  604. if (ret < 0)
  605. break;
  606. }
  607. add_segment(os, filename, os->start_dts, os->end_dts - os->start_dts, start_pos, range_length, index_length);
  608. }
  609. if (c->window_size || (final && c->remove_at_exit)) {
  610. for (i = 0; i < s->nb_streams; i++) {
  611. OutputStream *os = &c->streams[i];
  612. int j;
  613. int remove = os->nb_segments - c->window_size - c->extra_window_size;
  614. if (final && c->remove_at_exit)
  615. remove = os->nb_segments;
  616. if (remove > 0) {
  617. for (j = 0; j < remove; j++) {
  618. char filename[1024];
  619. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
  620. unlink(filename);
  621. av_free(os->segments[j]);
  622. }
  623. os->nb_segments -= remove;
  624. memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
  625. }
  626. }
  627. }
  628. if (ret >= 0)
  629. ret = write_manifest(s, final);
  630. return ret;
  631. }
  632. static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
  633. {
  634. DASHContext *c = s->priv_data;
  635. AVStream *st = s->streams[pkt->stream_index];
  636. OutputStream *os = &c->streams[pkt->stream_index];
  637. int64_t seg_end_duration = (os->segment_index) * (int64_t) c->min_seg_duration;
  638. int ret;
  639. // If forcing the stream to start at 0, the mp4 muxer will set the start
  640. // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
  641. if (os->first_dts == AV_NOPTS_VALUE &&
  642. s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
  643. pkt->pts -= pkt->dts;
  644. pkt->dts = 0;
  645. }
  646. if (os->first_dts == AV_NOPTS_VALUE)
  647. os->first_dts = pkt->dts;
  648. if ((!c->has_video || st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
  649. pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
  650. av_compare_ts(pkt->dts - os->first_dts, st->time_base,
  651. seg_end_duration, AV_TIME_BASE_Q) >= 0) {
  652. int64_t prev_duration = c->last_duration;
  653. c->last_duration = av_rescale_q(pkt->dts - os->start_dts,
  654. st->time_base,
  655. AV_TIME_BASE_Q);
  656. c->total_duration = av_rescale_q(pkt->dts - os->first_dts,
  657. st->time_base,
  658. AV_TIME_BASE_Q);
  659. if ((!c->use_timeline || !c->use_template) && prev_duration) {
  660. if (c->last_duration < prev_duration*9/10 ||
  661. c->last_duration > prev_duration*11/10) {
  662. av_log(s, AV_LOG_WARNING,
  663. "Segment durations differ too much, enable use_timeline "
  664. "and use_template, or keep a stricter keyframe interval\n");
  665. }
  666. }
  667. if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
  668. return ret;
  669. }
  670. if (!os->packets_written)
  671. os->start_dts = pkt->dts;
  672. os->end_dts = pkt->dts + pkt->duration;
  673. os->packets_written++;
  674. return ff_write_chained(os->ctx, 0, pkt, s, 0);
  675. }
  676. static int dash_write_trailer(AVFormatContext *s)
  677. {
  678. DASHContext *c = s->priv_data;
  679. if (s->nb_streams > 0) {
  680. OutputStream *os = &c->streams[0];
  681. // If no segments have been written so far, try to do a crude
  682. // guess of the segment duration
  683. if (!c->last_duration)
  684. c->last_duration = av_rescale_q(os->end_dts - os->start_dts,
  685. s->streams[0]->time_base,
  686. AV_TIME_BASE_Q);
  687. c->total_duration = av_rescale_q(os->end_dts - os->first_dts,
  688. s->streams[0]->time_base,
  689. AV_TIME_BASE_Q);
  690. }
  691. dash_flush(s, 1, -1);
  692. if (c->remove_at_exit) {
  693. char filename[1024];
  694. int i;
  695. for (i = 0; i < s->nb_streams; i++) {
  696. OutputStream *os = &c->streams[i];
  697. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
  698. unlink(filename);
  699. }
  700. unlink(s->filename);
  701. }
  702. dash_free(s);
  703. return 0;
  704. }
  705. #define OFFSET(x) offsetof(DASHContext, x)
  706. #define E AV_OPT_FLAG_ENCODING_PARAM
  707. static const AVOption options[] = {
  708. { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
  709. { "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 },
  710. { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
  711. { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
  712. { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
  713. { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
  714. { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
  715. { NULL },
  716. };
  717. static const AVClass dash_class = {
  718. .class_name = "dash muxer",
  719. .item_name = av_default_item_name,
  720. .option = options,
  721. .version = LIBAVUTIL_VERSION_INT,
  722. };
  723. AVOutputFormat ff_dash_muxer = {
  724. .name = "dash",
  725. .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
  726. .priv_data_size = sizeof(DASHContext),
  727. .audio_codec = AV_CODEC_ID_AAC,
  728. .video_codec = AV_CODEC_ID_H264,
  729. .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
  730. .write_header = dash_write_header,
  731. .write_packet = dash_write_packet,
  732. .write_trailer = dash_write_trailer,
  733. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  734. .priv_class = &dash_class,
  735. };