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.

1181 lines
43KB

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