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.

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