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.

1471 lines
54KB

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