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.

1423 lines
52KB

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