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.

668 lines
23KB

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