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.

1234 lines
45KB

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