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.

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