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.

595 lines
19KB

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