smoothstreamingenc.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. /*
  2. * Live smooth streaming fragmenter
  3. * Copyright (c) 2012 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 "internal.h"
  28. #include "os_support.h"
  29. #include "avc.h"
  30. #include "url.h"
  31. #include "isom.h"
  32. #include "libavutil/opt.h"
  33. #include "libavutil/avstring.h"
  34. #include "libavutil/mathematics.h"
  35. #include "libavutil/intreadwrite.h"
  36. typedef struct {
  37. char file[1024];
  38. char infofile[1024];
  39. int64_t start_time, duration;
  40. int n;
  41. int64_t start_pos, size;
  42. } Fragment;
  43. typedef struct {
  44. AVFormatContext *ctx;
  45. int ctx_inited;
  46. char dirname[1024];
  47. uint8_t iobuf[32768];
  48. URLContext *out; // Current output stream where all output is written
  49. URLContext *out2; // Auxillary output stream where all output also is written
  50. URLContext *tail_out; // The actual main output stream, if we're currently seeked back to write elsewhere
  51. int64_t tail_pos, cur_pos, cur_start_pos;
  52. int packets_written;
  53. const char *stream_type_tag;
  54. int nb_fragments, fragments_size, fragment_index;
  55. Fragment **fragments;
  56. const char *fourcc;
  57. char *private_str;
  58. int packet_size;
  59. int audio_tag;
  60. } OutputStream;
  61. typedef struct {
  62. const AVClass *class; /* Class for private options. */
  63. int window_size;
  64. int extra_window_size;
  65. int lookahead_count;
  66. int min_frag_duration;
  67. int remove_at_exit;
  68. OutputStream *streams;
  69. int has_video, has_audio;
  70. int nb_fragments;
  71. } SmoothStreamingContext;
  72. static int ism_write(void *opaque, uint8_t *buf, int buf_size)
  73. {
  74. OutputStream *os = opaque;
  75. if (os->out)
  76. ffurl_write(os->out, buf, buf_size);
  77. if (os->out2)
  78. ffurl_write(os->out2, buf, buf_size);
  79. os->cur_pos += buf_size;
  80. if (os->cur_pos >= os->tail_pos)
  81. os->tail_pos = os->cur_pos;
  82. return buf_size;
  83. }
  84. static int64_t ism_seek(void *opaque, int64_t offset, int whence)
  85. {
  86. OutputStream *os = opaque;
  87. int i;
  88. if (whence != SEEK_SET)
  89. return AVERROR(ENOSYS);
  90. if (os->tail_out) {
  91. if (os->out) {
  92. ffurl_close(os->out);
  93. }
  94. if (os->out2) {
  95. ffurl_close(os->out2);
  96. }
  97. os->out = os->tail_out;
  98. os->out2 = NULL;
  99. os->tail_out = NULL;
  100. }
  101. if (offset >= os->cur_start_pos) {
  102. ffurl_seek(os->out, offset - os->cur_start_pos, SEEK_SET);
  103. os->cur_pos = offset;
  104. return offset;
  105. }
  106. for (i = os->nb_fragments - 1; i >= 0; i--) {
  107. Fragment *frag = os->fragments[i];
  108. if (offset >= frag->start_pos && offset < frag->start_pos + frag->size) {
  109. int ret;
  110. AVDictionary *opts = NULL;
  111. os->tail_out = os->out;
  112. av_dict_set(&opts, "truncate", "0", 0);
  113. ret = ffurl_open(&os->out, frag->file, AVIO_FLAG_READ_WRITE, &os->ctx->interrupt_callback, &opts);
  114. av_dict_free(&opts);
  115. if (ret < 0) {
  116. os->out = os->tail_out;
  117. os->tail_out = NULL;
  118. return ret;
  119. }
  120. av_dict_set(&opts, "truncate", "0", 0);
  121. ffurl_open(&os->out2, frag->infofile, AVIO_FLAG_READ_WRITE, &os->ctx->interrupt_callback, &opts);
  122. av_dict_free(&opts);
  123. ffurl_seek(os->out, offset - frag->start_pos, SEEK_SET);
  124. if (os->out2)
  125. ffurl_seek(os->out2, offset - frag->start_pos, SEEK_SET);
  126. os->cur_pos = offset;
  127. return offset;
  128. }
  129. }
  130. return AVERROR(EIO);
  131. }
  132. static void get_private_data(OutputStream *os)
  133. {
  134. AVCodecContext *codec = os->ctx->streams[0]->codec;
  135. uint8_t *ptr = codec->extradata;
  136. int size = codec->extradata_size;
  137. int i;
  138. if (codec->codec_id == AV_CODEC_ID_H264) {
  139. ff_avc_write_annexb_extradata(ptr, &ptr, &size);
  140. if (!ptr)
  141. ptr = codec->extradata;
  142. }
  143. if (!ptr)
  144. return;
  145. os->private_str = av_mallocz(2*size + 1);
  146. for (i = 0; i < size; i++)
  147. snprintf(&os->private_str[2*i], 3, "%02x", ptr[i]);
  148. if (ptr != codec->extradata)
  149. av_free(ptr);
  150. }
  151. static void ism_free(AVFormatContext *s)
  152. {
  153. SmoothStreamingContext *c = s->priv_data;
  154. int i, j;
  155. if (!c->streams)
  156. return;
  157. for (i = 0; i < s->nb_streams; i++) {
  158. OutputStream *os = &c->streams[i];
  159. ffurl_close(os->out);
  160. ffurl_close(os->out2);
  161. ffurl_close(os->tail_out);
  162. os->out = os->out2 = os->tail_out = NULL;
  163. if (os->ctx && os->ctx_inited)
  164. av_write_trailer(os->ctx);
  165. if (os->ctx && os->ctx->pb)
  166. av_free(os->ctx->pb);
  167. if (os->ctx)
  168. avformat_free_context(os->ctx);
  169. av_free(os->private_str);
  170. for (j = 0; j < os->nb_fragments; j++)
  171. av_free(os->fragments[j]);
  172. av_free(os->fragments);
  173. }
  174. av_freep(&c->streams);
  175. }
  176. static int ism_write_header(AVFormatContext *s)
  177. {
  178. SmoothStreamingContext *c = s->priv_data;
  179. int ret = 0, i;
  180. AVOutputFormat *oformat;
  181. ret = mkdir(s->filename, 0777);
  182. if (ret) {
  183. av_log(s, AV_LOG_ERROR, "mkdir(%s): %s\n", s->filename, strerror(errno));
  184. return AVERROR(errno);
  185. }
  186. ret = 0;
  187. oformat = av_guess_format("ismv", NULL, NULL);
  188. if (!oformat) {
  189. ret = AVERROR_MUXER_NOT_FOUND;
  190. goto fail;
  191. }
  192. c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
  193. if (!c->streams) {
  194. ret = AVERROR(ENOMEM);
  195. goto fail;
  196. }
  197. for (i = 0; i < s->nb_streams; i++) {
  198. OutputStream *os = &c->streams[i];
  199. AVFormatContext *ctx;
  200. AVStream *st;
  201. AVDictionary *opts = NULL;
  202. char buf[10];
  203. if (!s->streams[i]->codec->bit_rate) {
  204. av_log(s, AV_LOG_ERROR, "No bit rate set for stream %d\n", i);
  205. ret = AVERROR(EINVAL);
  206. goto fail;
  207. }
  208. snprintf(os->dirname, sizeof(os->dirname), "%s/QualityLevels(%d)", s->filename, s->streams[i]->codec->bit_rate);
  209. mkdir(os->dirname, 0777);
  210. ctx = avformat_alloc_context();
  211. if (!ctx) {
  212. ret = AVERROR(ENOMEM);
  213. goto fail;
  214. }
  215. os->ctx = ctx;
  216. ctx->oformat = oformat;
  217. ctx->interrupt_callback = s->interrupt_callback;
  218. if (!(st = avformat_new_stream(ctx, NULL))) {
  219. ret = AVERROR(ENOMEM);
  220. goto fail;
  221. }
  222. avcodec_copy_context(st->codec, s->streams[i]->codec);
  223. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  224. ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, ism_write, ism_seek);
  225. if (!ctx->pb) {
  226. ret = AVERROR(ENOMEM);
  227. goto fail;
  228. }
  229. snprintf(buf, sizeof(buf), "%d", c->lookahead_count);
  230. av_dict_set(&opts, "ism_lookahead", buf, 0);
  231. av_dict_set(&opts, "movflags", "frag_custom", 0);
  232. if ((ret = avformat_write_header(ctx, &opts)) < 0) {
  233. goto fail;
  234. }
  235. os->ctx_inited = 1;
  236. avio_flush(ctx->pb);
  237. av_dict_free(&opts);
  238. s->streams[i]->time_base = st->time_base;
  239. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  240. c->has_video = 1;
  241. os->stream_type_tag = "video";
  242. if (st->codec->codec_id == AV_CODEC_ID_H264) {
  243. os->fourcc = "H264";
  244. } else if (st->codec->codec_id == AV_CODEC_ID_VC1) {
  245. os->fourcc = "WVC1";
  246. } else {
  247. av_log(s, AV_LOG_ERROR, "Unsupported video codec\n");
  248. ret = AVERROR(EINVAL);
  249. goto fail;
  250. }
  251. } else {
  252. c->has_audio = 1;
  253. os->stream_type_tag = "audio";
  254. if (st->codec->codec_id == AV_CODEC_ID_AAC) {
  255. os->fourcc = "AACL";
  256. os->audio_tag = 0xff;
  257. } else if (st->codec->codec_id == AV_CODEC_ID_WMAPRO) {
  258. os->fourcc = "WMAP";
  259. os->audio_tag = 0x0162;
  260. } else {
  261. av_log(s, AV_LOG_ERROR, "Unsupported audio codec\n");
  262. ret = AVERROR(EINVAL);
  263. goto fail;
  264. }
  265. os->packet_size = st->codec->block_align ? st->codec->block_align : 4;
  266. }
  267. get_private_data(os);
  268. }
  269. if (!c->has_video && c->min_frag_duration <= 0) {
  270. av_log(s, AV_LOG_WARNING, "no video stream and no min frag duration set\n");
  271. ret = AVERROR(EINVAL);
  272. }
  273. fail:
  274. if (ret)
  275. ism_free(s);
  276. return ret;
  277. }
  278. static int parse_fragment(AVFormatContext *s, const char *filename, int64_t *start_ts, int64_t *duration, int64_t *moof_size, int64_t size)
  279. {
  280. AVIOContext *in;
  281. int ret;
  282. uint32_t len;
  283. if ((ret = avio_open2(&in, filename, AVIO_FLAG_READ, &s->interrupt_callback, NULL)) < 0)
  284. return ret;
  285. ret = AVERROR(EIO);
  286. *moof_size = avio_rb32(in);
  287. if (*moof_size < 8 || *moof_size > size)
  288. goto fail;
  289. if (avio_rl32(in) != MKTAG('m','o','o','f'))
  290. goto fail;
  291. len = avio_rb32(in);
  292. if (len > *moof_size)
  293. goto fail;
  294. if (avio_rl32(in) != MKTAG('m','f','h','d'))
  295. goto fail;
  296. avio_seek(in, len - 8, SEEK_CUR);
  297. avio_rb32(in); /* traf size */
  298. if (avio_rl32(in) != MKTAG('t','r','a','f'))
  299. goto fail;
  300. while (avio_tell(in) < *moof_size) {
  301. uint32_t len = avio_rb32(in);
  302. uint32_t tag = avio_rl32(in);
  303. int64_t end = avio_tell(in) + len - 8;
  304. if (len < 8 || len >= *moof_size)
  305. goto fail;
  306. if (tag == MKTAG('u','u','i','d')) {
  307. const uint8_t tfxd[] = {
  308. 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
  309. 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
  310. };
  311. uint8_t uuid[16];
  312. avio_read(in, uuid, 16);
  313. if (!memcmp(uuid, tfxd, 16) && len >= 8 + 16 + 4 + 16) {
  314. avio_seek(in, 4, SEEK_CUR);
  315. *start_ts = avio_rb64(in);
  316. *duration = avio_rb64(in);
  317. ret = 0;
  318. break;
  319. }
  320. }
  321. avio_seek(in, end, SEEK_SET);
  322. }
  323. fail:
  324. avio_close(in);
  325. return ret;
  326. }
  327. static int add_fragment(OutputStream *os, const char *file, const char *infofile, int64_t start_time, int64_t duration, int64_t start_pos, int64_t size)
  328. {
  329. Fragment *frag;
  330. if (os->nb_fragments >= os->fragments_size) {
  331. os->fragments_size = (os->fragments_size + 1) * 2;
  332. os->fragments = av_realloc(os->fragments, sizeof(*os->fragments)*os->fragments_size);
  333. if (!os->fragments)
  334. return AVERROR(ENOMEM);
  335. }
  336. frag = av_mallocz(sizeof(*frag));
  337. if (!frag)
  338. return AVERROR(ENOMEM);
  339. av_strlcpy(frag->file, file, sizeof(frag->file));
  340. av_strlcpy(frag->infofile, infofile, sizeof(frag->infofile));
  341. frag->start_time = start_time;
  342. frag->duration = duration;
  343. frag->start_pos = start_pos;
  344. frag->size = size;
  345. frag->n = os->fragment_index;
  346. os->fragments[os->nb_fragments++] = frag;
  347. os->fragment_index++;
  348. return 0;
  349. }
  350. static int copy_moof(AVFormatContext *s, const char* infile, const char *outfile, int64_t size)
  351. {
  352. AVIOContext *in, *out;
  353. int ret = 0;
  354. if ((ret = avio_open2(&in, infile, AVIO_FLAG_READ, &s->interrupt_callback, NULL)) < 0)
  355. return ret;
  356. if ((ret = avio_open2(&out, outfile, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL)) < 0) {
  357. avio_close(in);
  358. return ret;
  359. }
  360. while (size > 0) {
  361. uint8_t buf[8192];
  362. int n = FFMIN(size, sizeof(buf));
  363. n = avio_read(in, buf, n);
  364. if (n <= 0) {
  365. ret = AVERROR(EIO);
  366. break;
  367. }
  368. avio_write(out, buf, n);
  369. size -= n;
  370. }
  371. avio_flush(out);
  372. avio_close(out);
  373. avio_close(in);
  374. return ret;
  375. }
  376. static void output_chunk_list(OutputStream *os, AVIOContext *out, int final, int skip, int window_size)
  377. {
  378. int removed = 0, i, start = 0;
  379. if (os->nb_fragments <= 0)
  380. return;
  381. if (os->fragments[0]->n > 0)
  382. removed = 1;
  383. if (final)
  384. skip = 0;
  385. if (window_size)
  386. start = FFMAX(os->nb_fragments - skip - window_size, 0);
  387. for (i = start; i < os->nb_fragments - skip; i++) {
  388. Fragment *frag = os->fragments[i];
  389. if (!final || removed)
  390. avio_printf(out, "<c t=\"%"PRIu64"\" d=\"%"PRIu64"\" />\n", frag->start_time, frag->duration);
  391. else
  392. avio_printf(out, "<c n=\"%d\" d=\"%"PRIu64"\" />\n", frag->n, frag->duration);
  393. }
  394. }
  395. static int write_manifest(AVFormatContext *s, int final)
  396. {
  397. SmoothStreamingContext *c = s->priv_data;
  398. AVIOContext *out;
  399. char filename[1024];
  400. int ret, i, video_chunks = 0, audio_chunks = 0, video_streams = 0, audio_streams = 0;
  401. int64_t duration = 0;
  402. snprintf(filename, sizeof(filename), "%s/Manifest", s->filename);
  403. ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
  404. if (ret < 0)
  405. return ret;
  406. avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  407. for (i = 0; i < s->nb_streams; i++) {
  408. OutputStream *os = &c->streams[i];
  409. if (os->nb_fragments > 0) {
  410. Fragment *last = os->fragments[os->nb_fragments - 1];
  411. duration = last->start_time + last->duration;
  412. }
  413. if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  414. video_chunks = os->nb_fragments;
  415. video_streams++;
  416. } else {
  417. audio_chunks = os->nb_fragments;
  418. audio_streams++;
  419. }
  420. }
  421. if (!final) {
  422. duration = 0;
  423. video_chunks = audio_chunks = 0;
  424. }
  425. if (c->window_size) {
  426. video_chunks = FFMIN(video_chunks, c->window_size);
  427. audio_chunks = FFMIN(audio_chunks, c->window_size);
  428. }
  429. avio_printf(out, "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" Duration=\"%"PRIu64"\"", duration);
  430. if (!final)
  431. avio_printf(out, " IsLive=\"true\" LookAheadFragmentCount=\"%d\" DVRWindowLength=\"0\"", c->lookahead_count);
  432. avio_printf(out, ">\n");
  433. if (c->has_video) {
  434. int last = -1, index = 0;
  435. avio_printf(out, "<StreamIndex Type=\"video\" QualityLevels=\"%d\" Chunks=\"%d\" Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n", video_streams, video_chunks);
  436. for (i = 0; i < s->nb_streams; i++) {
  437. OutputStream *os = &c->streams[i];
  438. if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
  439. continue;
  440. last = i;
  441. avio_printf(out, "<QualityLevel Index=\"%d\" Bitrate=\"%d\" FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" CodecPrivateData=\"%s\" />\n", index, s->streams[i]->codec->bit_rate, os->fourcc, s->streams[i]->codec->width, s->streams[i]->codec->height, os->private_str);
  442. index++;
  443. }
  444. output_chunk_list(&c->streams[last], out, final, c->lookahead_count, c->window_size);
  445. avio_printf(out, "</StreamIndex>\n");
  446. }
  447. if (c->has_audio) {
  448. int last = -1, index = 0;
  449. avio_printf(out, "<StreamIndex Type=\"audio\" QualityLevels=\"%d\" Chunks=\"%d\" Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n", audio_streams, audio_chunks);
  450. for (i = 0; i < s->nb_streams; i++) {
  451. OutputStream *os = &c->streams[i];
  452. if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
  453. continue;
  454. last = i;
  455. avio_printf(out, "<QualityLevel Index=\"%d\" Bitrate=\"%d\" FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" BitsPerSample=\"16\" PacketSize=\"%d\" AudioTag=\"%d\" CodecPrivateData=\"%s\" />\n", index, s->streams[i]->codec->bit_rate, os->fourcc, s->streams[i]->codec->sample_rate, s->streams[i]->codec->channels, os->packet_size, os->audio_tag, os->private_str);
  456. index++;
  457. }
  458. output_chunk_list(&c->streams[last], out, final, c->lookahead_count, c->window_size);
  459. avio_printf(out, "</StreamIndex>\n");
  460. }
  461. avio_printf(out, "</SmoothStreamingMedia>\n");
  462. avio_flush(out);
  463. avio_close(out);
  464. return 0;
  465. }
  466. static int ism_flush(AVFormatContext *s, int final)
  467. {
  468. SmoothStreamingContext *c = s->priv_data;
  469. int i, ret = 0;
  470. for (i = 0; i < s->nb_streams; i++) {
  471. OutputStream *os = &c->streams[i];
  472. char filename[1024], target_filename[1024], header_filename[1024];
  473. int64_t start_pos = os->tail_pos, size;
  474. int64_t start_ts, duration, moof_size;
  475. if (!os->packets_written)
  476. continue;
  477. snprintf(filename, sizeof(filename), "%s/temp", os->dirname);
  478. ret = ffurl_open(&os->out, filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
  479. if (ret < 0)
  480. break;
  481. os->cur_start_pos = os->tail_pos;
  482. av_write_frame(os->ctx, NULL);
  483. avio_flush(os->ctx->pb);
  484. os->packets_written = 0;
  485. if (!os->out || os->tail_out)
  486. return AVERROR(EIO);
  487. ffurl_close(os->out);
  488. os->out = NULL;
  489. size = os->tail_pos - start_pos;
  490. if ((ret = parse_fragment(s, filename, &start_ts, &duration, &moof_size, size)) < 0)
  491. break;
  492. snprintf(header_filename, sizeof(header_filename), "%s/FragmentInfo(%s=%"PRIu64")", os->dirname, os->stream_type_tag, start_ts);
  493. snprintf(target_filename, sizeof(target_filename), "%s/Fragments(%s=%"PRIu64")", os->dirname, os->stream_type_tag, start_ts);
  494. copy_moof(s, filename, header_filename, moof_size);
  495. rename(filename, target_filename);
  496. add_fragment(os, target_filename, header_filename, start_ts, duration, start_pos, size);
  497. }
  498. if (c->window_size || (final && c->remove_at_exit)) {
  499. for (i = 0; i < s->nb_streams; i++) {
  500. OutputStream *os = &c->streams[i];
  501. int j;
  502. int remove = os->nb_fragments - c->window_size - c->extra_window_size - c->lookahead_count;
  503. if (final && c->remove_at_exit)
  504. remove = os->nb_fragments;
  505. if (remove > 0) {
  506. for (j = 0; j < remove; j++) {
  507. unlink(os->fragments[j]->file);
  508. unlink(os->fragments[j]->infofile);
  509. av_free(os->fragments[j]);
  510. }
  511. os->nb_fragments -= remove;
  512. memmove(os->fragments, os->fragments + remove, os->nb_fragments * sizeof(*os->fragments));
  513. }
  514. if (final && c->remove_at_exit)
  515. rmdir(os->dirname);
  516. }
  517. }
  518. write_manifest(s, final);
  519. return ret;
  520. }
  521. static int ism_write_packet(AVFormatContext *s, AVPacket *pkt)
  522. {
  523. SmoothStreamingContext *c = s->priv_data;
  524. AVStream *st = s->streams[pkt->stream_index];
  525. OutputStream *os = &c->streams[pkt->stream_index];
  526. int64_t end_pts = (c->nb_fragments + 1) * c->min_frag_duration;
  527. if ((!c->has_video || st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
  528. av_compare_ts(pkt->pts, st->time_base,
  529. end_pts, AV_TIME_BASE_Q) >= 0 &&
  530. pkt->flags & AV_PKT_FLAG_KEY && os->packets_written) {
  531. ism_flush(s, 0);
  532. c->nb_fragments++;
  533. }
  534. os->packets_written++;
  535. return ff_write_chained(os->ctx, 0, pkt, s);
  536. }
  537. static int ism_write_trailer(AVFormatContext *s)
  538. {
  539. SmoothStreamingContext *c = s->priv_data;
  540. ism_flush(s, 1);
  541. if (c->remove_at_exit) {
  542. char filename[1024];
  543. snprintf(filename, sizeof(filename), "%s/Manifest", s->filename);
  544. unlink(filename);
  545. rmdir(s->filename);
  546. }
  547. ism_free(s);
  548. return 0;
  549. }
  550. #define OFFSET(x) offsetof(SmoothStreamingContext, x)
  551. #define E AV_OPT_FLAG_ENCODING_PARAM
  552. static const AVOption options[] = {
  553. { "window_size", "number of fragments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
  554. { "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 },
  555. { "lookahead_count", "number of lookahead fragments", OFFSET(lookahead_count), AV_OPT_TYPE_INT, { .i64 = 2 }, 0, INT_MAX, E },
  556. { "min_frag_duration", "minimum fragment duration (in microseconds)", OFFSET(min_frag_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
  557. { "remove_at_exit", "remove all fragments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
  558. { NULL },
  559. };
  560. static const AVClass ism_class = {
  561. .class_name = "smooth streaming muxer",
  562. .item_name = av_default_item_name,
  563. .option = options,
  564. .version = LIBAVUTIL_VERSION_INT,
  565. };
  566. AVOutputFormat ff_smoothstreaming_muxer = {
  567. .name = "smoothstreaming",
  568. .long_name = NULL_IF_CONFIG_SMALL("Smooth Streaming Muxer"),
  569. .priv_data_size = sizeof(SmoothStreamingContext),
  570. .audio_codec = AV_CODEC_ID_AAC,
  571. .video_codec = AV_CODEC_ID_H264,
  572. .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE,
  573. .write_header = ism_write_header,
  574. .write_packet = ism_write_packet,
  575. .write_trailer = ism_write_trailer,
  576. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  577. .priv_class = &ism_class,
  578. };