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.

1218 lines
44KB

  1. /*
  2. * MPEG-DASH ISO BMFF segmenter
  3. * Copyright (c) 2014 Martin Storsjo
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "config.h"
  22. #if HAVE_UNISTD_H
  23. #include <unistd.h>
  24. #endif
  25. #include "libavutil/avassert.h"
  26. #include "libavutil/avutil.h"
  27. #include "libavutil/avstring.h"
  28. #include "libavutil/intreadwrite.h"
  29. #include "libavutil/mathematics.h"
  30. #include "libavutil/opt.h"
  31. #include "libavutil/rational.h"
  32. #include "libavutil/time_internal.h"
  33. #include "avc.h"
  34. #include "avformat.h"
  35. #include "avio_internal.h"
  36. #include "internal.h"
  37. #include "isom.h"
  38. #include "os_support.h"
  39. #include "url.h"
  40. #include "dash.h"
  41. typedef struct Segment {
  42. char file[1024];
  43. int64_t start_pos;
  44. int range_length, index_length;
  45. int64_t time;
  46. int duration;
  47. int n;
  48. } Segment;
  49. typedef struct AdaptationSet {
  50. char id[10];
  51. enum AVMediaType media_type;
  52. AVDictionary *metadata;
  53. } AdaptationSet;
  54. typedef struct OutputStream {
  55. AVFormatContext *ctx;
  56. int ctx_inited, as_idx;
  57. AVIOContext *out;
  58. char format_name[8];
  59. int packets_written;
  60. char initfile[1024];
  61. int64_t init_start_pos, pos;
  62. int init_range_length;
  63. int nb_segments, segments_size, segment_index;
  64. Segment **segments;
  65. int64_t first_pts, start_pts, max_pts;
  66. int64_t last_dts;
  67. int bit_rate;
  68. char bandwidth_str[64];
  69. char codec_str[100];
  70. } OutputStream;
  71. typedef struct DASHContext {
  72. const AVClass *class; /* Class for private options. */
  73. char *adaptation_sets;
  74. AdaptationSet *as;
  75. int nb_as;
  76. int window_size;
  77. int extra_window_size;
  78. int min_seg_duration;
  79. int remove_at_exit;
  80. int use_template;
  81. int use_timeline;
  82. int single_file;
  83. OutputStream *streams;
  84. int has_video;
  85. int64_t last_duration;
  86. int64_t total_duration;
  87. char availability_start_time[100];
  88. char dirname[1024];
  89. const char *single_file_name;
  90. const char *init_seg_name;
  91. const char *media_seg_name;
  92. AVRational min_frame_rate, max_frame_rate;
  93. int ambiguous_frame_rate;
  94. const char *utc_timing_url;
  95. } DASHContext;
  96. static struct codec_string {
  97. int id;
  98. const char *str;
  99. } codecs[] = {
  100. { AV_CODEC_ID_VP8, "vp8" },
  101. { AV_CODEC_ID_VP9, "vp9" },
  102. { AV_CODEC_ID_VORBIS, "vorbis" },
  103. { AV_CODEC_ID_OPUS, "opus" },
  104. { 0, NULL }
  105. };
  106. static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
  107. char *str, int size)
  108. {
  109. const AVCodecTag *tags[2] = { NULL, NULL };
  110. uint32_t tag;
  111. int i;
  112. // common Webm codecs are not part of RFC 6381
  113. for (i = 0; codecs[i].id; i++)
  114. if (codecs[i].id == par->codec_id) {
  115. av_strlcpy(str, codecs[i].str, size);
  116. return;
  117. }
  118. // for codecs part of RFC 6381
  119. if (par->codec_type == AVMEDIA_TYPE_VIDEO)
  120. tags[0] = ff_codec_movvideo_tags;
  121. else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
  122. tags[0] = ff_codec_movaudio_tags;
  123. else
  124. return;
  125. tag = av_codec_get_tag(tags, par->codec_id);
  126. if (!tag)
  127. return;
  128. if (size < 5)
  129. return;
  130. AV_WL32(str, tag);
  131. str[4] = '\0';
  132. if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
  133. uint32_t oti;
  134. tags[0] = ff_mp4_obj_type;
  135. oti = av_codec_get_tag(tags, par->codec_id);
  136. if (oti)
  137. av_strlcatf(str, size, ".%02"PRIx32, oti);
  138. else
  139. return;
  140. if (tag == MKTAG('m', 'p', '4', 'a')) {
  141. if (par->extradata_size >= 2) {
  142. int aot = par->extradata[0] >> 3;
  143. if (aot == 31)
  144. aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
  145. av_strlcatf(str, size, ".%d", aot);
  146. }
  147. } else if (tag == MKTAG('m', 'p', '4', 'v')) {
  148. // Unimplemented, should output ProfileLevelIndication as a decimal number
  149. av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
  150. }
  151. } else if (!strcmp(str, "avc1")) {
  152. uint8_t *tmpbuf = NULL;
  153. uint8_t *extradata = par->extradata;
  154. int extradata_size = par->extradata_size;
  155. if (!extradata_size)
  156. return;
  157. if (extradata[0] != 1) {
  158. AVIOContext *pb;
  159. if (avio_open_dyn_buf(&pb) < 0)
  160. return;
  161. if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
  162. ffio_free_dyn_buf(&pb);
  163. return;
  164. }
  165. extradata_size = avio_close_dyn_buf(pb, &extradata);
  166. tmpbuf = extradata;
  167. }
  168. if (extradata_size >= 4)
  169. av_strlcatf(str, size, ".%02x%02x%02x",
  170. extradata[1], extradata[2], extradata[3]);
  171. av_free(tmpbuf);
  172. }
  173. }
  174. static int flush_dynbuf(OutputStream *os, int *range_length)
  175. {
  176. uint8_t *buffer;
  177. if (!os->ctx->pb) {
  178. return AVERROR(EINVAL);
  179. }
  180. // flush
  181. av_write_frame(os->ctx, NULL);
  182. avio_flush(os->ctx->pb);
  183. // write out to file
  184. *range_length = avio_close_dyn_buf(os->ctx->pb, &buffer);
  185. os->ctx->pb = NULL;
  186. avio_write(os->out, buffer, *range_length);
  187. av_free(buffer);
  188. // re-open buffer
  189. return avio_open_dyn_buf(&os->ctx->pb);
  190. }
  191. static int flush_init_segment(AVFormatContext *s, OutputStream *os)
  192. {
  193. DASHContext *c = s->priv_data;
  194. int ret, range_length;
  195. ret = flush_dynbuf(os, &range_length);
  196. if (ret < 0)
  197. return ret;
  198. os->pos = os->init_range_length = range_length;
  199. if (!c->single_file)
  200. ff_format_io_close(s, &os->out);
  201. return 0;
  202. }
  203. static void dash_free(AVFormatContext *s)
  204. {
  205. DASHContext *c = s->priv_data;
  206. int i, j;
  207. if (c->as) {
  208. for (i = 0; i < c->nb_as; i++)
  209. av_dict_free(&c->as[i].metadata);
  210. av_freep(&c->as);
  211. c->nb_as = 0;
  212. }
  213. if (!c->streams)
  214. return;
  215. for (i = 0; i < s->nb_streams; i++) {
  216. OutputStream *os = &c->streams[i];
  217. if (os->ctx && os->ctx_inited)
  218. av_write_trailer(os->ctx);
  219. if (os->ctx && os->ctx->pb)
  220. ffio_free_dyn_buf(&os->ctx->pb);
  221. ff_format_io_close(s, &os->out);
  222. if (os->ctx)
  223. avformat_free_context(os->ctx);
  224. for (j = 0; j < os->nb_segments; j++)
  225. av_free(os->segments[j]);
  226. av_free(os->segments);
  227. }
  228. av_freep(&c->streams);
  229. }
  230. static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c)
  231. {
  232. int i, start_index = 0, start_number = 1;
  233. if (c->window_size) {
  234. start_index = FFMAX(os->nb_segments - c->window_size, 0);
  235. start_number = FFMAX(os->segment_index - c->window_size, 1);
  236. }
  237. if (c->use_template) {
  238. int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
  239. avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
  240. if (!c->use_timeline)
  241. avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);
  242. avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
  243. if (c->use_timeline) {
  244. int64_t cur_time = 0;
  245. avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
  246. for (i = start_index; i < os->nb_segments; ) {
  247. Segment *seg = os->segments[i];
  248. int repeat = 0;
  249. avio_printf(out, "\t\t\t\t\t\t<S ");
  250. if (i == start_index || seg->time != cur_time) {
  251. cur_time = seg->time;
  252. avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
  253. }
  254. avio_printf(out, "d=\"%d\" ", seg->duration);
  255. while (i + repeat + 1 < os->nb_segments &&
  256. os->segments[i + repeat + 1]->duration == seg->duration &&
  257. os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
  258. repeat++;
  259. if (repeat > 0)
  260. avio_printf(out, "r=\"%d\" ", repeat);
  261. avio_printf(out, "/>\n");
  262. i += 1 + repeat;
  263. cur_time += (1 + repeat) * seg->duration;
  264. }
  265. avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
  266. }
  267. avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
  268. } else if (c->single_file) {
  269. avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
  270. avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
  271. 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);
  272. for (i = start_index; i < os->nb_segments; i++) {
  273. Segment *seg = os->segments[i];
  274. avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
  275. if (seg->index_length)
  276. avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
  277. avio_printf(out, "/>\n");
  278. }
  279. avio_printf(out, "\t\t\t\t</SegmentList>\n");
  280. } else {
  281. avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
  282. avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
  283. for (i = start_index; i < os->nb_segments; i++) {
  284. Segment *seg = os->segments[i];
  285. avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
  286. }
  287. avio_printf(out, "\t\t\t\t</SegmentList>\n");
  288. }
  289. }
  290. static char *xmlescape(const char *str) {
  291. int outlen = strlen(str)*3/2 + 6;
  292. char *out = av_realloc(NULL, outlen + 1);
  293. int pos = 0;
  294. if (!out)
  295. return NULL;
  296. for (; *str; str++) {
  297. if (pos + 6 > outlen) {
  298. char *tmp;
  299. outlen = 2 * outlen + 6;
  300. tmp = av_realloc(out, outlen + 1);
  301. if (!tmp) {
  302. av_free(out);
  303. return NULL;
  304. }
  305. out = tmp;
  306. }
  307. if (*str == '&') {
  308. memcpy(&out[pos], "&amp;", 5);
  309. pos += 5;
  310. } else if (*str == '<') {
  311. memcpy(&out[pos], "&lt;", 4);
  312. pos += 4;
  313. } else if (*str == '>') {
  314. memcpy(&out[pos], "&gt;", 4);
  315. pos += 4;
  316. } else if (*str == '\'') {
  317. memcpy(&out[pos], "&apos;", 6);
  318. pos += 6;
  319. } else if (*str == '\"') {
  320. memcpy(&out[pos], "&quot;", 6);
  321. pos += 6;
  322. } else {
  323. out[pos++] = *str;
  324. }
  325. }
  326. out[pos] = '\0';
  327. return out;
  328. }
  329. static void write_time(AVIOContext *out, int64_t time)
  330. {
  331. int seconds = time / AV_TIME_BASE;
  332. int fractions = time % AV_TIME_BASE;
  333. int minutes = seconds / 60;
  334. int hours = minutes / 60;
  335. seconds %= 60;
  336. minutes %= 60;
  337. avio_printf(out, "PT");
  338. if (hours)
  339. avio_printf(out, "%dH", hours);
  340. if (hours || minutes)
  341. avio_printf(out, "%dM", minutes);
  342. avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
  343. }
  344. static void format_date_now(char *buf, int size)
  345. {
  346. time_t t = time(NULL);
  347. struct tm *ptm, tmbuf;
  348. ptm = gmtime_r(&t, &tmbuf);
  349. if (ptm) {
  350. if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", ptm))
  351. buf[0] = '\0';
  352. }
  353. }
  354. static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index)
  355. {
  356. DASHContext *c = s->priv_data;
  357. AdaptationSet *as = &c->as[as_index];
  358. AVDictionaryEntry *lang, *role;
  359. int i;
  360. avio_printf(out, "\t\t<AdaptationSet id=\"%s\" contentType=\"%s\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
  361. as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
  362. if (as->media_type == AVMEDIA_TYPE_VIDEO && c->max_frame_rate.num && !c->ambiguous_frame_rate)
  363. avio_printf(out, " %s=\"%d/%d\"", (av_cmp_q(c->min_frame_rate, c->max_frame_rate) < 0) ? "maxFrameRate" : "frameRate", c->max_frame_rate.num, c->max_frame_rate.den);
  364. lang = av_dict_get(as->metadata, "language", NULL, 0);
  365. if (lang)
  366. avio_printf(out, " lang=\"%s\"", lang->value);
  367. avio_printf(out, ">\n");
  368. role = av_dict_get(as->metadata, "role", NULL, 0);
  369. if (role)
  370. avio_printf(out, "\t\t\t<Role schemeIdUri=\"urn:mpeg:dash:role:2011\" value=\"%s\"/>\n", role->value);
  371. for (i = 0; i < s->nb_streams; i++) {
  372. OutputStream *os = &c->streams[i];
  373. if (os->as_idx - 1 != as_index)
  374. continue;
  375. if (as->media_type == AVMEDIA_TYPE_VIDEO) {
  376. AVStream *st = s->streams[i];
  377. avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/%s\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"",
  378. i, os->format_name, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
  379. if (st->avg_frame_rate.num)
  380. avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
  381. avio_printf(out, ">\n");
  382. } else {
  383. avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/%s\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
  384. i, os->format_name, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->sample_rate);
  385. avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
  386. s->streams[i]->codecpar->channels);
  387. }
  388. output_segment_list(os, out, c);
  389. avio_printf(out, "\t\t\t</Representation>\n");
  390. }
  391. avio_printf(out, "\t\t</AdaptationSet>\n");
  392. return 0;
  393. }
  394. static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
  395. {
  396. DASHContext *c = s->priv_data;
  397. void *mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
  398. if (!mem)
  399. return AVERROR(ENOMEM);
  400. c->as = mem;
  401. ++c->nb_as;
  402. *as = &c->as[c->nb_as - 1];
  403. memset(*as, 0, sizeof(**as));
  404. (*as)->media_type = type;
  405. return 0;
  406. }
  407. static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
  408. {
  409. DASHContext *c = s->priv_data;
  410. AdaptationSet *as = &c->as[as_idx - 1];
  411. OutputStream *os = &c->streams[i];
  412. if (as->media_type != s->streams[i]->codecpar->codec_type) {
  413. av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
  414. return AVERROR(EINVAL);
  415. } else if (os->as_idx) {
  416. av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
  417. return AVERROR(EINVAL);
  418. }
  419. os->as_idx = as_idx;
  420. return 0;
  421. }
  422. static int parse_adaptation_sets(AVFormatContext *s)
  423. {
  424. DASHContext *c = s->priv_data;
  425. const char *p = c->adaptation_sets;
  426. enum { new_set, parse_id, parsing_streams } state;
  427. AdaptationSet *as;
  428. int i, n, ret;
  429. // default: one AdaptationSet for each stream
  430. if (!p) {
  431. for (i = 0; i < s->nb_streams; i++) {
  432. if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
  433. return ret;
  434. snprintf(as->id, sizeof(as->id), "%d", i);
  435. c->streams[i].as_idx = c->nb_as;
  436. }
  437. goto end;
  438. }
  439. // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
  440. state = new_set;
  441. while (*p) {
  442. if (*p == ' ') {
  443. p++;
  444. continue;
  445. } else if (state == new_set && av_strstart(p, "id=", &p)) {
  446. if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
  447. return ret;
  448. n = strcspn(p, ",");
  449. snprintf(as->id, sizeof(as->id), "%.*s", n, p);
  450. p += n;
  451. if (*p)
  452. p++;
  453. state = parse_id;
  454. } else if (state == parse_id && av_strstart(p, "streams=", &p)) {
  455. state = parsing_streams;
  456. } else if (state == parsing_streams) {
  457. AdaptationSet *as = &c->as[c->nb_as - 1];
  458. char idx_str[8], *end_str;
  459. n = strcspn(p, " ,");
  460. snprintf(idx_str, sizeof(idx_str), "%.*s", n, p);
  461. p += n;
  462. // if value is "a" or "v", map all streams of that type
  463. if (as->media_type == AVMEDIA_TYPE_UNKNOWN && (idx_str[0] == 'v' || idx_str[0] == 'a')) {
  464. enum AVMediaType type = (idx_str[0] == 'v') ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
  465. av_log(s, AV_LOG_DEBUG, "Map all streams of type %s\n", idx_str);
  466. for (i = 0; i < s->nb_streams; i++) {
  467. if (s->streams[i]->codecpar->codec_type != type)
  468. continue;
  469. as->media_type = s->streams[i]->codecpar->codec_type;
  470. if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
  471. return ret;
  472. }
  473. } else { // select single stream
  474. i = strtol(idx_str, &end_str, 10);
  475. if (idx_str == end_str || i < 0 || i >= s->nb_streams) {
  476. av_log(s, AV_LOG_ERROR, "Selected stream \"%s\" not found!\n", idx_str);
  477. return AVERROR(EINVAL);
  478. }
  479. av_log(s, AV_LOG_DEBUG, "Map stream %d\n", i);
  480. if (as->media_type == AVMEDIA_TYPE_UNKNOWN) {
  481. as->media_type = s->streams[i]->codecpar->codec_type;
  482. }
  483. if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
  484. return ret;
  485. }
  486. if (*p == ' ')
  487. state = new_set;
  488. if (*p)
  489. p++;
  490. } else {
  491. return AVERROR(EINVAL);
  492. }
  493. }
  494. end:
  495. // check for unassigned streams
  496. for (i = 0; i < s->nb_streams; i++) {
  497. OutputStream *os = &c->streams[i];
  498. if (!os->as_idx) {
  499. av_log(s, AV_LOG_ERROR, "Stream %d is not mapped to an AdaptationSet\n", i);
  500. return AVERROR(EINVAL);
  501. }
  502. }
  503. return 0;
  504. }
  505. static int write_manifest(AVFormatContext *s, int final)
  506. {
  507. DASHContext *c = s->priv_data;
  508. AVIOContext *out;
  509. char temp_filename[1024];
  510. int ret, i;
  511. const char *proto = avio_find_protocol_name(s->filename);
  512. int use_rename = proto && !strcmp(proto, "file");
  513. static unsigned int warned_non_file = 0;
  514. AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
  515. if (!use_rename && !warned_non_file++)
  516. av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
  517. snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename);
  518. ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL);
  519. if (ret < 0) {
  520. av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
  521. return ret;
  522. }
  523. avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  524. avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
  525. "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
  526. "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
  527. "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
  528. "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
  529. "\ttype=\"%s\"\n", final ? "static" : "dynamic");
  530. if (final) {
  531. avio_printf(out, "\tmediaPresentationDuration=\"");
  532. write_time(out, c->total_duration);
  533. avio_printf(out, "\"\n");
  534. } else {
  535. int64_t update_period = c->last_duration / AV_TIME_BASE;
  536. char now_str[100];
  537. if (c->use_template && !c->use_timeline)
  538. update_period = 500;
  539. avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
  540. avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
  541. if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
  542. format_date_now(c->availability_start_time, sizeof(c->availability_start_time));
  543. }
  544. if (c->availability_start_time[0])
  545. avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
  546. format_date_now(now_str, sizeof(now_str));
  547. if (now_str[0])
  548. avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
  549. if (c->window_size && c->use_template) {
  550. avio_printf(out, "\ttimeShiftBufferDepth=\"");
  551. write_time(out, c->last_duration * c->window_size);
  552. avio_printf(out, "\"\n");
  553. }
  554. }
  555. avio_printf(out, "\tminBufferTime=\"");
  556. write_time(out, c->last_duration * 2);
  557. avio_printf(out, "\">\n");
  558. avio_printf(out, "\t<ProgramInformation>\n");
  559. if (title) {
  560. char *escaped = xmlescape(title->value);
  561. avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
  562. av_free(escaped);
  563. }
  564. avio_printf(out, "\t</ProgramInformation>\n");
  565. if (c->utc_timing_url)
  566. avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
  567. if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
  568. OutputStream *os = &c->streams[0];
  569. int start_index = FFMAX(os->nb_segments - c->window_size, 0);
  570. int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
  571. avio_printf(out, "\t<Period id=\"0\" start=\"");
  572. write_time(out, start_time);
  573. avio_printf(out, "\">\n");
  574. } else {
  575. avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
  576. }
  577. for (i = 0; i < c->nb_as; i++) {
  578. if ((ret = write_adaptation_set(s, out, i)) < 0)
  579. return ret;
  580. }
  581. avio_printf(out, "\t</Period>\n");
  582. avio_printf(out, "</MPD>\n");
  583. avio_flush(out);
  584. ff_format_io_close(s, &out);
  585. if (use_rename)
  586. return avpriv_io_move(temp_filename, s->filename);
  587. return 0;
  588. }
  589. static int dict_copy_entry(AVDictionary **dst, const AVDictionary *src, const char *key)
  590. {
  591. AVDictionaryEntry *entry = av_dict_get(src, key, NULL, 0);
  592. if (entry)
  593. av_dict_set(dst, key, entry->value, AV_DICT_DONT_OVERWRITE);
  594. return 0;
  595. }
  596. static int dict_set_int(AVDictionary **pm, const char *key, int64_t value, int flags)
  597. {
  598. char valuestr[22];
  599. snprintf(valuestr, sizeof(valuestr), "%"PRId64, value);
  600. flags &= ~AV_DICT_DONT_STRDUP_VAL;
  601. return av_dict_set(pm, key, valuestr, flags);
  602. }
  603. static int dash_init(AVFormatContext *s)
  604. {
  605. DASHContext *c = s->priv_data;
  606. int ret = 0, i;
  607. char *ptr;
  608. char basename[1024];
  609. if (c->single_file_name)
  610. c->single_file = 1;
  611. if (c->single_file)
  612. c->use_template = 0;
  613. c->ambiguous_frame_rate = 0;
  614. av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
  615. ptr = strrchr(c->dirname, '/');
  616. if (ptr) {
  617. av_strlcpy(basename, &ptr[1], sizeof(basename));
  618. ptr[1] = '\0';
  619. } else {
  620. c->dirname[0] = '\0';
  621. av_strlcpy(basename, s->filename, sizeof(basename));
  622. }
  623. ptr = strrchr(basename, '.');
  624. if (ptr)
  625. *ptr = '\0';
  626. c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
  627. if (!c->streams)
  628. return AVERROR(ENOMEM);
  629. if ((ret = parse_adaptation_sets(s)) < 0)
  630. return ret;
  631. for (i = 0; i < s->nb_streams; i++) {
  632. OutputStream *os = &c->streams[i];
  633. AdaptationSet *as = &c->as[os->as_idx - 1];
  634. AVFormatContext *ctx;
  635. AVStream *st;
  636. AVDictionary *opts = NULL;
  637. char filename[1024];
  638. os->bit_rate = s->streams[i]->codecpar->bit_rate;
  639. if (os->bit_rate) {
  640. snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
  641. " bandwidth=\"%d\"", os->bit_rate);
  642. } else {
  643. int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
  644. AV_LOG_ERROR : AV_LOG_WARNING;
  645. av_log(s, level, "No bit rate set for stream %d\n", i);
  646. if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
  647. return AVERROR(EINVAL);
  648. }
  649. // copy AdaptationSet language and role from stream metadata
  650. dict_copy_entry(&as->metadata, s->streams[i]->metadata, "language");
  651. dict_copy_entry(&as->metadata, s->streams[i]->metadata, "role");
  652. ctx = avformat_alloc_context();
  653. if (!ctx)
  654. return AVERROR(ENOMEM);
  655. // choose muxer based on codec: webm for VP8/9 and opus, mp4 otherwise
  656. // note: os->format_name is also used as part of the mimetype of the
  657. // representation, e.g. video/<format_name>
  658. if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP8 ||
  659. s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP9 ||
  660. s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||
  661. s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VORBIS) {
  662. snprintf(os->format_name, sizeof(os->format_name), "webm");
  663. } else {
  664. snprintf(os->format_name, sizeof(os->format_name), "mp4");
  665. }
  666. ctx->oformat = av_guess_format(os->format_name, NULL, NULL);
  667. if (!ctx->oformat)
  668. return AVERROR_MUXER_NOT_FOUND;
  669. os->ctx = ctx;
  670. ctx->interrupt_callback = s->interrupt_callback;
  671. ctx->opaque = s->opaque;
  672. ctx->io_close = s->io_close;
  673. ctx->io_open = s->io_open;
  674. if (!(st = avformat_new_stream(ctx, NULL)))
  675. return AVERROR(ENOMEM);
  676. avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
  677. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  678. st->time_base = s->streams[i]->time_base;
  679. ctx->avoid_negative_ts = s->avoid_negative_ts;
  680. ctx->flags = s->flags;
  681. if ((ret = avio_open_dyn_buf(&ctx->pb)) < 0)
  682. return ret;
  683. if (c->single_file) {
  684. if (c->single_file_name)
  685. ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
  686. else
  687. snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
  688. } else {
  689. ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
  690. }
  691. snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
  692. ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, NULL);
  693. if (ret < 0)
  694. return ret;
  695. os->init_start_pos = 0;
  696. if (!strcmp(os->format_name, "mp4")) {
  697. av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
  698. } else {
  699. dict_set_int(&opts, "cluster_time_limit", c->min_seg_duration / 1000, 0);
  700. dict_set_int(&opts, "cluster_size_limit", 5 * 1024 * 1024, 0); // set a large cluster size limit
  701. }
  702. if ((ret = avformat_write_header(ctx, &opts)) < 0)
  703. return ret;
  704. os->ctx_inited = 1;
  705. avio_flush(ctx->pb);
  706. av_dict_free(&opts);
  707. av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
  708. // Flush init segment
  709. // except for mp4, since delay_moov is set and the init segment
  710. // is then flushed after the first packets
  711. if (strcmp(os->format_name, "mp4")) {
  712. flush_init_segment(s, os);
  713. }
  714. s->streams[i]->time_base = st->time_base;
  715. // If the muxer wants to shift timestamps, request to have them shifted
  716. // already before being handed to this muxer, so we don't have mismatches
  717. // between the MPD and the actual segments.
  718. s->avoid_negative_ts = ctx->avoid_negative_ts;
  719. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  720. AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
  721. if (avg_frame_rate.num > 0) {
  722. if (av_cmp_q(avg_frame_rate, c->min_frame_rate) < 0)
  723. c->min_frame_rate = avg_frame_rate;
  724. if (av_cmp_q(c->max_frame_rate, avg_frame_rate) < 0)
  725. c->max_frame_rate = avg_frame_rate;
  726. } else {
  727. c->ambiguous_frame_rate = 1;
  728. }
  729. c->has_video = 1;
  730. }
  731. set_codec_str(s, st->codecpar, os->codec_str, sizeof(os->codec_str));
  732. os->first_pts = AV_NOPTS_VALUE;
  733. os->max_pts = AV_NOPTS_VALUE;
  734. os->last_dts = AV_NOPTS_VALUE;
  735. os->segment_index = 1;
  736. }
  737. if (!c->has_video && c->min_seg_duration <= 0) {
  738. av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
  739. return AVERROR(EINVAL);
  740. }
  741. return 0;
  742. }
  743. static int dash_write_header(AVFormatContext *s)
  744. {
  745. DASHContext *c = s->priv_data;
  746. int i, ret;
  747. for (i = 0; i < s->nb_streams; i++) {
  748. OutputStream *os = &c->streams[i];
  749. if ((ret = avformat_write_header(os->ctx, NULL)) < 0) {
  750. dash_free(s);
  751. return ret;
  752. }
  753. }
  754. ret = write_manifest(s, 0);
  755. if (!ret)
  756. av_log(s, AV_LOG_VERBOSE, "Manifest written to: %s\n", s->filename);
  757. return ret;
  758. }
  759. static int add_segment(OutputStream *os, const char *file,
  760. int64_t time, int duration,
  761. int64_t start_pos, int64_t range_length,
  762. int64_t index_length)
  763. {
  764. int err;
  765. Segment *seg;
  766. if (os->nb_segments >= os->segments_size) {
  767. os->segments_size = (os->segments_size + 1) * 2;
  768. if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
  769. os->segments_size)) < 0) {
  770. os->segments_size = 0;
  771. os->nb_segments = 0;
  772. return err;
  773. }
  774. }
  775. seg = av_mallocz(sizeof(*seg));
  776. if (!seg)
  777. return AVERROR(ENOMEM);
  778. av_strlcpy(seg->file, file, sizeof(seg->file));
  779. seg->time = time;
  780. seg->duration = duration;
  781. if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
  782. seg->duration += seg->time;
  783. seg->time = 0;
  784. }
  785. seg->start_pos = start_pos;
  786. seg->range_length = range_length;
  787. seg->index_length = index_length;
  788. os->segments[os->nb_segments++] = seg;
  789. os->segment_index++;
  790. return 0;
  791. }
  792. static void write_styp(AVIOContext *pb)
  793. {
  794. avio_wb32(pb, 24);
  795. ffio_wfourcc(pb, "styp");
  796. ffio_wfourcc(pb, "msdh");
  797. avio_wb32(pb, 0); /* minor */
  798. ffio_wfourcc(pb, "msdh");
  799. ffio_wfourcc(pb, "msix");
  800. }
  801. static void find_index_range(AVFormatContext *s, const char *full_path,
  802. int64_t pos, int *index_length)
  803. {
  804. uint8_t buf[8];
  805. AVIOContext *pb;
  806. int ret;
  807. ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
  808. if (ret < 0)
  809. return;
  810. if (avio_seek(pb, pos, SEEK_SET) != pos) {
  811. ff_format_io_close(s, &pb);
  812. return;
  813. }
  814. ret = avio_read(pb, buf, 8);
  815. ff_format_io_close(s, &pb);
  816. if (ret < 8)
  817. return;
  818. if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
  819. return;
  820. *index_length = AV_RB32(&buf[0]);
  821. }
  822. static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
  823. AVCodecParameters *par)
  824. {
  825. uint8_t *extradata;
  826. if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
  827. return 0;
  828. extradata = av_malloc(par->extradata_size);
  829. if (!extradata)
  830. return AVERROR(ENOMEM);
  831. memcpy(extradata, par->extradata, par->extradata_size);
  832. os->ctx->streams[0]->codecpar->extradata = extradata;
  833. os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
  834. set_codec_str(s, par, os->codec_str, sizeof(os->codec_str));
  835. return 0;
  836. }
  837. static int dash_flush(AVFormatContext *s, int final, int stream)
  838. {
  839. DASHContext *c = s->priv_data;
  840. int i, ret = 0;
  841. const char *proto = avio_find_protocol_name(s->filename);
  842. int use_rename = proto && !strcmp(proto, "file");
  843. int cur_flush_segment_index = 0;
  844. if (stream >= 0)
  845. cur_flush_segment_index = c->streams[stream].segment_index;
  846. for (i = 0; i < s->nb_streams; i++) {
  847. OutputStream *os = &c->streams[i];
  848. char filename[1024] = "", full_path[1024], temp_path[1024];
  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. flush_init_segment(s, os);
  865. }
  866. if (!c->single_file) {
  867. ff_dash_fill_tmpl_params(filename, sizeof(filename), c->media_seg_name, i, os->segment_index, os->bit_rate, os->start_pts);
  868. snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
  869. snprintf(temp_path, sizeof(temp_path), use_rename ? "%s.tmp" : "%s", full_path);
  870. ret = s->io_open(s, &os->out, temp_path, AVIO_FLAG_WRITE, NULL);
  871. if (ret < 0)
  872. break;
  873. if (!strcmp(os->format_name, "mp4"))
  874. write_styp(os->ctx->pb);
  875. } else {
  876. snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, os->initfile);
  877. }
  878. ret = flush_dynbuf(os, &range_length);
  879. if (ret < 0)
  880. break;
  881. os->packets_written = 0;
  882. if (c->single_file) {
  883. find_index_range(s, full_path, os->pos, &index_length);
  884. } else {
  885. ff_format_io_close(s, &os->out);
  886. if (use_rename) {
  887. ret = avpriv_io_move(temp_path, full_path);
  888. if (ret < 0)
  889. break;
  890. }
  891. }
  892. if (!os->bit_rate) {
  893. // calculate average bitrate of first segment
  894. int64_t bitrate = (int64_t) range_length * 8 * AV_TIME_BASE / (os->max_pts - os->start_pts);
  895. if (bitrate >= 0) {
  896. os->bit_rate = bitrate;
  897. snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
  898. " bandwidth=\"%d\"", os->bit_rate);
  899. }
  900. }
  901. add_segment(os, filename, os->start_pts, os->max_pts - os->start_pts, os->pos, range_length, index_length);
  902. av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, full_path);
  903. os->pos += range_length;
  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, 0);
  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. return 0;
  1020. }
  1021. static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
  1022. {
  1023. DASHContext *c = s->priv_data;
  1024. OutputStream *os = &c->streams[avpkt->stream_index];
  1025. AVFormatContext *oc = os->ctx;
  1026. if (oc->oformat->check_bitstream) {
  1027. int ret;
  1028. AVPacket pkt = *avpkt;
  1029. pkt.stream_index = 0;
  1030. ret = oc->oformat->check_bitstream(oc, &pkt);
  1031. if (ret == 1) {
  1032. AVStream *st = s->streams[avpkt->stream_index];
  1033. AVStream *ost = oc->streams[0];
  1034. st->internal->bsfcs = ost->internal->bsfcs;
  1035. st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
  1036. ost->internal->bsfcs = NULL;
  1037. ost->internal->nb_bsfcs = 0;
  1038. }
  1039. return ret;
  1040. }
  1041. return 1;
  1042. }
  1043. #define OFFSET(x) offsetof(DASHContext, x)
  1044. #define E AV_OPT_FLAG_ENCODING_PARAM
  1045. static const AVOption options[] = {
  1046. { "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 },
  1047. { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
  1048. { "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 },
  1049. { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
  1050. { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
  1051. { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
  1052. { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
  1053. { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
  1054. { "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 },
  1055. { "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 },
  1056. { "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 },
  1057. { "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, E },
  1058. { NULL },
  1059. };
  1060. static const AVClass dash_class = {
  1061. .class_name = "dash muxer",
  1062. .item_name = av_default_item_name,
  1063. .option = options,
  1064. .version = LIBAVUTIL_VERSION_INT,
  1065. };
  1066. AVOutputFormat ff_dash_muxer = {
  1067. .name = "dash",
  1068. .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
  1069. .priv_data_size = sizeof(DASHContext),
  1070. .audio_codec = AV_CODEC_ID_AAC,
  1071. .video_codec = AV_CODEC_ID_H264,
  1072. .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
  1073. .init = dash_init,
  1074. .write_header = dash_write_header,
  1075. .write_packet = dash_write_packet,
  1076. .write_trailer = dash_write_trailer,
  1077. .deinit = dash_free,
  1078. .check_bitstream = dash_check_bitstream,
  1079. .priv_class = &dash_class,
  1080. };