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.

558 lines
18KB

  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. if (avio_open_dyn_buf(&io) < 0) {
  229. err = AVERROR(ENOMEM);
  230. goto fail;
  231. }
  232. if (codec->extradata_size < 11 || codec->extradata[0] != 1)
  233. goto fail;
  234. sps_size = AV_RB16(&codec->extradata[6]);
  235. if (11 + sps_size > codec->extradata_size)
  236. goto fail;
  237. avio_wb32(io, 0x00000001);
  238. avio_write(io, &codec->extradata[8], sps_size);
  239. pps_size = AV_RB16(&codec->extradata[9 + sps_size]);
  240. if (11 + sps_size + pps_size > codec->extradata_size)
  241. goto fail;
  242. avio_wb32(io, 0x00000001);
  243. avio_write(io, &codec->extradata[11 + sps_size], pps_size);
  244. err = 0;
  245. fail:
  246. vf->codec_private_size = avio_close_dyn_buf(io, &vf->codec_private);
  247. return err;
  248. }
  249. static int handle_file(struct VideoFiles *files, const char *file, int split)
  250. {
  251. AVFormatContext *ctx = NULL;
  252. int err = 0, i, orig_files = files->nb_files;
  253. char errbuf[50], *ptr;
  254. struct VideoFile *vf;
  255. err = avformat_open_input(&ctx, file, NULL, NULL);
  256. if (err < 0) {
  257. av_strerror(err, errbuf, sizeof(errbuf));
  258. fprintf(stderr, "Unable to open %s: %s\n", file, errbuf);
  259. return 1;
  260. }
  261. err = avformat_find_stream_info(ctx, NULL);
  262. if (err < 0) {
  263. av_strerror(err, errbuf, sizeof(errbuf));
  264. fprintf(stderr, "Unable to identify %s: %s\n", file, errbuf);
  265. goto fail;
  266. }
  267. if (ctx->nb_streams < 1) {
  268. fprintf(stderr, "No streams found in %s\n", file);
  269. goto fail;
  270. }
  271. if (!files->duration)
  272. files->duration = ctx->duration;
  273. for (i = 0; i < ctx->nb_streams; i++) {
  274. AVStream *st = ctx->streams[i];
  275. vf = av_mallocz(sizeof(*vf));
  276. files->files = av_realloc(files->files,
  277. sizeof(*files->files) * (files->nb_files + 1));
  278. files->files[files->nb_files] = vf;
  279. vf->name = file;
  280. if ((ptr = strrchr(file, '/')) != NULL)
  281. vf->name = ptr + 1;
  282. vf->bitrate = st->codec->bit_rate;
  283. vf->track_id = st->id;
  284. vf->timescale = st->time_base.den;
  285. vf->duration = av_rescale_rnd(ctx->duration, vf->timescale,
  286. AV_TIME_BASE, AV_ROUND_UP);
  287. vf->is_audio = st->codec->codec_type == AVMEDIA_TYPE_AUDIO;
  288. vf->is_video = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
  289. if (!vf->is_audio && !vf->is_video) {
  290. fprintf(stderr,
  291. "Track %d in %s is neither video nor audio, skipping\n",
  292. vf->track_id, file);
  293. av_freep(&files->files[files->nb_files]);
  294. continue;
  295. }
  296. if (vf->is_audio) {
  297. if (files->audio_file < 0)
  298. files->audio_file = files->nb_files;
  299. files->nb_audio_files++;
  300. vf->channels = st->codec->channels;
  301. vf->sample_rate = st->codec->sample_rate;
  302. if (st->codec->codec_id == AV_CODEC_ID_AAC) {
  303. vf->fourcc = "AACL";
  304. vf->tag = 255;
  305. vf->blocksize = 4;
  306. } else if (st->codec->codec_id == AV_CODEC_ID_WMAPRO) {
  307. vf->fourcc = "WMAP";
  308. vf->tag = st->codec->codec_tag;
  309. vf->blocksize = st->codec->block_align;
  310. }
  311. get_private_data(vf, st->codec);
  312. }
  313. if (vf->is_video) {
  314. if (files->video_file < 0)
  315. files->video_file = files->nb_files;
  316. files->nb_video_files++;
  317. vf->width = st->codec->width;
  318. vf->height = st->codec->height;
  319. if (st->codec->codec_id == AV_CODEC_ID_H264)
  320. vf->fourcc = "H264";
  321. else if (st->codec->codec_id == AV_CODEC_ID_VC1)
  322. vf->fourcc = "WVC1";
  323. get_video_private_data(vf, st->codec);
  324. }
  325. files->nb_files++;
  326. }
  327. avformat_close_input(&ctx);
  328. err = read_mfra(files, orig_files, file, split);
  329. fail:
  330. if (ctx)
  331. avformat_close_input(&ctx);
  332. return err;
  333. }
  334. static void output_server_manifest(struct VideoFiles *files,
  335. const char *basename)
  336. {
  337. char filename[1000];
  338. FILE *out;
  339. int i;
  340. snprintf(filename, sizeof(filename), "%s.ism", basename);
  341. out = fopen(filename, "w");
  342. if (!out) {
  343. perror(filename);
  344. return;
  345. }
  346. fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  347. fprintf(out, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
  348. fprintf(out, "\t<head>\n");
  349. fprintf(out, "\t\t<meta name=\"clientManifestRelativePath\" "
  350. "content=\"%s.ismc\" />\n", basename);
  351. fprintf(out, "\t</head>\n");
  352. fprintf(out, "\t<body>\n");
  353. fprintf(out, "\t\t<switch>\n");
  354. for (i = 0; i < files->nb_files; i++) {
  355. struct VideoFile *vf = files->files[i];
  356. const char *type = vf->is_video ? "video" : "audio";
  357. fprintf(out, "\t\t\t<%s src=\"%s\" systemBitrate=\"%d\">\n",
  358. type, vf->name, vf->bitrate);
  359. fprintf(out, "\t\t\t\t<param name=\"trackID\" value=\"%d\" "
  360. "valueType=\"data\" />\n", vf->track_id);
  361. fprintf(out, "\t\t\t</%s>\n", type);
  362. }
  363. fprintf(out, "\t\t</switch>\n");
  364. fprintf(out, "\t</body>\n");
  365. fprintf(out, "</smil>\n");
  366. fclose(out);
  367. }
  368. static void output_client_manifest(struct VideoFiles *files,
  369. const char *basename, int split)
  370. {
  371. char filename[1000];
  372. FILE *out;
  373. int i, j;
  374. if (split)
  375. snprintf(filename, sizeof(filename), "Manifest");
  376. else
  377. snprintf(filename, sizeof(filename), "%s.ismc", basename);
  378. out = fopen(filename, "w");
  379. if (!out) {
  380. perror(filename);
  381. return;
  382. }
  383. fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  384. fprintf(out, "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" "
  385. "Duration=\"%"PRId64 "\">\n", files->duration * 10);
  386. if (files->video_file >= 0) {
  387. struct VideoFile *vf = files->files[files->video_file];
  388. struct VideoFile *first_vf = vf;
  389. int index = 0;
  390. fprintf(out,
  391. "\t<StreamIndex Type=\"video\" QualityLevels=\"%d\" "
  392. "Chunks=\"%d\" "
  393. "Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n",
  394. files->nb_video_files, vf->chunks);
  395. for (i = 0; i < files->nb_files; i++) {
  396. vf = files->files[i];
  397. if (!vf->is_video)
  398. continue;
  399. fprintf(out,
  400. "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
  401. "FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" "
  402. "CodecPrivateData=\"",
  403. index, vf->bitrate, vf->fourcc, vf->width, vf->height);
  404. for (j = 0; j < vf->codec_private_size; j++)
  405. fprintf(out, "%02X", vf->codec_private[j]);
  406. fprintf(out, "\" />\n");
  407. index++;
  408. if (vf->chunks != first_vf->chunks)
  409. fprintf(stderr, "Mismatched number of video chunks in %s and %s\n",
  410. vf->name, first_vf->name);
  411. }
  412. vf = first_vf;
  413. for (i = 0; i < vf->chunks; i++) {
  414. for (j = files->video_file + 1; j < files->nb_files; j++) {
  415. if (files->files[j]->is_video &&
  416. vf->offsets[i].duration != files->files[j]->offsets[i].duration)
  417. fprintf(stderr, "Mismatched duration of video chunk %d in %s and %s\n",
  418. i, vf->name, files->files[j]->name);
  419. }
  420. fprintf(out, "\t\t<c n=\"%d\" d=\"%d\" />\n", i,
  421. vf->offsets[i].duration);
  422. }
  423. fprintf(out, "\t</StreamIndex>\n");
  424. }
  425. if (files->audio_file >= 0) {
  426. struct VideoFile *vf = files->files[files->audio_file];
  427. struct VideoFile *first_vf = vf;
  428. int index = 0;
  429. fprintf(out,
  430. "\t<StreamIndex Type=\"audio\" QualityLevels=\"%d\" "
  431. "Chunks=\"%d\" "
  432. "Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n",
  433. files->nb_audio_files, vf->chunks);
  434. for (i = 0; i < files->nb_files; i++) {
  435. vf = files->files[i];
  436. if (!vf->is_audio)
  437. continue;
  438. fprintf(out,
  439. "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
  440. "FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" "
  441. "BitsPerSample=\"16\" PacketSize=\"%d\" "
  442. "AudioTag=\"%d\" CodecPrivateData=\"",
  443. index, vf->bitrate, vf->fourcc, vf->sample_rate,
  444. vf->channels, vf->blocksize, vf->tag);
  445. for (j = 0; j < vf->codec_private_size; j++)
  446. fprintf(out, "%02X", vf->codec_private[j]);
  447. fprintf(out, "\" />\n");
  448. index++;
  449. if (vf->chunks != first_vf->chunks)
  450. fprintf(stderr, "Mismatched number of audio chunks in %s and %s\n",
  451. vf->name, first_vf->name);
  452. }
  453. vf = first_vf;
  454. for (i = 0; i < vf->chunks; i++) {
  455. for (j = files->audio_file + 1; j < files->nb_files; j++) {
  456. if (files->files[j]->is_audio &&
  457. vf->offsets[i].duration != files->files[j]->offsets[i].duration)
  458. fprintf(stderr, "Mismatched duration of audio chunk %d in %s and %s\n",
  459. i, vf->name, files->files[j]->name);
  460. }
  461. fprintf(out, "\t\t<c n=\"%d\" d=\"%d\" />\n",
  462. i, vf->offsets[i].duration);
  463. }
  464. fprintf(out, "\t</StreamIndex>\n");
  465. }
  466. fprintf(out, "</SmoothStreamingMedia>\n");
  467. fclose(out);
  468. }
  469. static void clean_files(struct VideoFiles *files)
  470. {
  471. int i;
  472. for (i = 0; i < files->nb_files; i++) {
  473. av_freep(&files->files[i]->codec_private);
  474. av_freep(&files->files[i]->offsets);
  475. av_freep(&files->files[i]);
  476. }
  477. av_freep(&files->files);
  478. files->nb_files = 0;
  479. }
  480. int main(int argc, char **argv)
  481. {
  482. const char *basename = NULL;
  483. int split = 0, i;
  484. struct VideoFiles vf = { 0, .video_file = -1, .audio_file = -1 };
  485. av_register_all();
  486. for (i = 1; i < argc; i++) {
  487. if (!strcmp(argv[i], "-n")) {
  488. basename = argv[i + 1];
  489. i++;
  490. } else if (!strcmp(argv[i], "-split")) {
  491. split = 1;
  492. } else if (argv[i][0] == '-') {
  493. return usage(argv[0], 1);
  494. } else {
  495. if (handle_file(&vf, argv[i], split))
  496. return 1;
  497. }
  498. }
  499. if (!vf.nb_files || (!basename && !split))
  500. return usage(argv[0], 1);
  501. if (!split)
  502. output_server_manifest(&vf, basename);
  503. output_client_manifest(&vf, basename, split);
  504. clean_files(&vf);
  505. return 0;
  506. }