ismindex.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. /*
  2. * Copyright (c) 2012 Martin Storsjo
  3. *
  4. * This file is part of Libav.
  5. *
  6. * Libav is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * Libav is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with Libav; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /*
  21. * To create a simple file for smooth streaming:
  22. * ffmpeg <normal input/transcoding options> -movflags frag_keyframe foo.ismv
  23. * ismindex -n foo foo.ismv
  24. * This step creates foo.ism and foo.ismc that is required by IIS for
  25. * serving it.
  26. *
  27. * To pre-split files for serving as static files by a web server without
  28. * any extra server support, create the ismv file as above, and split it:
  29. * ismindex -split foo.ismv
  30. * This step creates a file Manifest and directories QualityLevel(...),
  31. * that can be read directly by a smooth streaming player.
  32. */
  33. #include <stdio.h>
  34. #include <string.h>
  35. #include <sys/stat.h>
  36. #ifdef _WIN32
  37. #include <direct.h>
  38. #define mkdir(a, b) _mkdir(a)
  39. #endif
  40. #include "cmdutils.h"
  41. #include "libavformat/avformat.h"
  42. #include "libavutil/intreadwrite.h"
  43. #include "libavutil/mathematics.h"
  44. static int usage(const char *argv0, int ret)
  45. {
  46. fprintf(stderr, "%s [-split] [-n basename] file1 [file2] ...\n", argv0);
  47. return ret;
  48. }
  49. struct MoofOffset {
  50. int64_t time;
  51. int64_t offset;
  52. int duration;
  53. };
  54. struct VideoFile {
  55. const char *name;
  56. int64_t duration;
  57. int bitrate;
  58. int track_id;
  59. int is_audio, is_video;
  60. int width, height;
  61. int chunks;
  62. int sample_rate, channels;
  63. uint8_t *codec_private;
  64. int codec_private_size;
  65. struct MoofOffset *offsets;
  66. int timescale;
  67. const char *fourcc;
  68. int blocksize;
  69. int tag;
  70. };
  71. struct VideoFiles {
  72. int nb_files;
  73. int64_t duration;
  74. struct VideoFile **files;
  75. int video_file, audio_file;
  76. int nb_video_files, nb_audio_files;
  77. };
  78. static int copy_tag(AVIOContext *in, AVIOContext *out, int32_t tag_name)
  79. {
  80. int32_t size, tag;
  81. size = avio_rb32(in);
  82. tag = avio_rb32(in);
  83. avio_wb32(out, size);
  84. avio_wb32(out, tag);
  85. if (tag != tag_name)
  86. return -1;
  87. size -= 8;
  88. while (size > 0) {
  89. char buf[1024];
  90. int len = FFMIN(sizeof(buf), size);
  91. if (avio_read(in, buf, len) != len)
  92. break;
  93. avio_write(out, buf, len);
  94. size -= len;
  95. }
  96. return 0;
  97. }
  98. static int write_fragment(const char *filename, AVIOContext *in)
  99. {
  100. AVIOContext *out = NULL;
  101. int ret;
  102. if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, NULL, NULL)) < 0)
  103. return ret;
  104. copy_tag(in, out, MKBETAG('m', 'o', 'o', 'f'));
  105. copy_tag(in, out, MKBETAG('m', 'd', 'a', 't'));
  106. avio_flush(out);
  107. avio_close(out);
  108. return ret;
  109. }
  110. static int write_fragments(struct VideoFiles *files, int start_index,
  111. AVIOContext *in)
  112. {
  113. char dirname[100], filename[500];
  114. int i, j;
  115. for (i = start_index; i < files->nb_files; i++) {
  116. struct VideoFile *vf = files->files[i];
  117. const char *type = vf->is_video ? "video" : "audio";
  118. snprintf(dirname, sizeof(dirname), "QualityLevels(%d)", vf->bitrate);
  119. mkdir(dirname, 0777);
  120. for (j = 0; j < vf->chunks; j++) {
  121. snprintf(filename, sizeof(filename), "%s/Fragments(%s=%"PRId64")",
  122. dirname, type, vf->offsets[j].time);
  123. avio_seek(in, vf->offsets[j].offset, SEEK_SET);
  124. write_fragment(filename, in);
  125. }
  126. }
  127. return 0;
  128. }
  129. static int read_tfra(struct VideoFiles *files, int start_index, AVIOContext *f)
  130. {
  131. int ret = AVERROR_EOF, track_id;
  132. int version, fieldlength, i, j;
  133. int64_t pos = avio_tell(f);
  134. uint32_t size = avio_rb32(f);
  135. struct VideoFile *vf = NULL;
  136. if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a'))
  137. goto fail;
  138. version = avio_r8(f);
  139. avio_rb24(f);
  140. track_id = avio_rb32(f); /* track id */
  141. for (i = start_index; i < files->nb_files && !vf; i++)
  142. if (files->files[i]->track_id == track_id)
  143. vf = files->files[i];
  144. if (!vf) {
  145. /* Ok, continue parsing the next atom */
  146. ret = 0;
  147. goto fail;
  148. }
  149. fieldlength = avio_rb32(f);
  150. vf->chunks = avio_rb32(f);
  151. vf->offsets = av_mallocz(sizeof(*vf->offsets) * vf->chunks);
  152. if (!vf->offsets) {
  153. ret = AVERROR(ENOMEM);
  154. goto fail;
  155. }
  156. for (i = 0; i < vf->chunks; i++) {
  157. if (version == 1) {
  158. vf->offsets[i].time = avio_rb64(f);
  159. vf->offsets[i].offset = avio_rb64(f);
  160. } else {
  161. vf->offsets[i].time = avio_rb32(f);
  162. vf->offsets[i].offset = avio_rb32(f);
  163. }
  164. for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
  165. avio_r8(f);
  166. for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
  167. avio_r8(f);
  168. for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
  169. avio_r8(f);
  170. if (i > 0)
  171. vf->offsets[i - 1].duration = vf->offsets[i].time -
  172. vf->offsets[i - 1].time;
  173. }
  174. if (vf->chunks > 0)
  175. vf->offsets[vf->chunks - 1].duration = vf->duration -
  176. vf->offsets[vf->chunks - 1].time;
  177. ret = 0;
  178. fail:
  179. avio_seek(f, pos + size, SEEK_SET);
  180. return ret;
  181. }
  182. static int read_mfra(struct VideoFiles *files, int start_index,
  183. const char *file, int split)
  184. {
  185. int err = 0;
  186. AVIOContext *f = NULL;
  187. int32_t mfra_size;
  188. if ((err = avio_open2(&f, file, AVIO_FLAG_READ, NULL, NULL)) < 0)
  189. goto fail;
  190. avio_seek(f, avio_size(f) - 4, SEEK_SET);
  191. mfra_size = avio_rb32(f);
  192. avio_seek(f, -mfra_size, SEEK_CUR);
  193. if (avio_rb32(f) != mfra_size) {
  194. err = AVERROR_INVALIDDATA;
  195. goto fail;
  196. }
  197. if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
  198. err = AVERROR_INVALIDDATA;
  199. goto fail;
  200. }
  201. while (!read_tfra(files, start_index, f)) {
  202. /* Empty */
  203. }
  204. if (split)
  205. write_fragments(files, start_index, f);
  206. fail:
  207. if (f)
  208. avio_close(f);
  209. if (err)
  210. fprintf(stderr, "Unable to read the MFRA atom in %s\n", file);
  211. return err;
  212. }
  213. static int get_private_data(struct VideoFile *vf, AVCodecContext *codec)
  214. {
  215. vf->codec_private_size = codec->extradata_size;
  216. vf->codec_private = av_mallocz(codec->extradata_size);
  217. if (!vf->codec_private)
  218. return AVERROR(ENOMEM);
  219. memcpy(vf->codec_private, codec->extradata, codec->extradata_size);
  220. return 0;
  221. }
  222. static int get_video_private_data(struct VideoFile *vf, AVCodecContext *codec)
  223. {
  224. AVIOContext *io = NULL;
  225. uint16_t sps_size, pps_size;
  226. int err = AVERROR(EINVAL);
  227. if (codec->codec_id == AV_CODEC_ID_VC1)
  228. return get_private_data(vf, codec);
  229. if (avio_open_dyn_buf(&io) < 0) {
  230. err = AVERROR(ENOMEM);
  231. goto fail;
  232. }
  233. if (codec->extradata_size < 11 || codec->extradata[0] != 1)
  234. goto fail;
  235. sps_size = AV_RB16(&codec->extradata[6]);
  236. if (11 + sps_size > codec->extradata_size)
  237. goto fail;
  238. avio_wb32(io, 0x00000001);
  239. avio_write(io, &codec->extradata[8], sps_size);
  240. pps_size = AV_RB16(&codec->extradata[9 + sps_size]);
  241. if (11 + sps_size + pps_size > codec->extradata_size)
  242. goto fail;
  243. avio_wb32(io, 0x00000001);
  244. avio_write(io, &codec->extradata[11 + sps_size], pps_size);
  245. err = 0;
  246. fail:
  247. vf->codec_private_size = avio_close_dyn_buf(io, &vf->codec_private);
  248. return err;
  249. }
  250. static int handle_file(struct VideoFiles *files, const char *file, int split)
  251. {
  252. AVFormatContext *ctx = NULL;
  253. int err = 0, i, orig_files = files->nb_files;
  254. char errbuf[50], *ptr;
  255. struct VideoFile *vf;
  256. err = avformat_open_input(&ctx, file, NULL, NULL);
  257. if (err < 0) {
  258. av_strerror(err, errbuf, sizeof(errbuf));
  259. fprintf(stderr, "Unable to open %s: %s\n", file, errbuf);
  260. return 1;
  261. }
  262. err = avformat_find_stream_info(ctx, NULL);
  263. if (err < 0) {
  264. av_strerror(err, errbuf, sizeof(errbuf));
  265. fprintf(stderr, "Unable to identify %s: %s\n", file, errbuf);
  266. goto fail;
  267. }
  268. if (ctx->nb_streams < 1) {
  269. fprintf(stderr, "No streams found in %s\n", file);
  270. goto fail;
  271. }
  272. if (!files->duration)
  273. files->duration = ctx->duration;
  274. for (i = 0; i < ctx->nb_streams; i++) {
  275. AVStream *st = ctx->streams[i];
  276. vf = av_mallocz(sizeof(*vf));
  277. files->files = av_realloc(files->files,
  278. sizeof(*files->files) * (files->nb_files + 1));
  279. files->files[files->nb_files] = vf;
  280. vf->name = file;
  281. if ((ptr = strrchr(file, '/')) != NULL)
  282. vf->name = ptr + 1;
  283. vf->bitrate = st->codec->bit_rate;
  284. vf->track_id = st->id;
  285. vf->timescale = st->time_base.den;
  286. vf->duration = av_rescale_rnd(ctx->duration, vf->timescale,
  287. AV_TIME_BASE, AV_ROUND_UP);
  288. vf->is_audio = st->codec->codec_type == AVMEDIA_TYPE_AUDIO;
  289. vf->is_video = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
  290. if (!vf->is_audio && !vf->is_video) {
  291. fprintf(stderr,
  292. "Track %d in %s is neither video nor audio, skipping\n",
  293. vf->track_id, file);
  294. av_freep(&files->files[files->nb_files]);
  295. continue;
  296. }
  297. if (vf->is_audio) {
  298. if (files->audio_file < 0)
  299. files->audio_file = files->nb_files;
  300. files->nb_audio_files++;
  301. vf->channels = st->codec->channels;
  302. vf->sample_rate = st->codec->sample_rate;
  303. if (st->codec->codec_id == AV_CODEC_ID_AAC) {
  304. vf->fourcc = "AACL";
  305. vf->tag = 255;
  306. vf->blocksize = 4;
  307. } else if (st->codec->codec_id == AV_CODEC_ID_WMAPRO) {
  308. vf->fourcc = "WMAP";
  309. vf->tag = st->codec->codec_tag;
  310. vf->blocksize = st->codec->block_align;
  311. }
  312. get_private_data(vf, st->codec);
  313. }
  314. if (vf->is_video) {
  315. if (files->video_file < 0)
  316. files->video_file = files->nb_files;
  317. files->nb_video_files++;
  318. vf->width = st->codec->width;
  319. vf->height = st->codec->height;
  320. if (st->codec->codec_id == AV_CODEC_ID_H264)
  321. vf->fourcc = "H264";
  322. else if (st->codec->codec_id == AV_CODEC_ID_VC1)
  323. vf->fourcc = "WVC1";
  324. get_video_private_data(vf, st->codec);
  325. }
  326. files->nb_files++;
  327. }
  328. avformat_close_input(&ctx);
  329. err = read_mfra(files, orig_files, file, split);
  330. fail:
  331. if (ctx)
  332. avformat_close_input(&ctx);
  333. return err;
  334. }
  335. static void output_server_manifest(struct VideoFiles *files,
  336. const char *basename)
  337. {
  338. char filename[1000];
  339. FILE *out;
  340. int i;
  341. snprintf(filename, sizeof(filename), "%s.ism", basename);
  342. out = fopen(filename, "w");
  343. if (!out) {
  344. perror(filename);
  345. return;
  346. }
  347. fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  348. fprintf(out, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
  349. fprintf(out, "\t<head>\n");
  350. fprintf(out, "\t\t<meta name=\"clientManifestRelativePath\" "
  351. "content=\"%s.ismc\" />\n", basename);
  352. fprintf(out, "\t</head>\n");
  353. fprintf(out, "\t<body>\n");
  354. fprintf(out, "\t\t<switch>\n");
  355. for (i = 0; i < files->nb_files; i++) {
  356. struct VideoFile *vf = files->files[i];
  357. const char *type = vf->is_video ? "video" : "audio";
  358. fprintf(out, "\t\t\t<%s src=\"%s\" systemBitrate=\"%d\">\n",
  359. type, vf->name, vf->bitrate);
  360. fprintf(out, "\t\t\t\t<param name=\"trackID\" value=\"%d\" "
  361. "valueType=\"data\" />\n", vf->track_id);
  362. fprintf(out, "\t\t\t</%s>\n", type);
  363. }
  364. fprintf(out, "\t\t</switch>\n");
  365. fprintf(out, "\t</body>\n");
  366. fprintf(out, "</smil>\n");
  367. fclose(out);
  368. }
  369. static void output_client_manifest(struct VideoFiles *files,
  370. const char *basename, int split)
  371. {
  372. char filename[1000];
  373. FILE *out;
  374. int i, j;
  375. if (split)
  376. snprintf(filename, sizeof(filename), "Manifest");
  377. else
  378. snprintf(filename, sizeof(filename), "%s.ismc", basename);
  379. out = fopen(filename, "w");
  380. if (!out) {
  381. perror(filename);
  382. return;
  383. }
  384. fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  385. fprintf(out, "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" "
  386. "Duration=\"%"PRId64 "\">\n", files->duration * 10);
  387. if (files->video_file >= 0) {
  388. struct VideoFile *vf = files->files[files->video_file];
  389. struct VideoFile *first_vf = vf;
  390. int index = 0;
  391. fprintf(out,
  392. "\t<StreamIndex Type=\"video\" QualityLevels=\"%d\" "
  393. "Chunks=\"%d\" "
  394. "Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n",
  395. files->nb_video_files, vf->chunks);
  396. for (i = 0; i < files->nb_files; i++) {
  397. vf = files->files[i];
  398. if (!vf->is_video)
  399. continue;
  400. fprintf(out,
  401. "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
  402. "FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" "
  403. "CodecPrivateData=\"",
  404. index, vf->bitrate, vf->fourcc, vf->width, vf->height);
  405. for (j = 0; j < vf->codec_private_size; j++)
  406. fprintf(out, "%02X", vf->codec_private[j]);
  407. fprintf(out, "\" />\n");
  408. index++;
  409. if (vf->chunks != first_vf->chunks)
  410. fprintf(stderr, "Mismatched number of video chunks in %s and %s\n",
  411. vf->name, first_vf->name);
  412. }
  413. vf = first_vf;
  414. for (i = 0; i < vf->chunks; i++) {
  415. for (j = files->video_file + 1; j < files->nb_files; j++) {
  416. if (files->files[j]->is_video &&
  417. vf->offsets[i].duration != files->files[j]->offsets[i].duration)
  418. fprintf(stderr, "Mismatched duration of video chunk %d in %s and %s\n",
  419. i, vf->name, files->files[j]->name);
  420. }
  421. fprintf(out, "\t\t<c n=\"%d\" d=\"%d\" />\n", i,
  422. vf->offsets[i].duration);
  423. }
  424. fprintf(out, "\t</StreamIndex>\n");
  425. }
  426. if (files->audio_file >= 0) {
  427. struct VideoFile *vf = files->files[files->audio_file];
  428. struct VideoFile *first_vf = vf;
  429. int index = 0;
  430. fprintf(out,
  431. "\t<StreamIndex Type=\"audio\" QualityLevels=\"%d\" "
  432. "Chunks=\"%d\" "
  433. "Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n",
  434. files->nb_audio_files, vf->chunks);
  435. for (i = 0; i < files->nb_files; i++) {
  436. vf = files->files[i];
  437. if (!vf->is_audio)
  438. continue;
  439. fprintf(out,
  440. "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
  441. "FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" "
  442. "BitsPerSample=\"16\" PacketSize=\"%d\" "
  443. "AudioTag=\"%d\" CodecPrivateData=\"",
  444. index, vf->bitrate, vf->fourcc, vf->sample_rate,
  445. vf->channels, vf->blocksize, vf->tag);
  446. for (j = 0; j < vf->codec_private_size; j++)
  447. fprintf(out, "%02X", vf->codec_private[j]);
  448. fprintf(out, "\" />\n");
  449. index++;
  450. if (vf->chunks != first_vf->chunks)
  451. fprintf(stderr, "Mismatched number of audio chunks in %s and %s\n",
  452. vf->name, first_vf->name);
  453. }
  454. vf = first_vf;
  455. for (i = 0; i < vf->chunks; i++) {
  456. for (j = files->audio_file + 1; j < files->nb_files; j++) {
  457. if (files->files[j]->is_audio &&
  458. vf->offsets[i].duration != files->files[j]->offsets[i].duration)
  459. fprintf(stderr, "Mismatched duration of audio chunk %d in %s and %s\n",
  460. i, vf->name, files->files[j]->name);
  461. }
  462. fprintf(out, "\t\t<c n=\"%d\" d=\"%d\" />\n",
  463. i, vf->offsets[i].duration);
  464. }
  465. fprintf(out, "\t</StreamIndex>\n");
  466. }
  467. fprintf(out, "</SmoothStreamingMedia>\n");
  468. fclose(out);
  469. }
  470. static void clean_files(struct VideoFiles *files)
  471. {
  472. int i;
  473. for (i = 0; i < files->nb_files; i++) {
  474. av_freep(&files->files[i]->codec_private);
  475. av_freep(&files->files[i]->offsets);
  476. av_freep(&files->files[i]);
  477. }
  478. av_freep(&files->files);
  479. files->nb_files = 0;
  480. }
  481. int main(int argc, char **argv)
  482. {
  483. const char *basename = NULL;
  484. int split = 0, i;
  485. struct VideoFiles vf = { 0, .video_file = -1, .audio_file = -1 };
  486. av_register_all();
  487. for (i = 1; i < argc; i++) {
  488. if (!strcmp(argv[i], "-n")) {
  489. basename = argv[i + 1];
  490. i++;
  491. } else if (!strcmp(argv[i], "-split")) {
  492. split = 1;
  493. } else if (argv[i][0] == '-') {
  494. return usage(argv[0], 1);
  495. } else {
  496. if (handle_file(&vf, argv[i], split))
  497. return 1;
  498. }
  499. }
  500. if (!vf.nb_files || (!basename && !split))
  501. return usage(argv[0], 1);
  502. if (!split)
  503. output_server_manifest(&vf, basename);
  504. output_client_manifest(&vf, basename, split);
  505. clean_files(&vf);
  506. return 0;
  507. }