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.

1206 lines
44KB

  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/avutil.h"
  26. #include "libavutil/avstring.h"
  27. #include "libavutil/intreadwrite.h"
  28. #include "libavutil/mathematics.h"
  29. #include "libavutil/opt.h"
  30. #include "libavutil/time_internal.h"
  31. #include "avc.h"
  32. #include "avformat.h"
  33. #include "avio_internal.h"
  34. #include "internal.h"
  35. #include "isom.h"
  36. #include "os_support.h"
  37. #include "url.h"
  38. // See ISO/IEC 23009-1:2014 5.3.9.4.4
  39. typedef enum {
  40. DASH_TMPL_ID_UNDEFINED = -1,
  41. DASH_TMPL_ID_ESCAPE,
  42. DASH_TMPL_ID_REP_ID,
  43. DASH_TMPL_ID_NUMBER,
  44. DASH_TMPL_ID_BANDWIDTH,
  45. DASH_TMPL_ID_TIME,
  46. } DASHTmplId;
  47. typedef struct Segment {
  48. char file[1024];
  49. int64_t start_pos;
  50. int range_length, index_length;
  51. int64_t time;
  52. int duration;
  53. int n;
  54. } Segment;
  55. typedef struct AdaptationSet {
  56. char id[10];
  57. enum AVMediaType media_type;
  58. AVDictionary *metadata;
  59. } AdaptationSet;
  60. typedef struct OutputStream {
  61. AVFormatContext *ctx;
  62. int ctx_inited, as_idx;
  63. uint8_t iobuf[32768];
  64. AVIOContext *out;
  65. int packets_written;
  66. char initfile[1024];
  67. int64_t init_start_pos;
  68. int init_range_length;
  69. int nb_segments, segments_size, segment_index;
  70. Segment **segments;
  71. int64_t first_pts, start_pts, max_pts;
  72. int64_t last_dts;
  73. int bit_rate;
  74. char bandwidth_str[64];
  75. char codec_str[100];
  76. } OutputStream;
  77. typedef struct DASHContext {
  78. const AVClass *class; /* Class for private options. */
  79. char *adaptation_sets;
  80. AdaptationSet *as;
  81. int nb_as;
  82. int window_size;
  83. int extra_window_size;
  84. int min_seg_duration;
  85. int remove_at_exit;
  86. int use_template;
  87. int use_timeline;
  88. int single_file;
  89. OutputStream *streams;
  90. int has_video;
  91. int64_t last_duration;
  92. int64_t total_duration;
  93. char availability_start_time[100];
  94. char dirname[1024];
  95. const char *single_file_name;
  96. const char *init_seg_name;
  97. const char *media_seg_name;
  98. const char *utc_timing_url;
  99. } DASHContext;
  100. static int dash_write(void *opaque, uint8_t *buf, int buf_size)
  101. {
  102. OutputStream *os = opaque;
  103. if (os->out)
  104. avio_write(os->out, buf, buf_size);
  105. return buf_size;
  106. }
  107. // RFC 6381
  108. static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
  109. char *str, int size)
  110. {
  111. const AVCodecTag *tags[2] = { NULL, NULL };
  112. uint32_t tag;
  113. if (par->codec_type == AVMEDIA_TYPE_VIDEO)
  114. tags[0] = ff_codec_movvideo_tags;
  115. else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
  116. tags[0] = ff_codec_movaudio_tags;
  117. else
  118. return;
  119. tag = av_codec_get_tag(tags, par->codec_id);
  120. if (!tag)
  121. return;
  122. if (size < 5)
  123. return;
  124. AV_WL32(str, tag);
  125. str[4] = '\0';
  126. if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
  127. uint32_t oti;
  128. tags[0] = ff_mp4_obj_type;
  129. oti = av_codec_get_tag(tags, par->codec_id);
  130. if (oti)
  131. av_strlcatf(str, size, ".%02"SCNx32, oti);
  132. else
  133. return;
  134. if (tag == MKTAG('m', 'p', '4', 'a')) {
  135. if (par->extradata_size >= 2) {
  136. int aot = par->extradata[0] >> 3;
  137. if (aot == 31)
  138. aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
  139. av_strlcatf(str, size, ".%d", aot);
  140. }
  141. } else if (tag == MKTAG('m', 'p', '4', 'v')) {
  142. // Unimplemented, should output ProfileLevelIndication as a decimal number
  143. av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
  144. }
  145. } else if (!strcmp(str, "avc1")) {
  146. uint8_t *tmpbuf = NULL;
  147. uint8_t *extradata = par->extradata;
  148. int extradata_size = par->extradata_size;
  149. if (!extradata_size)
  150. return;
  151. if (extradata[0] != 1) {
  152. AVIOContext *pb;
  153. if (avio_open_dyn_buf(&pb) < 0)
  154. return;
  155. if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
  156. ffio_free_dyn_buf(&pb);
  157. return;
  158. }
  159. extradata_size = avio_close_dyn_buf(pb, &extradata);
  160. tmpbuf = extradata;
  161. }
  162. if (extradata_size >= 4)
  163. av_strlcatf(str, size, ".%02x%02x%02x",
  164. extradata[1], extradata[2], extradata[3]);
  165. av_free(tmpbuf);
  166. }
  167. }
  168. static void dash_free(AVFormatContext *s)
  169. {
  170. DASHContext *c = s->priv_data;
  171. int i, j;
  172. if (c->as) {
  173. for (i = 0; i < c->nb_as; i++)
  174. av_dict_free(&c->as[i].metadata);
  175. av_freep(&c->as);
  176. c->nb_as = 0;
  177. }
  178. if (!c->streams)
  179. return;
  180. for (i = 0; i < s->nb_streams; i++) {
  181. OutputStream *os = &c->streams[i];
  182. if (os->ctx && os->ctx_inited)
  183. av_write_trailer(os->ctx);
  184. if (os->ctx && os->ctx->pb)
  185. av_free(os->ctx->pb);
  186. ff_format_io_close(s, &os->out);
  187. if (os->ctx)
  188. avformat_free_context(os->ctx);
  189. for (j = 0; j < os->nb_segments; j++)
  190. av_free(os->segments[j]);
  191. av_free(os->segments);
  192. }
  193. av_freep(&c->streams);
  194. }
  195. static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c)
  196. {
  197. int i, start_index = 0, start_number = 1;
  198. if (c->window_size) {
  199. start_index = FFMAX(os->nb_segments - c->window_size, 0);
  200. start_number = FFMAX(os->segment_index - c->window_size, 1);
  201. }
  202. if (c->use_template) {
  203. int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
  204. avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
  205. if (!c->use_timeline)
  206. avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);
  207. avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
  208. if (c->use_timeline) {
  209. int64_t cur_time = 0;
  210. avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
  211. for (i = start_index; i < os->nb_segments; ) {
  212. Segment *seg = os->segments[i];
  213. int repeat = 0;
  214. avio_printf(out, "\t\t\t\t\t\t<S ");
  215. if (i == start_index || seg->time != cur_time) {
  216. cur_time = seg->time;
  217. avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
  218. }
  219. avio_printf(out, "d=\"%d\" ", seg->duration);
  220. while (i + repeat + 1 < os->nb_segments &&
  221. os->segments[i + repeat + 1]->duration == seg->duration &&
  222. os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
  223. repeat++;
  224. if (repeat > 0)
  225. avio_printf(out, "r=\"%d\" ", repeat);
  226. avio_printf(out, "/>\n");
  227. i += 1 + repeat;
  228. cur_time += (1 + repeat) * seg->duration;
  229. }
  230. avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
  231. }
  232. avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
  233. } else if (c->single_file) {
  234. avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
  235. avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
  236. 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);
  237. for (i = start_index; i < os->nb_segments; i++) {
  238. Segment *seg = os->segments[i];
  239. avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
  240. if (seg->index_length)
  241. avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
  242. avio_printf(out, "/>\n");
  243. }
  244. avio_printf(out, "\t\t\t\t</SegmentList>\n");
  245. } else {
  246. avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
  247. avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
  248. for (i = start_index; i < os->nb_segments; i++) {
  249. Segment *seg = os->segments[i];
  250. avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
  251. }
  252. avio_printf(out, "\t\t\t\t</SegmentList>\n");
  253. }
  254. }
  255. static DASHTmplId dash_read_tmpl_id(const char *identifier, char *format_tag,
  256. size_t format_tag_size, const char **ptr) {
  257. const char *next_ptr;
  258. DASHTmplId id_type = DASH_TMPL_ID_UNDEFINED;
  259. if (av_strstart(identifier, "$$", &next_ptr)) {
  260. id_type = DASH_TMPL_ID_ESCAPE;
  261. *ptr = next_ptr;
  262. } else if (av_strstart(identifier, "$RepresentationID$", &next_ptr)) {
  263. id_type = DASH_TMPL_ID_REP_ID;
  264. // default to basic format, as $RepresentationID$ identifiers
  265. // are not allowed to have custom format-tags.
  266. av_strlcpy(format_tag, "%d", format_tag_size);
  267. *ptr = next_ptr;
  268. } else { // the following identifiers may have an explicit format_tag
  269. if (av_strstart(identifier, "$Number", &next_ptr))
  270. id_type = DASH_TMPL_ID_NUMBER;
  271. else if (av_strstart(identifier, "$Bandwidth", &next_ptr))
  272. id_type = DASH_TMPL_ID_BANDWIDTH;
  273. else if (av_strstart(identifier, "$Time", &next_ptr))
  274. id_type = DASH_TMPL_ID_TIME;
  275. else
  276. id_type = DASH_TMPL_ID_UNDEFINED;
  277. // next parse the dash format-tag and generate a c-string format tag
  278. // (next_ptr now points at the first '%' at the beginning of the format-tag)
  279. if (id_type != DASH_TMPL_ID_UNDEFINED) {
  280. const char *number_format = (id_type == DASH_TMPL_ID_TIME) ? PRId64 : "d";
  281. if (next_ptr[0] == '$') { // no dash format-tag
  282. snprintf(format_tag, format_tag_size, "%%%s", number_format);
  283. *ptr = &next_ptr[1];
  284. } else {
  285. const char *width_ptr;
  286. // only tolerate single-digit width-field (i.e. up to 9-digit width)
  287. if (av_strstart(next_ptr, "%0", &width_ptr) &&
  288. av_isdigit(width_ptr[0]) &&
  289. av_strstart(&width_ptr[1], "d$", &next_ptr)) {
  290. // yes, we're using a format tag to build format_tag.
  291. snprintf(format_tag, format_tag_size, "%s%c%s", "%0", width_ptr[0], number_format);
  292. *ptr = next_ptr;
  293. } else {
  294. av_log(NULL, AV_LOG_WARNING, "Failed to parse format-tag beginning with %s. Expected either a "
  295. "closing '$' character or a format-string like '%%0[width]d', "
  296. "where width must be a single digit\n", next_ptr);
  297. id_type = DASH_TMPL_ID_UNDEFINED;
  298. }
  299. }
  300. }
  301. }
  302. return id_type;
  303. }
  304. static void dash_fill_tmpl_params(char *dst, size_t buffer_size,
  305. const char *template, int rep_id,
  306. int number, int bit_rate,
  307. int64_t time) {
  308. int dst_pos = 0;
  309. const char *t_cur = template;
  310. while (dst_pos < buffer_size - 1 && *t_cur) {
  311. char format_tag[7]; // May be "%d", "%0Xd", or "%0Xlld" (for $Time$), where X is in [0-9]
  312. int n = 0;
  313. DASHTmplId id_type;
  314. const char *t_next = strchr(t_cur, '$'); // copy over everything up to the first '$' character
  315. if (t_next) {
  316. int num_copy_bytes = FFMIN(t_next - t_cur, buffer_size - dst_pos - 1);
  317. av_strlcpy(&dst[dst_pos], t_cur, num_copy_bytes + 1);
  318. // advance
  319. dst_pos += num_copy_bytes;
  320. t_cur = t_next;
  321. } else { // no more DASH identifiers to substitute - just copy the rest over and break
  322. av_strlcpy(&dst[dst_pos], t_cur, buffer_size - dst_pos);
  323. break;
  324. }
  325. if (dst_pos >= buffer_size - 1 || !*t_cur)
  326. break;
  327. // t_cur is now pointing to a '$' character
  328. id_type = dash_read_tmpl_id(t_cur, format_tag, sizeof(format_tag), &t_next);
  329. switch (id_type) {
  330. case DASH_TMPL_ID_ESCAPE:
  331. av_strlcpy(&dst[dst_pos], "$", 2);
  332. n = 1;
  333. break;
  334. case DASH_TMPL_ID_REP_ID:
  335. n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, rep_id);
  336. break;
  337. case DASH_TMPL_ID_NUMBER:
  338. n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, number);
  339. break;
  340. case DASH_TMPL_ID_BANDWIDTH:
  341. n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, bit_rate);
  342. break;
  343. case DASH_TMPL_ID_TIME:
  344. n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, time);
  345. break;
  346. case DASH_TMPL_ID_UNDEFINED:
  347. // copy over one byte and advance
  348. av_strlcpy(&dst[dst_pos], t_cur, 2);
  349. n = 1;
  350. t_next = &t_cur[1];
  351. break;
  352. }
  353. // t_next points just past the processed identifier
  354. // n is the number of bytes that were attempted to be written to dst
  355. // (may have failed to write all because buffer_size).
  356. // advance
  357. dst_pos += FFMIN(n, buffer_size - dst_pos - 1);
  358. t_cur = t_next;
  359. }
  360. }
  361. static char *xmlescape(const char *str) {
  362. int outlen = strlen(str)*3/2 + 6;
  363. char *out = av_realloc(NULL, outlen + 1);
  364. int pos = 0;
  365. if (!out)
  366. return NULL;
  367. for (; *str; str++) {
  368. if (pos + 6 > outlen) {
  369. char *tmp;
  370. outlen = 2 * outlen + 6;
  371. tmp = av_realloc(out, outlen + 1);
  372. if (!tmp) {
  373. av_free(out);
  374. return NULL;
  375. }
  376. out = tmp;
  377. }
  378. if (*str == '&') {
  379. memcpy(&out[pos], "&amp;", 5);
  380. pos += 5;
  381. } else if (*str == '<') {
  382. memcpy(&out[pos], "&lt;", 4);
  383. pos += 4;
  384. } else if (*str == '>') {
  385. memcpy(&out[pos], "&gt;", 4);
  386. pos += 4;
  387. } else if (*str == '\'') {
  388. memcpy(&out[pos], "&apos;", 6);
  389. pos += 6;
  390. } else if (*str == '\"') {
  391. memcpy(&out[pos], "&quot;", 6);
  392. pos += 6;
  393. } else {
  394. out[pos++] = *str;
  395. }
  396. }
  397. out[pos] = '\0';
  398. return out;
  399. }
  400. static void write_time(AVIOContext *out, int64_t time)
  401. {
  402. int seconds = time / AV_TIME_BASE;
  403. int fractions = time % AV_TIME_BASE;
  404. int minutes = seconds / 60;
  405. int hours = minutes / 60;
  406. seconds %= 60;
  407. minutes %= 60;
  408. avio_printf(out, "PT");
  409. if (hours)
  410. avio_printf(out, "%dH", hours);
  411. if (hours || minutes)
  412. avio_printf(out, "%dM", minutes);
  413. avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
  414. }
  415. static void format_date_now(char *buf, int size)
  416. {
  417. time_t t = time(NULL);
  418. struct tm *ptm, tmbuf;
  419. ptm = gmtime_r(&t, &tmbuf);
  420. if (ptm) {
  421. if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", ptm))
  422. buf[0] = '\0';
  423. }
  424. }
  425. static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index)
  426. {
  427. DASHContext *c = s->priv_data;
  428. AdaptationSet *as = &c->as[as_index];
  429. AVDictionaryEntry *lang, *role;
  430. int i;
  431. avio_printf(out, "\t\t<AdaptationSet id=\"%s\" contentType=\"%s\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
  432. as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
  433. lang = av_dict_get(as->metadata, "language", NULL, 0);
  434. if (lang)
  435. avio_printf(out, " lang=\"%s\"", lang->value);
  436. avio_printf(out, ">\n");
  437. role = av_dict_get(as->metadata, "role", NULL, 0);
  438. if (role)
  439. avio_printf(out, "\t\t\t<Role schemeIdUri=\"urn:mpeg:dash:role:2011\" value=\"%s\"/>\n", role->value);
  440. for (i = 0; i < s->nb_streams; i++) {
  441. OutputStream *os = &c->streams[i];
  442. if (os->as_idx - 1 != as_index)
  443. continue;
  444. if (as->media_type == AVMEDIA_TYPE_VIDEO) {
  445. avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/mp4\" codecs=\"%s\"%s width=\"%d\" height=\"%d\">\n",
  446. i, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
  447. } else {
  448. avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/mp4\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
  449. i, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->sample_rate);
  450. avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
  451. s->streams[i]->codecpar->channels);
  452. }
  453. output_segment_list(os, out, c);
  454. avio_printf(out, "\t\t\t</Representation>\n");
  455. }
  456. avio_printf(out, "\t\t</AdaptationSet>\n");
  457. return 0;
  458. }
  459. static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
  460. {
  461. DASHContext *c = s->priv_data;
  462. void *mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
  463. if (!mem)
  464. return AVERROR(ENOMEM);
  465. c->as = mem;
  466. ++c->nb_as;
  467. *as = &c->as[c->nb_as - 1];
  468. memset(*as, 0, sizeof(**as));
  469. (*as)->media_type = type;
  470. return 0;
  471. }
  472. static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
  473. {
  474. DASHContext *c = s->priv_data;
  475. AdaptationSet *as = &c->as[as_idx - 1];
  476. OutputStream *os = &c->streams[i];
  477. if (as->media_type != s->streams[i]->codecpar->codec_type) {
  478. av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
  479. return AVERROR(EINVAL);
  480. } else if (os->as_idx) {
  481. av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
  482. return AVERROR(EINVAL);
  483. }
  484. os->as_idx = as_idx;
  485. return 0;
  486. }
  487. static int parse_adaptation_sets(AVFormatContext *s)
  488. {
  489. DASHContext *c = s->priv_data;
  490. const char *p = c->adaptation_sets;
  491. enum { new_set, parse_id, parsing_streams } state;
  492. AdaptationSet *as;
  493. int i, n, ret;
  494. // default: one AdaptationSet for each stream
  495. if (!p) {
  496. for (i = 0; i < s->nb_streams; i++) {
  497. if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
  498. return ret;
  499. snprintf(as->id, sizeof(as->id), "%d", i);
  500. c->streams[i].as_idx = c->nb_as;
  501. }
  502. goto end;
  503. }
  504. // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
  505. state = new_set;
  506. while (*p) {
  507. if (*p == ' ') {
  508. p++;
  509. continue;
  510. } else if (state == new_set && av_strstart(p, "id=", &p)) {
  511. if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
  512. return ret;
  513. n = strcspn(p, ",");
  514. snprintf(as->id, sizeof(as->id), "%.*s", n, p);
  515. p += n;
  516. if (*p)
  517. p++;
  518. state = parse_id;
  519. } else if (state == parse_id && av_strstart(p, "streams=", &p)) {
  520. state = parsing_streams;
  521. } else if (state == parsing_streams) {
  522. AdaptationSet *as = &c->as[c->nb_as - 1];
  523. char idx_str[8], *end_str;
  524. n = strcspn(p, " ,");
  525. snprintf(idx_str, sizeof(idx_str), "%.*s", n, p);
  526. p += n;
  527. // if value is "a" or "v", map all streams of that type
  528. if (as->media_type == AVMEDIA_TYPE_UNKNOWN && (idx_str[0] == 'v' || idx_str[0] == 'a')) {
  529. enum AVMediaType type = (idx_str[0] == 'v') ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
  530. av_log(s, AV_LOG_DEBUG, "Map all streams of type %s\n", idx_str);
  531. for (i = 0; i < s->nb_streams; i++) {
  532. if (s->streams[i]->codecpar->codec_type != type)
  533. continue;
  534. as->media_type = s->streams[i]->codecpar->codec_type;
  535. if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
  536. return ret;
  537. }
  538. } else { // select single stream
  539. i = strtol(idx_str, &end_str, 10);
  540. if (idx_str == end_str || i < 0 || i >= s->nb_streams) {
  541. av_log(s, AV_LOG_ERROR, "Selected stream \"%s\" not found!\n", idx_str);
  542. return AVERROR(EINVAL);
  543. }
  544. av_log(s, AV_LOG_DEBUG, "Map stream %d\n", i);
  545. if (as->media_type == AVMEDIA_TYPE_UNKNOWN) {
  546. as->media_type = s->streams[i]->codecpar->codec_type;
  547. }
  548. if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
  549. return ret;
  550. }
  551. if (*p == ' ')
  552. state = new_set;
  553. if (*p)
  554. p++;
  555. } else {
  556. return AVERROR(EINVAL);
  557. }
  558. }
  559. end:
  560. // check for unassigned streams
  561. for (i = 0; i < s->nb_streams; i++) {
  562. OutputStream *os = &c->streams[i];
  563. if (!os->as_idx) {
  564. av_log(s, AV_LOG_ERROR, "Stream %d is not mapped to an AdaptationSet\n", i);
  565. return AVERROR(EINVAL);
  566. }
  567. }
  568. return 0;
  569. }
  570. static int write_manifest(AVFormatContext *s, int final)
  571. {
  572. DASHContext *c = s->priv_data;
  573. AVIOContext *out;
  574. char temp_filename[1024];
  575. int ret, i;
  576. AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
  577. snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", s->filename);
  578. ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL);
  579. if (ret < 0) {
  580. av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
  581. return ret;
  582. }
  583. avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  584. avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
  585. "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
  586. "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
  587. "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
  588. "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
  589. "\ttype=\"%s\"\n", final ? "static" : "dynamic");
  590. if (final) {
  591. avio_printf(out, "\tmediaPresentationDuration=\"");
  592. write_time(out, c->total_duration);
  593. avio_printf(out, "\"\n");
  594. } else {
  595. int64_t update_period = c->last_duration / AV_TIME_BASE;
  596. char now_str[100];
  597. if (c->use_template && !c->use_timeline)
  598. update_period = 500;
  599. avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
  600. avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
  601. if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
  602. format_date_now(c->availability_start_time, sizeof(c->availability_start_time));
  603. }
  604. if (c->availability_start_time[0])
  605. avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
  606. format_date_now(now_str, sizeof(now_str));
  607. if (now_str[0])
  608. avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
  609. if (c->window_size && c->use_template) {
  610. avio_printf(out, "\ttimeShiftBufferDepth=\"");
  611. write_time(out, c->last_duration * c->window_size);
  612. avio_printf(out, "\"\n");
  613. }
  614. }
  615. avio_printf(out, "\tminBufferTime=\"");
  616. write_time(out, c->last_duration * 2);
  617. avio_printf(out, "\">\n");
  618. avio_printf(out, "\t<ProgramInformation>\n");
  619. if (title) {
  620. char *escaped = xmlescape(title->value);
  621. avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
  622. av_free(escaped);
  623. }
  624. avio_printf(out, "\t</ProgramInformation>\n");
  625. if (c->utc_timing_url)
  626. avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
  627. if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
  628. OutputStream *os = &c->streams[0];
  629. int start_index = FFMAX(os->nb_segments - c->window_size, 0);
  630. int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
  631. avio_printf(out, "\t<Period id=\"0\" start=\"");
  632. write_time(out, start_time);
  633. avio_printf(out, "\">\n");
  634. } else {
  635. avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
  636. }
  637. for (i = 0; i < c->nb_as; i++) {
  638. if ((ret = write_adaptation_set(s, out, i)) < 0)
  639. return ret;
  640. }
  641. avio_printf(out, "\t</Period>\n");
  642. avio_printf(out, "</MPD>\n");
  643. avio_flush(out);
  644. ff_format_io_close(s, &out);
  645. return ff_rename(temp_filename, s->filename);
  646. }
  647. static int dict_copy_entry(AVDictionary **dst, const AVDictionary *src, const char *key)
  648. {
  649. AVDictionaryEntry *entry = av_dict_get(src, key, NULL, 0);
  650. if (entry)
  651. av_dict_set(dst, key, entry->value, AV_DICT_DONT_OVERWRITE);
  652. return 0;
  653. }
  654. static int dash_write_header(AVFormatContext *s)
  655. {
  656. DASHContext *c = s->priv_data;
  657. int ret = 0, i;
  658. AVOutputFormat *oformat;
  659. char *ptr;
  660. char basename[1024];
  661. if (c->single_file_name)
  662. c->single_file = 1;
  663. if (c->single_file)
  664. c->use_template = 0;
  665. av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
  666. ptr = strrchr(c->dirname, '/');
  667. if (ptr) {
  668. av_strlcpy(basename, &ptr[1], sizeof(basename));
  669. ptr[1] = '\0';
  670. } else {
  671. c->dirname[0] = '\0';
  672. av_strlcpy(basename, s->filename, sizeof(basename));
  673. }
  674. ptr = strrchr(basename, '.');
  675. if (ptr)
  676. *ptr = '\0';
  677. oformat = av_guess_format("mp4", NULL, NULL);
  678. if (!oformat) {
  679. ret = AVERROR_MUXER_NOT_FOUND;
  680. goto fail;
  681. }
  682. c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
  683. if (!c->streams) {
  684. ret = AVERROR(ENOMEM);
  685. goto fail;
  686. }
  687. if ((ret = parse_adaptation_sets(s)) < 0)
  688. goto fail;
  689. for (i = 0; i < s->nb_streams; i++) {
  690. OutputStream *os = &c->streams[i];
  691. AdaptationSet *as = &c->as[os->as_idx - 1];
  692. AVFormatContext *ctx;
  693. AVStream *st;
  694. AVDictionary *opts = NULL;
  695. char filename[1024];
  696. os->bit_rate = s->streams[i]->codecpar->bit_rate;
  697. if (os->bit_rate) {
  698. snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
  699. " bandwidth=\"%d\"", os->bit_rate);
  700. } else {
  701. int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
  702. AV_LOG_ERROR : AV_LOG_WARNING;
  703. av_log(s, level, "No bit rate set for stream %d\n", i);
  704. if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
  705. ret = AVERROR(EINVAL);
  706. goto fail;
  707. }
  708. }
  709. // copy AdaptationSet language and role from stream metadata
  710. dict_copy_entry(&as->metadata, s->streams[i]->metadata, "language");
  711. dict_copy_entry(&as->metadata, s->streams[i]->metadata, "role");
  712. ctx = avformat_alloc_context();
  713. if (!ctx) {
  714. ret = AVERROR(ENOMEM);
  715. goto fail;
  716. }
  717. os->ctx = ctx;
  718. ctx->oformat = oformat;
  719. ctx->interrupt_callback = s->interrupt_callback;
  720. ctx->opaque = s->opaque;
  721. ctx->io_close = s->io_close;
  722. ctx->io_open = s->io_open;
  723. if (!(st = avformat_new_stream(ctx, NULL))) {
  724. ret = AVERROR(ENOMEM);
  725. goto fail;
  726. }
  727. avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
  728. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  729. st->time_base = s->streams[i]->time_base;
  730. ctx->avoid_negative_ts = s->avoid_negative_ts;
  731. ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, dash_write, NULL);
  732. if (!ctx->pb) {
  733. ret = AVERROR(ENOMEM);
  734. goto fail;
  735. }
  736. if (c->single_file) {
  737. if (c->single_file_name)
  738. dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
  739. else
  740. snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
  741. } else {
  742. dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
  743. }
  744. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
  745. ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, NULL);
  746. if (ret < 0)
  747. goto fail;
  748. os->init_start_pos = 0;
  749. av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
  750. if ((ret = avformat_write_header(ctx, &opts)) < 0) {
  751. goto fail;
  752. }
  753. os->ctx_inited = 1;
  754. avio_flush(ctx->pb);
  755. av_dict_free(&opts);
  756. av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
  757. s->streams[i]->time_base = st->time_base;
  758. // If the muxer wants to shift timestamps, request to have them shifted
  759. // already before being handed to this muxer, so we don't have mismatches
  760. // between the MPD and the actual segments.
  761. s->avoid_negative_ts = ctx->avoid_negative_ts;
  762. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  763. c->has_video = 1;
  764. set_codec_str(s, st->codecpar, os->codec_str, sizeof(os->codec_str));
  765. os->first_pts = AV_NOPTS_VALUE;
  766. os->max_pts = AV_NOPTS_VALUE;
  767. os->last_dts = AV_NOPTS_VALUE;
  768. os->segment_index = 1;
  769. }
  770. if (!c->has_video && c->min_seg_duration <= 0) {
  771. av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
  772. ret = AVERROR(EINVAL);
  773. }
  774. ret = write_manifest(s, 0);
  775. if (!ret)
  776. av_log(s, AV_LOG_VERBOSE, "Manifest written to: %s\n", s->filename);
  777. fail:
  778. if (ret)
  779. dash_free(s);
  780. return ret;
  781. }
  782. static int add_segment(OutputStream *os, const char *file,
  783. int64_t time, int duration,
  784. int64_t start_pos, int64_t range_length,
  785. int64_t index_length)
  786. {
  787. int err;
  788. Segment *seg;
  789. if (os->nb_segments >= os->segments_size) {
  790. os->segments_size = (os->segments_size + 1) * 2;
  791. if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
  792. os->segments_size)) < 0) {
  793. os->segments_size = 0;
  794. os->nb_segments = 0;
  795. return err;
  796. }
  797. }
  798. seg = av_mallocz(sizeof(*seg));
  799. if (!seg)
  800. return AVERROR(ENOMEM);
  801. av_strlcpy(seg->file, file, sizeof(seg->file));
  802. seg->time = time;
  803. seg->duration = duration;
  804. if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
  805. seg->duration += seg->time;
  806. seg->time = 0;
  807. }
  808. seg->start_pos = start_pos;
  809. seg->range_length = range_length;
  810. seg->index_length = index_length;
  811. os->segments[os->nb_segments++] = seg;
  812. os->segment_index++;
  813. return 0;
  814. }
  815. static void write_styp(AVIOContext *pb)
  816. {
  817. avio_wb32(pb, 24);
  818. ffio_wfourcc(pb, "styp");
  819. ffio_wfourcc(pb, "msdh");
  820. avio_wb32(pb, 0); /* minor */
  821. ffio_wfourcc(pb, "msdh");
  822. ffio_wfourcc(pb, "msix");
  823. }
  824. static void find_index_range(AVFormatContext *s, const char *full_path,
  825. int64_t pos, int *index_length)
  826. {
  827. uint8_t buf[8];
  828. AVIOContext *pb;
  829. int ret;
  830. ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
  831. if (ret < 0)
  832. return;
  833. if (avio_seek(pb, pos, SEEK_SET) != pos) {
  834. ff_format_io_close(s, &pb);
  835. return;
  836. }
  837. ret = avio_read(pb, buf, 8);
  838. ff_format_io_close(s, &pb);
  839. if (ret < 8)
  840. return;
  841. if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
  842. return;
  843. *index_length = AV_RB32(&buf[0]);
  844. }
  845. static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
  846. AVCodecParameters *par)
  847. {
  848. uint8_t *extradata;
  849. if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
  850. return 0;
  851. extradata = av_malloc(par->extradata_size);
  852. if (!extradata)
  853. return AVERROR(ENOMEM);
  854. memcpy(extradata, par->extradata, par->extradata_size);
  855. os->ctx->streams[0]->codecpar->extradata = extradata;
  856. os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
  857. set_codec_str(s, par, os->codec_str, sizeof(os->codec_str));
  858. return 0;
  859. }
  860. static int dash_flush(AVFormatContext *s, int final, int stream)
  861. {
  862. DASHContext *c = s->priv_data;
  863. int i, ret = 0;
  864. int cur_flush_segment_index = 0;
  865. if (stream >= 0)
  866. cur_flush_segment_index = c->streams[stream].segment_index;
  867. for (i = 0; i < s->nb_streams; i++) {
  868. OutputStream *os = &c->streams[i];
  869. char filename[1024] = "", full_path[1024], temp_path[1024];
  870. int64_t start_pos;
  871. int range_length, index_length = 0;
  872. if (!os->packets_written)
  873. continue;
  874. // Flush the single stream that got a keyframe right now.
  875. // Flush all audio streams as well, in sync with video keyframes,
  876. // but not the other video streams.
  877. if (stream >= 0 && i != stream) {
  878. if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
  879. continue;
  880. // Make sure we don't flush audio streams multiple times, when
  881. // all video streams are flushed one at a time.
  882. if (c->has_video && os->segment_index > cur_flush_segment_index)
  883. continue;
  884. }
  885. if (!os->init_range_length) {
  886. av_write_frame(os->ctx, NULL);
  887. os->init_range_length = avio_tell(os->ctx->pb);
  888. if (!c->single_file)
  889. ff_format_io_close(s, &os->out);
  890. }
  891. start_pos = avio_tell(os->ctx->pb);
  892. if (!c->single_file) {
  893. dash_fill_tmpl_params(filename, sizeof(filename), c->media_seg_name, i, os->segment_index, os->bit_rate, os->start_pts);
  894. snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
  895. snprintf(temp_path, sizeof(temp_path), "%s.tmp", full_path);
  896. ret = s->io_open(s, &os->out, temp_path, AVIO_FLAG_WRITE, NULL);
  897. if (ret < 0)
  898. break;
  899. write_styp(os->ctx->pb);
  900. } else {
  901. snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, os->initfile);
  902. }
  903. av_write_frame(os->ctx, NULL);
  904. avio_flush(os->ctx->pb);
  905. os->packets_written = 0;
  906. range_length = avio_tell(os->ctx->pb) - start_pos;
  907. if (c->single_file) {
  908. find_index_range(s, full_path, start_pos, &index_length);
  909. } else {
  910. ff_format_io_close(s, &os->out);
  911. ret = ff_rename(temp_path, full_path);
  912. if (ret < 0)
  913. break;
  914. }
  915. if (!os->bit_rate) {
  916. // calculate average bitrate of first segment
  917. int64_t bitrate = (int64_t) range_length * 8 * AV_TIME_BASE / (os->max_pts - os->start_pts);
  918. if (bitrate >= 0) {
  919. os->bit_rate = bitrate;
  920. snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
  921. " bandwidth=\"%d\"", os->bit_rate);
  922. }
  923. }
  924. add_segment(os, filename, os->start_pts, os->max_pts - os->start_pts, start_pos, range_length, index_length);
  925. av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, full_path);
  926. }
  927. if (c->window_size || (final && c->remove_at_exit)) {
  928. for (i = 0; i < s->nb_streams; i++) {
  929. OutputStream *os = &c->streams[i];
  930. int j;
  931. int remove = os->nb_segments - c->window_size - c->extra_window_size;
  932. if (final && c->remove_at_exit)
  933. remove = os->nb_segments;
  934. if (remove > 0) {
  935. for (j = 0; j < remove; j++) {
  936. char filename[1024];
  937. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
  938. unlink(filename);
  939. av_free(os->segments[j]);
  940. }
  941. os->nb_segments -= remove;
  942. memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
  943. }
  944. }
  945. }
  946. if (ret >= 0)
  947. ret = write_manifest(s, final);
  948. return ret;
  949. }
  950. static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
  951. {
  952. DASHContext *c = s->priv_data;
  953. AVStream *st = s->streams[pkt->stream_index];
  954. OutputStream *os = &c->streams[pkt->stream_index];
  955. int ret;
  956. ret = update_stream_extradata(s, os, st->codecpar);
  957. if (ret < 0)
  958. return ret;
  959. // Fill in a heuristic guess of the packet duration, if none is available.
  960. // The mp4 muxer will do something similar (for the last packet in a fragment)
  961. // if nothing is set (setting it for the other packets doesn't hurt).
  962. // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
  963. // invoke its heuristic (this doesn't have to be identical to that algorithm),
  964. // so that we know the exact timestamps of fragments.
  965. if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
  966. pkt->duration = pkt->dts - os->last_dts;
  967. os->last_dts = pkt->dts;
  968. // If forcing the stream to start at 0, the mp4 muxer will set the start
  969. // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
  970. if (os->first_pts == AV_NOPTS_VALUE &&
  971. s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
  972. pkt->pts -= pkt->dts;
  973. pkt->dts = 0;
  974. }
  975. if (os->first_pts == AV_NOPTS_VALUE)
  976. os->first_pts = pkt->pts;
  977. if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
  978. pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
  979. av_compare_ts(pkt->pts - os->start_pts, st->time_base,
  980. c->min_seg_duration, AV_TIME_BASE_Q) >= 0) {
  981. int64_t prev_duration = c->last_duration;
  982. c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
  983. st->time_base,
  984. AV_TIME_BASE_Q);
  985. c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
  986. st->time_base,
  987. AV_TIME_BASE_Q);
  988. if ((!c->use_timeline || !c->use_template) && prev_duration) {
  989. if (c->last_duration < prev_duration*9/10 ||
  990. c->last_duration > prev_duration*11/10) {
  991. av_log(s, AV_LOG_WARNING,
  992. "Segment durations differ too much, enable use_timeline "
  993. "and use_template, or keep a stricter keyframe interval\n");
  994. }
  995. }
  996. if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
  997. return ret;
  998. }
  999. if (!os->packets_written) {
  1000. // If we wrote a previous segment, adjust the start time of the segment
  1001. // to the end of the previous one (which is the same as the mp4 muxer
  1002. // does). This avoids gaps in the timeline.
  1003. if (os->max_pts != AV_NOPTS_VALUE)
  1004. os->start_pts = os->max_pts;
  1005. else
  1006. os->start_pts = pkt->pts;
  1007. }
  1008. if (os->max_pts == AV_NOPTS_VALUE)
  1009. os->max_pts = pkt->pts + pkt->duration;
  1010. else
  1011. os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
  1012. os->packets_written++;
  1013. return ff_write_chained(os->ctx, 0, pkt, s);
  1014. }
  1015. static int dash_write_trailer(AVFormatContext *s)
  1016. {
  1017. DASHContext *c = s->priv_data;
  1018. if (s->nb_streams > 0) {
  1019. OutputStream *os = &c->streams[0];
  1020. // If no segments have been written so far, try to do a crude
  1021. // guess of the segment duration
  1022. if (!c->last_duration)
  1023. c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
  1024. s->streams[0]->time_base,
  1025. AV_TIME_BASE_Q);
  1026. c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
  1027. s->streams[0]->time_base,
  1028. AV_TIME_BASE_Q);
  1029. }
  1030. dash_flush(s, 1, -1);
  1031. if (c->remove_at_exit) {
  1032. char filename[1024];
  1033. int i;
  1034. for (i = 0; i < s->nb_streams; i++) {
  1035. OutputStream *os = &c->streams[i];
  1036. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
  1037. unlink(filename);
  1038. }
  1039. unlink(s->filename);
  1040. }
  1041. dash_free(s);
  1042. return 0;
  1043. }
  1044. #define OFFSET(x) offsetof(DASHContext, x)
  1045. #define E AV_OPT_FLAG_ENCODING_PARAM
  1046. static const AVOption options[] = {
  1047. { "adaptation_sets", "Adaptation sets. Syntax: id=0,streams=0,1,2 id=1,streams=3,4 and so on", OFFSET(adaptation_sets), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
  1048. { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
  1049. { "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 },
  1050. { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
  1051. { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
  1052. { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
  1053. { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
  1054. { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
  1055. { "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 },
  1056. { "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 },
  1057. { "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 },
  1058. { "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, AV_OPT_FLAG_ENCODING_PARAM },
  1059. { NULL },
  1060. };
  1061. static const AVClass dash_class = {
  1062. .class_name = "dash muxer",
  1063. .item_name = av_default_item_name,
  1064. .option = options,
  1065. .version = LIBAVUTIL_VERSION_INT,
  1066. };
  1067. AVOutputFormat ff_dash_muxer = {
  1068. .name = "dash",
  1069. .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
  1070. .priv_data_size = sizeof(DASHContext),
  1071. .audio_codec = AV_CODEC_ID_AAC,
  1072. .video_codec = AV_CODEC_ID_H264,
  1073. .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
  1074. .write_header = dash_write_header,
  1075. .write_packet = dash_write_packet,
  1076. .write_trailer = dash_write_trailer,
  1077. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  1078. .priv_class = &dash_class,
  1079. };