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.

1585 lines
59KB

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