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.

592 lines
19KB

  1. /*
  2. * Live HDS fragmenter
  3. * Copyright (c) 2013 Martin Storsjo
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "config.h"
  22. #include <float.h>
  23. #if HAVE_UNISTD_H
  24. #include <unistd.h>
  25. #endif
  26. #include "avformat.h"
  27. #include "internal.h"
  28. #include "os_support.h"
  29. #include "libavutil/avstring.h"
  30. #include "libavutil/base64.h"
  31. #include "libavutil/intreadwrite.h"
  32. #include "libavutil/mathematics.h"
  33. #include "libavutil/opt.h"
  34. typedef struct Fragment {
  35. char file[1024];
  36. int64_t start_time, duration;
  37. int n;
  38. } Fragment;
  39. typedef struct OutputStream {
  40. int bitrate;
  41. int first_stream;
  42. AVFormatContext *ctx;
  43. int ctx_inited;
  44. uint8_t iobuf[32768];
  45. char temp_filename[1024];
  46. int64_t frag_start_ts, last_ts;
  47. AVIOContext *out;
  48. int packets_written;
  49. int nb_fragments, fragments_size, fragment_index;
  50. Fragment **fragments;
  51. int has_audio, has_video;
  52. uint8_t *metadata;
  53. int metadata_size;
  54. uint8_t *extra_packets[2];
  55. int extra_packet_sizes[2];
  56. int nb_extra_packets;
  57. } OutputStream;
  58. typedef struct HDSContext {
  59. const AVClass *class; /* Class for private options. */
  60. int window_size;
  61. int extra_window_size;
  62. int min_frag_duration;
  63. int remove_at_exit;
  64. OutputStream *streams;
  65. int nb_streams;
  66. } HDSContext;
  67. static int parse_header(OutputStream *os, const uint8_t *buf, int buf_size)
  68. {
  69. if (buf_size < 13)
  70. return AVERROR_INVALIDDATA;
  71. if (memcmp(buf, "FLV", 3))
  72. return AVERROR_INVALIDDATA;
  73. buf += 13;
  74. buf_size -= 13;
  75. while (buf_size >= 11 + 4) {
  76. int type = buf[0];
  77. int size = AV_RB24(&buf[1]) + 11 + 4;
  78. if (size > buf_size)
  79. return AVERROR_INVALIDDATA;
  80. if (type == 8 || type == 9) {
  81. if (os->nb_extra_packets >= FF_ARRAY_ELEMS(os->extra_packets))
  82. return AVERROR_INVALIDDATA;
  83. os->extra_packet_sizes[os->nb_extra_packets] = size;
  84. os->extra_packets[os->nb_extra_packets] = av_malloc(size);
  85. if (!os->extra_packets[os->nb_extra_packets])
  86. return AVERROR(ENOMEM);
  87. memcpy(os->extra_packets[os->nb_extra_packets], buf, size);
  88. os->nb_extra_packets++;
  89. } else if (type == 0x12) {
  90. if (os->metadata)
  91. return AVERROR_INVALIDDATA;
  92. os->metadata_size = size - 11 - 4;
  93. os->metadata = av_malloc(os->metadata_size);
  94. if (!os->metadata)
  95. return AVERROR(ENOMEM);
  96. memcpy(os->metadata, buf + 11, os->metadata_size);
  97. }
  98. buf += size;
  99. buf_size -= size;
  100. }
  101. if (!os->metadata)
  102. return AVERROR_INVALIDDATA;
  103. return 0;
  104. }
  105. static int hds_write(void *opaque, uint8_t *buf, int buf_size)
  106. {
  107. OutputStream *os = opaque;
  108. if (os->out) {
  109. avio_write(os->out, buf, buf_size);
  110. } else {
  111. if (!os->metadata_size) {
  112. int ret;
  113. // Assuming the IO buffer is large enough to fit the
  114. // FLV header and all metadata and extradata packets
  115. if ((ret = parse_header(os, buf, buf_size)) < 0)
  116. return ret;
  117. }
  118. }
  119. return buf_size;
  120. }
  121. static void hds_free(AVFormatContext *s)
  122. {
  123. HDSContext *c = s->priv_data;
  124. int i, j;
  125. if (!c->streams)
  126. return;
  127. for (i = 0; i < s->nb_streams; i++) {
  128. OutputStream *os = &c->streams[i];
  129. if (os->out)
  130. ff_format_io_close(s, &os->out);
  131. if (os->ctx && os->ctx_inited)
  132. av_write_trailer(os->ctx);
  133. if (os->ctx)
  134. avio_context_free(&os->ctx->pb);
  135. if (os->ctx)
  136. avformat_free_context(os->ctx);
  137. av_free(os->metadata);
  138. for (j = 0; j < os->nb_extra_packets; j++)
  139. av_free(os->extra_packets[j]);
  140. for (j = 0; j < os->nb_fragments; j++)
  141. av_free(os->fragments[j]);
  142. av_free(os->fragments);
  143. }
  144. av_freep(&c->streams);
  145. }
  146. static int write_manifest(AVFormatContext *s, int final)
  147. {
  148. HDSContext *c = s->priv_data;
  149. AVIOContext *out;
  150. char filename[1024], temp_filename[1024];
  151. int ret, i;
  152. float duration = 0;
  153. if (c->nb_streams > 0)
  154. duration = c->streams[0].last_ts * av_q2d(s->streams[0]->time_base);
  155. snprintf(filename, sizeof(filename), "%s/index.f4m", s->filename);
  156. snprintf(temp_filename, sizeof(temp_filename), "%s/index.f4m.tmp", s->filename);
  157. ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL);
  158. if (ret < 0) {
  159. av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
  160. return ret;
  161. }
  162. avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  163. avio_printf(out, "<manifest xmlns=\"http://ns.adobe.com/f4m/1.0\">\n");
  164. avio_printf(out, "\t<id>%s</id>\n", av_basename(s->filename));
  165. avio_printf(out, "\t<streamType>%s</streamType>\n",
  166. final ? "recorded" : "live");
  167. avio_printf(out, "\t<deliveryType>streaming</deliveryType>\n");
  168. if (final)
  169. avio_printf(out, "\t<duration>%f</duration>\n", duration);
  170. for (i = 0; i < c->nb_streams; i++) {
  171. OutputStream *os = &c->streams[i];
  172. int b64_size = AV_BASE64_SIZE(os->metadata_size);
  173. char *base64 = av_malloc(b64_size);
  174. if (!base64) {
  175. ff_format_io_close(s, &out);
  176. return AVERROR(ENOMEM);
  177. }
  178. av_base64_encode(base64, b64_size, os->metadata, os->metadata_size);
  179. avio_printf(out, "\t<bootstrapInfo profile=\"named\" url=\"stream%d.abst\" id=\"bootstrap%d\" />\n", i, i);
  180. avio_printf(out, "\t<media bitrate=\"%d\" url=\"stream%d\" bootstrapInfoId=\"bootstrap%d\">\n", os->bitrate/1000, i, i);
  181. avio_printf(out, "\t\t<metadata>%s</metadata>\n", base64);
  182. avio_printf(out, "\t</media>\n");
  183. av_free(base64);
  184. }
  185. avio_printf(out, "</manifest>\n");
  186. avio_flush(out);
  187. ff_format_io_close(s, &out);
  188. return ff_rename(temp_filename, filename);
  189. }
  190. static void update_size(AVIOContext *out, int64_t pos)
  191. {
  192. int64_t end = avio_tell(out);
  193. avio_seek(out, pos, SEEK_SET);
  194. avio_wb32(out, end - pos);
  195. avio_seek(out, end, SEEK_SET);
  196. }
  197. /* Note, the .abst files need to be served with the "binary/octet"
  198. * mime type, otherwise at least the OSMF player can easily fail
  199. * with "stream not found" when polling for the next fragment. */
  200. static int write_abst(AVFormatContext *s, OutputStream *os, int final)
  201. {
  202. HDSContext *c = s->priv_data;
  203. AVIOContext *out;
  204. char filename[1024], temp_filename[1024];
  205. int i, ret;
  206. int64_t asrt_pos, afrt_pos;
  207. int start = 0, fragments;
  208. int index = s->streams[os->first_stream]->id;
  209. int64_t cur_media_time = 0;
  210. if (c->window_size)
  211. start = FFMAX(os->nb_fragments - c->window_size, 0);
  212. fragments = os->nb_fragments - start;
  213. if (final)
  214. cur_media_time = os->last_ts;
  215. else if (os->nb_fragments)
  216. cur_media_time = os->fragments[os->nb_fragments - 1]->start_time;
  217. snprintf(filename, sizeof(filename),
  218. "%s/stream%d.abst", s->filename, index);
  219. snprintf(temp_filename, sizeof(temp_filename),
  220. "%s/stream%d.abst.tmp", s->filename, index);
  221. ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL);
  222. if (ret < 0) {
  223. av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
  224. return ret;
  225. }
  226. avio_wb32(out, 0); // abst size
  227. avio_wl32(out, MKTAG('a','b','s','t'));
  228. avio_wb32(out, 0); // version + flags
  229. avio_wb32(out, os->fragment_index - 1); // BootstrapinfoVersion
  230. avio_w8(out, final ? 0 : 0x20); // profile, live, update
  231. avio_wb32(out, 1000); // timescale
  232. avio_wb64(out, cur_media_time);
  233. avio_wb64(out, 0); // SmpteTimeCodeOffset
  234. avio_w8(out, 0); // MovieIdentifer (null string)
  235. avio_w8(out, 0); // ServerEntryCount
  236. avio_w8(out, 0); // QualityEntryCount
  237. avio_w8(out, 0); // DrmData (null string)
  238. avio_w8(out, 0); // MetaData (null string)
  239. avio_w8(out, 1); // SegmentRunTableCount
  240. asrt_pos = avio_tell(out);
  241. avio_wb32(out, 0); // asrt size
  242. avio_wl32(out, MKTAG('a','s','r','t'));
  243. avio_wb32(out, 0); // version + flags
  244. avio_w8(out, 0); // QualityEntryCount
  245. avio_wb32(out, 1); // SegmentRunEntryCount
  246. avio_wb32(out, 1); // FirstSegment
  247. avio_wb32(out, final ? (os->fragment_index - 1) : 0xffffffff); // FragmentsPerSegment
  248. update_size(out, asrt_pos);
  249. avio_w8(out, 1); // FragmentRunTableCount
  250. afrt_pos = avio_tell(out);
  251. avio_wb32(out, 0); // afrt size
  252. avio_wl32(out, MKTAG('a','f','r','t'));
  253. avio_wb32(out, 0); // version + flags
  254. avio_wb32(out, 1000); // timescale
  255. avio_w8(out, 0); // QualityEntryCount
  256. avio_wb32(out, fragments); // FragmentRunEntryCount
  257. for (i = start; i < os->nb_fragments; i++) {
  258. avio_wb32(out, os->fragments[i]->n);
  259. avio_wb64(out, os->fragments[i]->start_time);
  260. avio_wb32(out, os->fragments[i]->duration);
  261. }
  262. update_size(out, afrt_pos);
  263. update_size(out, 0);
  264. ff_format_io_close(s, &out);
  265. return ff_rename(temp_filename, filename);
  266. }
  267. static int init_file(AVFormatContext *s, OutputStream *os, int64_t start_ts)
  268. {
  269. int ret, i;
  270. ret = s->io_open(s, &os->out, os->temp_filename, AVIO_FLAG_WRITE, NULL);
  271. if (ret < 0)
  272. return ret;
  273. avio_wb32(os->out, 0);
  274. avio_wl32(os->out, MKTAG('m','d','a','t'));
  275. for (i = 0; i < os->nb_extra_packets; i++) {
  276. AV_WB24(os->extra_packets[i] + 4, start_ts);
  277. os->extra_packets[i][7] = (start_ts >> 24) & 0x7f;
  278. avio_write(os->out, os->extra_packets[i], os->extra_packet_sizes[i]);
  279. }
  280. return 0;
  281. }
  282. static void close_file(AVFormatContext *s, OutputStream *os)
  283. {
  284. int64_t pos = avio_tell(os->out);
  285. avio_seek(os->out, 0, SEEK_SET);
  286. avio_wb32(os->out, pos);
  287. avio_flush(os->out);
  288. ff_format_io_close(s, &os->out);
  289. }
  290. static int hds_write_header(AVFormatContext *s)
  291. {
  292. HDSContext *c = s->priv_data;
  293. int ret = 0, i;
  294. AVOutputFormat *oformat;
  295. if (mkdir(s->filename, 0777) == -1 && errno != EEXIST) {
  296. ret = AVERROR(errno);
  297. goto fail;
  298. }
  299. oformat = av_guess_format("flv", NULL, NULL);
  300. if (!oformat) {
  301. ret = AVERROR_MUXER_NOT_FOUND;
  302. goto fail;
  303. }
  304. c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
  305. if (!c->streams) {
  306. ret = AVERROR(ENOMEM);
  307. goto fail;
  308. }
  309. for (i = 0; i < s->nb_streams; i++) {
  310. OutputStream *os = &c->streams[c->nb_streams];
  311. AVFormatContext *ctx;
  312. AVStream *st = s->streams[i];
  313. if (!st->codecpar->bit_rate) {
  314. av_log(s, AV_LOG_ERROR, "No bit rate set for stream %d\n", i);
  315. ret = AVERROR(EINVAL);
  316. goto fail;
  317. }
  318. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  319. if (os->has_video) {
  320. c->nb_streams++;
  321. os++;
  322. }
  323. os->has_video = 1;
  324. } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  325. if (os->has_audio) {
  326. c->nb_streams++;
  327. os++;
  328. }
  329. os->has_audio = 1;
  330. } else {
  331. av_log(s, AV_LOG_ERROR, "Unsupported stream type in stream %d\n", i);
  332. ret = AVERROR(EINVAL);
  333. goto fail;
  334. }
  335. os->bitrate += s->streams[i]->codecpar->bit_rate;
  336. if (!os->ctx) {
  337. os->first_stream = i;
  338. ctx = avformat_alloc_context();
  339. if (!ctx) {
  340. ret = AVERROR(ENOMEM);
  341. goto fail;
  342. }
  343. os->ctx = ctx;
  344. ctx->oformat = oformat;
  345. ctx->interrupt_callback = s->interrupt_callback;
  346. ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf),
  347. AVIO_FLAG_WRITE, os,
  348. NULL, hds_write, NULL);
  349. if (!ctx->pb) {
  350. ret = AVERROR(ENOMEM);
  351. goto fail;
  352. }
  353. } else {
  354. ctx = os->ctx;
  355. }
  356. s->streams[i]->id = c->nb_streams;
  357. if (!(st = avformat_new_stream(ctx, NULL))) {
  358. ret = AVERROR(ENOMEM);
  359. goto fail;
  360. }
  361. avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
  362. st->codecpar->codec_tag = 0;
  363. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  364. st->time_base = s->streams[i]->time_base;
  365. }
  366. if (c->streams[c->nb_streams].ctx)
  367. c->nb_streams++;
  368. for (i = 0; i < c->nb_streams; i++) {
  369. OutputStream *os = &c->streams[i];
  370. int j;
  371. if ((ret = avformat_write_header(os->ctx, NULL)) < 0) {
  372. goto fail;
  373. }
  374. os->ctx_inited = 1;
  375. avio_flush(os->ctx->pb);
  376. for (j = 0; j < os->ctx->nb_streams; j++)
  377. s->streams[os->first_stream + j]->time_base = os->ctx->streams[j]->time_base;
  378. snprintf(os->temp_filename, sizeof(os->temp_filename),
  379. "%s/stream%d_temp", s->filename, i);
  380. ret = init_file(s, os, 0);
  381. if (ret < 0)
  382. goto fail;
  383. if (!os->has_video && c->min_frag_duration <= 0) {
  384. av_log(s, AV_LOG_WARNING,
  385. "No video stream in output stream %d and no min frag duration set\n", i);
  386. ret = AVERROR(EINVAL);
  387. }
  388. os->fragment_index = 1;
  389. write_abst(s, os, 0);
  390. }
  391. ret = write_manifest(s, 0);
  392. fail:
  393. if (ret)
  394. hds_free(s);
  395. return ret;
  396. }
  397. static int add_fragment(OutputStream *os, const char *file,
  398. int64_t start_time, int64_t duration)
  399. {
  400. Fragment *frag;
  401. if (duration == 0)
  402. duration = 1;
  403. if (os->nb_fragments >= os->fragments_size) {
  404. int ret;
  405. os->fragments_size = (os->fragments_size + 1) * 2;
  406. if ((ret = av_reallocp_array(&os->fragments, os->fragments_size,
  407. sizeof(*os->fragments))) < 0) {
  408. os->fragments_size = 0;
  409. os->nb_fragments = 0;
  410. return ret;
  411. }
  412. }
  413. frag = av_mallocz(sizeof(*frag));
  414. if (!frag)
  415. return AVERROR(ENOMEM);
  416. av_strlcpy(frag->file, file, sizeof(frag->file));
  417. frag->start_time = start_time;
  418. frag->duration = duration;
  419. frag->n = os->fragment_index;
  420. os->fragments[os->nb_fragments++] = frag;
  421. os->fragment_index++;
  422. return 0;
  423. }
  424. static int hds_flush(AVFormatContext *s, OutputStream *os, int final,
  425. int64_t end_ts)
  426. {
  427. HDSContext *c = s->priv_data;
  428. int i, ret = 0;
  429. char target_filename[1024];
  430. int index = s->streams[os->first_stream]->id;
  431. if (!os->packets_written)
  432. return 0;
  433. avio_flush(os->ctx->pb);
  434. os->packets_written = 0;
  435. close_file(s, os);
  436. snprintf(target_filename, sizeof(target_filename),
  437. "%s/stream%dSeg1-Frag%d", s->filename, index, os->fragment_index);
  438. ret = ff_rename(os->temp_filename, target_filename);
  439. if (ret < 0)
  440. return ret;
  441. add_fragment(os, target_filename, os->frag_start_ts, end_ts - os->frag_start_ts);
  442. if (!final) {
  443. ret = init_file(s, os, end_ts);
  444. if (ret < 0)
  445. return ret;
  446. }
  447. if (c->window_size || (final && c->remove_at_exit)) {
  448. int remove = os->nb_fragments - c->window_size - c->extra_window_size;
  449. if (final && c->remove_at_exit)
  450. remove = os->nb_fragments;
  451. if (remove > 0) {
  452. for (i = 0; i < remove; i++) {
  453. unlink(os->fragments[i]->file);
  454. av_free(os->fragments[i]);
  455. }
  456. os->nb_fragments -= remove;
  457. memmove(os->fragments, os->fragments + remove,
  458. os->nb_fragments * sizeof(*os->fragments));
  459. }
  460. }
  461. if (ret >= 0)
  462. ret = write_abst(s, os, final);
  463. return ret;
  464. }
  465. static int hds_write_packet(AVFormatContext *s, AVPacket *pkt)
  466. {
  467. HDSContext *c = s->priv_data;
  468. AVStream *st = s->streams[pkt->stream_index];
  469. OutputStream *os = &c->streams[s->streams[pkt->stream_index]->id];
  470. int64_t end_dts = os->fragment_index * (int64_t) c->min_frag_duration;
  471. int ret;
  472. if (st->first_dts == AV_NOPTS_VALUE)
  473. st->first_dts = pkt->dts;
  474. if ((!os->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
  475. av_compare_ts(pkt->dts - st->first_dts, st->time_base,
  476. end_dts, AV_TIME_BASE_Q) >= 0 &&
  477. pkt->flags & AV_PKT_FLAG_KEY && os->packets_written) {
  478. if ((ret = hds_flush(s, os, 0, pkt->dts)) < 0)
  479. return ret;
  480. }
  481. // Note, these fragment start timestamps, that represent a whole
  482. // OutputStream, assume all streams in it have the same time base.
  483. if (!os->packets_written)
  484. os->frag_start_ts = pkt->dts;
  485. os->last_ts = pkt->dts;
  486. os->packets_written++;
  487. return ff_write_chained(os->ctx, pkt->stream_index - os->first_stream, pkt, s);
  488. }
  489. static int hds_write_trailer(AVFormatContext *s)
  490. {
  491. HDSContext *c = s->priv_data;
  492. int i;
  493. for (i = 0; i < c->nb_streams; i++)
  494. hds_flush(s, &c->streams[i], 1, c->streams[i].last_ts);
  495. write_manifest(s, 1);
  496. if (c->remove_at_exit) {
  497. char filename[1024];
  498. snprintf(filename, sizeof(filename), "%s/index.f4m", s->filename);
  499. unlink(filename);
  500. for (i = 0; i < c->nb_streams; i++) {
  501. snprintf(filename, sizeof(filename), "%s/stream%d.abst", s->filename, i);
  502. unlink(filename);
  503. }
  504. rmdir(s->filename);
  505. }
  506. hds_free(s);
  507. return 0;
  508. }
  509. #define OFFSET(x) offsetof(HDSContext, x)
  510. #define E AV_OPT_FLAG_ENCODING_PARAM
  511. static const AVOption options[] = {
  512. { "window_size", "number of fragments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
  513. { "extra_window_size", "number of fragments kept outside of the manifest before removing from disk", OFFSET(extra_window_size), AV_OPT_TYPE_INT, { .i64 = 5 }, 0, INT_MAX, E },
  514. { "min_frag_duration", "minimum fragment duration (in microseconds)", OFFSET(min_frag_duration), AV_OPT_TYPE_INT64, { .i64 = 10000000 }, 0, INT_MAX, E },
  515. { "remove_at_exit", "remove all fragments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
  516. { NULL },
  517. };
  518. static const AVClass hds_class = {
  519. .class_name = "HDS muxer",
  520. .item_name = av_default_item_name,
  521. .option = options,
  522. .version = LIBAVUTIL_VERSION_INT,
  523. };
  524. AVOutputFormat ff_hds_muxer = {
  525. .name = "hds",
  526. .long_name = NULL_IF_CONFIG_SMALL("HDS Muxer"),
  527. .priv_data_size = sizeof(HDSContext),
  528. .audio_codec = AV_CODEC_ID_AAC,
  529. .video_codec = AV_CODEC_ID_H264,
  530. .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE,
  531. .write_header = hds_write_header,
  532. .write_packet = hds_write_packet,
  533. .write_trailer = hds_write_trailer,
  534. .priv_class = &hds_class,
  535. };