ffmpeg-mux.c 21 KB

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