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.

1447 lines
53KB

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