ffmpeg-mux.c 21 KB

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