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.

1629 lines
61KB

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