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.

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