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.

526 lines
16KB

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