ffmpeg-mux.c 21 KB

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