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.

644 lines
22KB

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