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.

651 lines
22KB

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