ffmpeg-mux.c 21 KB

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