ismindex.c 18 KB

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