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.

1535 lines
57KB

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