ffmpeg-mux.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. /*
  2. * Copyright (c) 2015 Hugh Bailey <[email protected]>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #ifdef _WIN32
  17. #include <io.h>
  18. #include <fcntl.h>
  19. #include <windows.h>
  20. #define inline __inline
  21. #endif
  22. #include <stdbool.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include "ffmpeg-mux.h"
  26. #include <libavformat/avformat.h>
  27. #if LIBAVCODEC_VERSION_MAJOR >= 58
  28. #define CODEC_FLAG_GLOBAL_H AV_CODEC_FLAG_GLOBAL_HEADER
  29. #else
  30. #define CODEC_FLAG_GLOBAL_H CODEC_FLAG_GLOBAL_HEADER
  31. #endif
  32. /* ------------------------------------------------------------------------- */
  33. struct resize_buf {
  34. uint8_t *buf;
  35. size_t size;
  36. size_t capacity;
  37. };
  38. static inline void resize_buf_resize(struct resize_buf *rb, size_t size)
  39. {
  40. if (!rb->buf) {
  41. rb->buf = malloc(size);
  42. rb->size = size;
  43. rb->capacity = size;
  44. } else {
  45. if (rb->capacity < size) {
  46. size_t capx2 = rb->capacity * 2;
  47. size_t new_cap = capx2 > size ? capx2 : size;
  48. rb->buf = realloc(rb->buf, new_cap);
  49. rb->capacity = new_cap;
  50. }
  51. rb->size = size;
  52. }
  53. }
  54. static inline void resize_buf_free(struct resize_buf *rb)
  55. {
  56. free(rb->buf);
  57. }
  58. /* ------------------------------------------------------------------------- */
  59. struct main_params {
  60. char *file;
  61. int has_video;
  62. int tracks;
  63. char *vcodec;
  64. int vbitrate;
  65. int gop;
  66. int width;
  67. int height;
  68. int fps_num;
  69. int fps_den;
  70. int color_primaries;
  71. int color_trc;
  72. int colorspace;
  73. int color_range;
  74. char *acodec;
  75. char *muxer_settings;
  76. };
  77. struct audio_params {
  78. char *name;
  79. int abitrate;
  80. int sample_rate;
  81. int channels;
  82. };
  83. struct header {
  84. uint8_t *data;
  85. int size;
  86. };
  87. struct audio_info {
  88. AVStream *stream;
  89. AVCodecContext *ctx;
  90. };
  91. struct ffmpeg_mux {
  92. AVFormatContext *output;
  93. AVStream *video_stream;
  94. AVCodecContext *video_ctx;
  95. struct audio_info *audio_infos;
  96. struct main_params params;
  97. struct audio_params *audio;
  98. struct header video_header;
  99. struct header *audio_header;
  100. int num_audio_streams;
  101. bool initialized;
  102. char error[4096];
  103. };
  104. static void header_free(struct header *header)
  105. {
  106. free(header->data);
  107. }
  108. static void free_avformat(struct ffmpeg_mux *ffm)
  109. {
  110. if (ffm->output) {
  111. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  112. avcodec_free_context(&ffm->video_ctx);
  113. #endif
  114. if ((ffm->output->oformat->flags & AVFMT_NOFILE) == 0)
  115. avio_close(ffm->output->pb);
  116. avformat_free_context(ffm->output);
  117. ffm->output = NULL;
  118. }
  119. if (ffm->audio_infos) {
  120. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  121. for (int i = 0; i < ffm->num_audio_streams; ++i)
  122. avcodec_free_context(&ffm->audio_infos[i].ctx);
  123. #endif
  124. free(ffm->audio_infos);
  125. }
  126. ffm->video_stream = NULL;
  127. ffm->audio_infos = NULL;
  128. ffm->num_audio_streams = 0;
  129. }
  130. static void ffmpeg_mux_free(struct ffmpeg_mux *ffm)
  131. {
  132. if (ffm->initialized) {
  133. av_write_trailer(ffm->output);
  134. }
  135. free_avformat(ffm);
  136. header_free(&ffm->video_header);
  137. if (ffm->audio_header) {
  138. for (int i = 0; i < ffm->params.tracks; i++) {
  139. header_free(&ffm->audio_header[i]);
  140. }
  141. free(ffm->audio_header);
  142. }
  143. if (ffm->audio) {
  144. free(ffm->audio);
  145. }
  146. memset(ffm, 0, sizeof(*ffm));
  147. }
  148. static bool get_opt_str(int *p_argc, char ***p_argv, char **str,
  149. const char *opt)
  150. {
  151. int argc = *p_argc;
  152. char **argv = *p_argv;
  153. if (!argc) {
  154. printf("Missing expected option: '%s'\n", opt);
  155. return false;
  156. }
  157. (*p_argc)--;
  158. (*p_argv)++;
  159. *str = argv[0];
  160. return true;
  161. }
  162. static bool get_opt_int(int *p_argc, char ***p_argv, int *i, const char *opt)
  163. {
  164. char *str;
  165. if (!get_opt_str(p_argc, p_argv, &str, opt)) {
  166. return false;
  167. }
  168. *i = atoi(str);
  169. return true;
  170. }
  171. static bool get_audio_params(struct audio_params *audio, int *argc,
  172. char ***argv)
  173. {
  174. if (!get_opt_str(argc, argv, &audio->name, "audio track name"))
  175. return false;
  176. if (!get_opt_int(argc, argv, &audio->abitrate, "audio bitrate"))
  177. return false;
  178. if (!get_opt_int(argc, argv, &audio->sample_rate, "audio sample rate"))
  179. return false;
  180. if (!get_opt_int(argc, argv, &audio->channels, "audio channels"))
  181. return false;
  182. return true;
  183. }
  184. static bool init_params(int *argc, char ***argv, struct main_params *params,
  185. struct audio_params **p_audio)
  186. {
  187. struct audio_params *audio = NULL;
  188. if (!get_opt_str(argc, argv, &params->file, "file name"))
  189. return false;
  190. if (!get_opt_int(argc, argv, &params->has_video, "video track count"))
  191. return false;
  192. if (!get_opt_int(argc, argv, &params->tracks, "audio track count"))
  193. return false;
  194. if (params->has_video > 1 || params->has_video < 0) {
  195. puts("Invalid number of video tracks\n");
  196. return false;
  197. }
  198. if (params->tracks < 0) {
  199. puts("Invalid number of audio tracks\n");
  200. return false;
  201. }
  202. if (params->has_video == 0 && params->tracks == 0) {
  203. puts("Must have at least 1 audio track or 1 video track\n");
  204. return false;
  205. }
  206. if (params->has_video) {
  207. if (!get_opt_str(argc, argv, &params->vcodec, "video codec"))
  208. return false;
  209. if (!get_opt_int(argc, argv, &params->vbitrate,
  210. "video bitrate"))
  211. return false;
  212. if (!get_opt_int(argc, argv, &params->width, "video width"))
  213. return false;
  214. if (!get_opt_int(argc, argv, &params->height, "video height"))
  215. return false;
  216. if (!get_opt_int(argc, argv, &params->color_primaries,
  217. "video color primaries"))
  218. return false;
  219. if (!get_opt_int(argc, argv, &params->color_trc,
  220. "video color trc"))
  221. return false;
  222. if (!get_opt_int(argc, argv, &params->colorspace,
  223. "video colorspace"))
  224. return false;
  225. if (!get_opt_int(argc, argv, &params->color_range,
  226. "video color range"))
  227. return false;
  228. if (!get_opt_int(argc, argv, &params->fps_num, "video fps num"))
  229. return false;
  230. if (!get_opt_int(argc, argv, &params->fps_den, "video fps den"))
  231. return false;
  232. }
  233. if (params->tracks) {
  234. if (!get_opt_str(argc, argv, &params->acodec, "audio codec"))
  235. return false;
  236. audio = calloc(params->tracks, sizeof(*audio));
  237. for (int i = 0; i < params->tracks; i++) {
  238. if (!get_audio_params(&audio[i], argc, argv)) {
  239. free(audio);
  240. return false;
  241. }
  242. }
  243. }
  244. *p_audio = audio;
  245. get_opt_str(argc, argv, &params->muxer_settings, "muxer settings");
  246. return true;
  247. }
  248. static bool new_stream(struct ffmpeg_mux *ffm, AVStream **stream,
  249. const char *name, AVCodec **codec)
  250. {
  251. const AVCodecDescriptor *desc = avcodec_descriptor_get_by_name(name);
  252. if (!desc) {
  253. fprintf(stderr, "Couldn't find encoder '%s'\n", name);
  254. return false;
  255. }
  256. *codec = avcodec_find_encoder(desc->id);
  257. if (!*codec) {
  258. fprintf(stderr, "Couldn't create encoder");
  259. return false;
  260. }
  261. *stream = avformat_new_stream(ffm->output, *codec);
  262. if (!*stream) {
  263. fprintf(stderr, "Couldn't create stream for encoder '%s'\n",
  264. name);
  265. return false;
  266. }
  267. (*stream)->id = ffm->output->nb_streams - 1;
  268. return true;
  269. }
  270. static void create_video_stream(struct ffmpeg_mux *ffm)
  271. {
  272. AVCodec *codec;
  273. AVCodecContext *context;
  274. void *extradata = NULL;
  275. if (!new_stream(ffm, &ffm->video_stream, ffm->params.vcodec, &codec))
  276. return;
  277. if (ffm->video_header.size) {
  278. extradata = av_memdup(ffm->video_header.data,
  279. ffm->video_header.size);
  280. }
  281. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  282. context = avcodec_alloc_context3(codec);
  283. #else
  284. context = ffm->video_stream->codec;
  285. #endif
  286. context->bit_rate = (int64_t)ffm->params.vbitrate * 1000;
  287. context->width = ffm->params.width;
  288. context->height = ffm->params.height;
  289. context->coded_width = ffm->params.width;
  290. context->coded_height = ffm->params.height;
  291. context->color_primaries = ffm->params.color_primaries;
  292. context->color_trc = ffm->params.color_trc;
  293. context->colorspace = ffm->params.colorspace;
  294. context->color_range = ffm->params.color_range;
  295. context->extradata = extradata;
  296. context->extradata_size = ffm->video_header.size;
  297. context->time_base =
  298. (AVRational){ffm->params.fps_den, ffm->params.fps_num};
  299. ffm->video_stream->time_base = context->time_base;
  300. ffm->video_stream->avg_frame_rate = av_inv_q(context->time_base);
  301. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  302. context->flags |= CODEC_FLAG_GLOBAL_H;
  303. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  304. avcodec_parameters_from_context(ffm->video_stream->codecpar, context);
  305. #endif
  306. ffm->video_ctx = context;
  307. }
  308. static void create_audio_stream(struct ffmpeg_mux *ffm, int idx)
  309. {
  310. AVCodec *codec;
  311. AVCodecContext *context;
  312. AVStream *stream;
  313. void *extradata = NULL;
  314. if (!new_stream(ffm, &stream, ffm->params.acodec, &codec))
  315. return;
  316. av_dict_set(&stream->metadata, "title", ffm->audio[idx].name, 0);
  317. stream->time_base = (AVRational){1, ffm->audio[idx].sample_rate};
  318. if (ffm->audio_header[idx].size) {
  319. extradata = av_memdup(ffm->audio_header[idx].data,
  320. ffm->audio_header[idx].size);
  321. }
  322. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  323. context = avcodec_alloc_context3(codec);
  324. #else
  325. context = stream->codec;
  326. #endif
  327. context->bit_rate = (int64_t)ffm->audio[idx].abitrate * 1000;
  328. context->channels = ffm->audio[idx].channels;
  329. context->sample_rate = ffm->audio[idx].sample_rate;
  330. context->sample_fmt = AV_SAMPLE_FMT_S16;
  331. context->time_base = stream->time_base;
  332. context->extradata = extradata;
  333. context->extradata_size = ffm->audio_header[idx].size;
  334. context->channel_layout =
  335. av_get_default_channel_layout(context->channels);
  336. //AVlib default channel layout for 4 channels is 4.0 ; fix for quad
  337. if (context->channels == 4)
  338. context->channel_layout = av_get_channel_layout("quad");
  339. //AVlib default channel layout for 5 channels is 5.0 ; fix for 4.1
  340. if (context->channels == 5)
  341. context->channel_layout = av_get_channel_layout("4.1");
  342. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  343. context->flags |= CODEC_FLAG_GLOBAL_H;
  344. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  345. avcodec_parameters_from_context(stream->codecpar, context);
  346. #endif
  347. ffm->audio_infos[ffm->num_audio_streams].stream = stream;
  348. ffm->audio_infos[ffm->num_audio_streams].ctx = context;
  349. ffm->num_audio_streams++;
  350. }
  351. static bool init_streams(struct ffmpeg_mux *ffm)
  352. {
  353. if (ffm->params.has_video)
  354. create_video_stream(ffm);
  355. if (ffm->params.tracks) {
  356. ffm->audio_infos =
  357. calloc(ffm->params.tracks, sizeof(*ffm->audio_infos));
  358. for (int i = 0; i < ffm->params.tracks; i++)
  359. create_audio_stream(ffm, i);
  360. }
  361. if (!ffm->video_stream && !ffm->num_audio_streams)
  362. return false;
  363. return true;
  364. }
  365. static void set_header(struct header *header, uint8_t *data, size_t size)
  366. {
  367. header->size = (int)size;
  368. header->data = malloc(size);
  369. memcpy(header->data, data, size);
  370. }
  371. static void ffmpeg_mux_header(struct ffmpeg_mux *ffm, uint8_t *data,
  372. struct ffm_packet_info *info)
  373. {
  374. if (info->type == FFM_PACKET_VIDEO) {
  375. set_header(&ffm->video_header, data, (size_t)info->size);
  376. } else {
  377. set_header(&ffm->audio_header[info->index], data,
  378. (size_t)info->size);
  379. }
  380. }
  381. static size_t safe_read(void *vdata, size_t size)
  382. {
  383. uint8_t *data = vdata;
  384. size_t total = size;
  385. while (size > 0) {
  386. size_t in_size = fread(data, 1, size, stdin);
  387. if (in_size == 0)
  388. return 0;
  389. size -= in_size;
  390. data += in_size;
  391. }
  392. return total;
  393. }
  394. static bool ffmpeg_mux_get_header(struct ffmpeg_mux *ffm)
  395. {
  396. struct ffm_packet_info info = {0};
  397. bool success = safe_read(&info, sizeof(info)) == sizeof(info);
  398. if (success) {
  399. uint8_t *data = malloc(info.size);
  400. if (safe_read(data, info.size) == info.size) {
  401. ffmpeg_mux_header(ffm, data, &info);
  402. } else {
  403. success = false;
  404. }
  405. free(data);
  406. }
  407. return success;
  408. }
  409. static inline bool ffmpeg_mux_get_extra_data(struct ffmpeg_mux *ffm)
  410. {
  411. if (ffm->params.has_video) {
  412. if (!ffmpeg_mux_get_header(ffm)) {
  413. return false;
  414. }
  415. }
  416. for (int i = 0; i < ffm->params.tracks; i++) {
  417. if (!ffmpeg_mux_get_header(ffm)) {
  418. return false;
  419. }
  420. }
  421. return true;
  422. }
  423. #ifdef _MSC_VER
  424. #pragma warning(disable : 4996)
  425. #endif
  426. static inline int open_output_file(struct ffmpeg_mux *ffm)
  427. {
  428. AVOutputFormat *format = ffm->output->oformat;
  429. int ret;
  430. if ((format->flags & AVFMT_NOFILE) == 0) {
  431. ret = avio_open(&ffm->output->pb, ffm->params.file,
  432. AVIO_FLAG_WRITE);
  433. if (ret < 0) {
  434. fprintf(stderr, "Couldn't open '%s', %s",
  435. ffm->params.file, av_err2str(ret));
  436. return FFM_ERROR;
  437. }
  438. }
  439. AVDictionary *dict = NULL;
  440. if ((ret = av_dict_parse_string(&dict, ffm->params.muxer_settings, "=",
  441. " ", 0))) {
  442. fprintf(stderr, "Failed to parse muxer settings: %s\n%s",
  443. av_err2str(ret), ffm->params.muxer_settings);
  444. av_dict_free(&dict);
  445. }
  446. if (av_dict_count(dict) > 0) {
  447. printf("Using muxer settings:");
  448. AVDictionaryEntry *entry = NULL;
  449. while ((entry = av_dict_get(dict, "", entry,
  450. AV_DICT_IGNORE_SUFFIX)))
  451. printf("\n\t%s=%s", entry->key, entry->value);
  452. printf("\n");
  453. }
  454. ret = avformat_write_header(ffm->output, &dict);
  455. if (ret < 0) {
  456. fprintf(stderr, "Error opening '%s': %s", ffm->params.file,
  457. av_err2str(ret));
  458. av_dict_free(&dict);
  459. return ret == -22 ? FFM_UNSUPPORTED : FFM_ERROR;
  460. }
  461. av_dict_free(&dict);
  462. return FFM_SUCCESS;
  463. }
  464. #define SRT_PROTO "srt"
  465. #define UDP_PROTO "udp"
  466. #define TCP_PROTO "tcp"
  467. static int ffmpeg_mux_init_context(struct ffmpeg_mux *ffm)
  468. {
  469. AVOutputFormat *output_format;
  470. int ret;
  471. bool isNetwork = false;
  472. if (strncmp(ffm->params.file, SRT_PROTO, sizeof(SRT_PROTO) - 1) == 0 ||
  473. strncmp(ffm->params.file, UDP_PROTO, sizeof(UDP_PROTO) - 1) == 0 ||
  474. strncmp(ffm->params.file, TCP_PROTO, sizeof(TCP_PROTO) - 1) == 0)
  475. isNetwork = true;
  476. if (isNetwork) {
  477. avformat_network_init();
  478. output_format = av_guess_format("mpegts", NULL, "video/M2PT");
  479. } else {
  480. output_format = av_guess_format(NULL, ffm->params.file, NULL);
  481. }
  482. if (output_format == NULL) {
  483. fprintf(stderr, "Couldn't find an appropriate muxer for '%s'\n",
  484. ffm->params.file);
  485. return FFM_ERROR;
  486. }
  487. ret = avformat_alloc_output_context2(&ffm->output, output_format, NULL,
  488. ffm->params.file);
  489. if (ret < 0) {
  490. fprintf(stderr, "Couldn't initialize output context: %s\n",
  491. av_err2str(ret));
  492. return FFM_ERROR;
  493. }
  494. ffm->output->oformat->video_codec = AV_CODEC_ID_NONE;
  495. ffm->output->oformat->audio_codec = AV_CODEC_ID_NONE;
  496. if (!init_streams(ffm)) {
  497. free_avformat(ffm);
  498. return FFM_ERROR;
  499. }
  500. ret = open_output_file(ffm);
  501. if (ret != FFM_SUCCESS) {
  502. free_avformat(ffm);
  503. return ret;
  504. }
  505. return FFM_SUCCESS;
  506. }
  507. static int ffmpeg_mux_init_internal(struct ffmpeg_mux *ffm, int argc,
  508. char *argv[])
  509. {
  510. argc--;
  511. argv++;
  512. if (!init_params(&argc, &argv, &ffm->params, &ffm->audio))
  513. return FFM_ERROR;
  514. if (ffm->params.tracks) {
  515. ffm->audio_header =
  516. calloc(ffm->params.tracks, sizeof(*ffm->audio_header));
  517. }
  518. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
  519. av_register_all();
  520. #endif
  521. if (!ffmpeg_mux_get_extra_data(ffm))
  522. return FFM_ERROR;
  523. /* ffmpeg does not have a way of telling what's supported
  524. * for a given output format, so we try each possibility */
  525. return ffmpeg_mux_init_context(ffm);
  526. }
  527. static int ffmpeg_mux_init(struct ffmpeg_mux *ffm, int argc, char *argv[])
  528. {
  529. int ret = ffmpeg_mux_init_internal(ffm, argc, argv);
  530. if (ret != FFM_SUCCESS) {
  531. ffmpeg_mux_free(ffm);
  532. return ret;
  533. }
  534. ffm->initialized = true;
  535. return ret;
  536. }
  537. static inline int get_index(struct ffmpeg_mux *ffm,
  538. struct ffm_packet_info *info)
  539. {
  540. if (info->type == FFM_PACKET_VIDEO) {
  541. if (ffm->video_stream) {
  542. return ffm->video_stream->id;
  543. }
  544. } else {
  545. if ((int)info->index < ffm->num_audio_streams) {
  546. return ffm->audio_infos[info->index].stream->id;
  547. }
  548. }
  549. return -1;
  550. }
  551. static AVCodecContext *get_codec_context(struct ffmpeg_mux *ffm,
  552. struct ffm_packet_info *info)
  553. {
  554. if (info->type == FFM_PACKET_VIDEO) {
  555. if (ffm->video_stream) {
  556. return ffm->video_ctx;
  557. }
  558. } else {
  559. if ((int)info->index < ffm->num_audio_streams) {
  560. return ffm->audio_infos[info->index].ctx;
  561. }
  562. }
  563. return NULL;
  564. }
  565. static inline AVStream *get_stream(struct ffmpeg_mux *ffm, int idx)
  566. {
  567. return ffm->output->streams[idx];
  568. }
  569. static inline int64_t rescale_ts(struct ffmpeg_mux *ffm,
  570. AVRational codec_time_base, int64_t val,
  571. int idx)
  572. {
  573. AVStream *stream = get_stream(ffm, idx);
  574. return av_rescale_q_rnd(val / codec_time_base.num, codec_time_base,
  575. stream->time_base,
  576. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  577. }
  578. static inline bool ffmpeg_mux_packet(struct ffmpeg_mux *ffm, uint8_t *buf,
  579. struct ffm_packet_info *info)
  580. {
  581. int idx = get_index(ffm, info);
  582. AVPacket packet = {0};
  583. /* The muxer might not support video/audio, or multiple audio tracks */
  584. if (idx == -1) {
  585. return true;
  586. }
  587. const AVRational codec_time_base =
  588. get_codec_context(ffm, info)->time_base;
  589. av_init_packet(&packet);
  590. packet.data = buf;
  591. packet.size = (int)info->size;
  592. packet.stream_index = idx;
  593. packet.pts = rescale_ts(ffm, codec_time_base, info->pts, idx);
  594. packet.dts = rescale_ts(ffm, codec_time_base, info->dts, idx);
  595. if (info->keyframe)
  596. packet.flags = AV_PKT_FLAG_KEY;
  597. return av_interleaved_write_frame(ffm->output, &packet) >= 0;
  598. }
  599. /* ------------------------------------------------------------------------- */
  600. #ifdef _WIN32
  601. int wmain(int argc, wchar_t *argv_w[])
  602. #else
  603. int main(int argc, char *argv[])
  604. #endif
  605. {
  606. struct ffm_packet_info info = {0};
  607. struct ffmpeg_mux ffm = {0};
  608. struct resize_buf rb = {0};
  609. bool fail = false;
  610. int ret;
  611. #ifdef _WIN32
  612. char **argv;
  613. SetErrorMode(SEM_FAILCRITICALERRORS);
  614. argv = malloc(argc * sizeof(char *));
  615. for (int i = 0; i < argc; i++) {
  616. size_t len = wcslen(argv_w[i]);
  617. int size;
  618. size = WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len,
  619. NULL, 0, NULL, NULL);
  620. argv[i] = malloc(size + 1);
  621. WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len, argv[i],
  622. size + 1, NULL, NULL);
  623. argv[i][size] = 0;
  624. }
  625. _setmode(_fileno(stdin), O_BINARY);
  626. #endif
  627. setvbuf(stderr, NULL, _IONBF, 0);
  628. ret = ffmpeg_mux_init(&ffm, argc, argv);
  629. if (ret != FFM_SUCCESS) {
  630. fprintf(stderr, "Couldn't initialize muxer\n");
  631. return ret;
  632. }
  633. while (!fail && safe_read(&info, sizeof(info)) == sizeof(info)) {
  634. resize_buf_resize(&rb, info.size);
  635. if (safe_read(rb.buf, info.size) == info.size) {
  636. ffmpeg_mux_packet(&ffm, rb.buf, &info);
  637. } else {
  638. fail = true;
  639. }
  640. }
  641. ffmpeg_mux_free(&ffm);
  642. resize_buf_free(&rb);
  643. #ifdef _WIN32
  644. for (int i = 0; i < argc; i++)
  645. free(argv[i]);
  646. free(argv);
  647. #endif
  648. return 0;
  649. }