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.

1689 lines
63KB

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