ffmpeg-mux.c 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  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/threading.h>
  26. #include <util/platform.h>
  27. #include <util/circlebuf.h>
  28. #include <util/dstr.h>
  29. #include <libavcodec/avcodec.h>
  30. #include <libavformat/avformat.h>
  31. #include <libavutil/channel_layout.h>
  32. #include <libavutil/mastering_display_metadata.h>
  33. #define ANSI_COLOR_RED "\x1b[0;91m"
  34. #define ANSI_COLOR_MAGENTA "\x1b[0;95m"
  35. #define ANSI_COLOR_RESET "\x1b[0m"
  36. #if LIBAVCODEC_VERSION_MAJOR >= 58
  37. #define CODEC_FLAG_GLOBAL_H AV_CODEC_FLAG_GLOBAL_HEADER
  38. #else
  39. #define CODEC_FLAG_GLOBAL_H CODEC_FLAG_GLOBAL_HEADER
  40. #endif
  41. #define AVIO_BUFFER_SIZE 65536
  42. /* ------------------------------------------------------------------------- */
  43. static char *global_stream_key = "";
  44. struct resize_buf {
  45. uint8_t *buf;
  46. size_t size;
  47. size_t capacity;
  48. };
  49. static inline void resize_buf_resize(struct resize_buf *rb, size_t size)
  50. {
  51. if (!rb->buf) {
  52. rb->buf = malloc(size);
  53. rb->size = size;
  54. rb->capacity = size;
  55. } else {
  56. if (rb->capacity < size) {
  57. size_t capx2 = rb->capacity * 2;
  58. size_t new_cap = capx2 > size ? capx2 : size;
  59. rb->buf = realloc(rb->buf, new_cap);
  60. rb->capacity = new_cap;
  61. }
  62. rb->size = size;
  63. }
  64. }
  65. static inline void resize_buf_free(struct resize_buf *rb)
  66. {
  67. free(rb->buf);
  68. }
  69. /* ------------------------------------------------------------------------- */
  70. struct main_params {
  71. char *file;
  72. /* printable_file is file with any stream key information removed */
  73. struct dstr printable_file;
  74. int has_video;
  75. int tracks;
  76. char *vcodec;
  77. int vbitrate;
  78. int gop;
  79. int width;
  80. int height;
  81. int fps_num;
  82. int fps_den;
  83. int color_primaries;
  84. int color_trc;
  85. int colorspace;
  86. int color_range;
  87. int max_luminance;
  88. char *acodec;
  89. char *muxer_settings;
  90. };
  91. struct audio_params {
  92. char *name;
  93. int abitrate;
  94. int sample_rate;
  95. int frame_size;
  96. int channels;
  97. };
  98. struct header {
  99. uint8_t *data;
  100. int size;
  101. };
  102. struct audio_info {
  103. AVStream *stream;
  104. AVCodecContext *ctx;
  105. };
  106. struct io_header {
  107. uint64_t seek_offset;
  108. uint64_t data_length;
  109. };
  110. struct io_buffer {
  111. bool active;
  112. bool shutdown_requested;
  113. bool output_error;
  114. os_event_t *buffer_space_available_event;
  115. os_event_t *new_data_available_event;
  116. pthread_t io_thread;
  117. pthread_mutex_t data_mutex;
  118. FILE *output_file;
  119. struct circlebuf data;
  120. uint64_t next_pos;
  121. };
  122. struct ffmpeg_mux {
  123. AVFormatContext *output;
  124. AVStream *video_stream;
  125. AVCodecContext *video_ctx;
  126. AVPacket *packet;
  127. struct audio_info *audio_infos;
  128. struct main_params params;
  129. struct audio_params *audio;
  130. struct header video_header;
  131. struct header *audio_header;
  132. int num_audio_streams;
  133. bool initialized;
  134. struct io_buffer io;
  135. };
  136. static void header_free(struct header *header)
  137. {
  138. free(header->data);
  139. }
  140. static void free_avformat(struct ffmpeg_mux *ffm)
  141. {
  142. if (ffm->output) {
  143. avcodec_free_context(&ffm->video_ctx);
  144. if ((ffm->output->oformat->flags & AVFMT_NOFILE) == 0)
  145. avio_close(ffm->output->pb);
  146. avformat_free_context(ffm->output);
  147. ffm->output = NULL;
  148. }
  149. if (ffm->audio_infos) {
  150. for (int i = 0; i < ffm->num_audio_streams; ++i)
  151. avcodec_free_context(&ffm->audio_infos[i].ctx);
  152. free(ffm->audio_infos);
  153. }
  154. ffm->video_stream = NULL;
  155. ffm->audio_infos = NULL;
  156. ffm->num_audio_streams = 0;
  157. }
  158. static void ffmpeg_mux_free(struct ffmpeg_mux *ffm)
  159. {
  160. if (ffm->initialized) {
  161. av_write_trailer(ffm->output);
  162. }
  163. // If we're writing to a file with the circlebuf, shut it
  164. // down gracefully
  165. if (ffm->io.active) {
  166. os_atomic_set_bool(&ffm->io.shutdown_requested, true);
  167. // Wakes up the I/O thread and waits for it to finish
  168. pthread_mutex_lock(&ffm->io.data_mutex);
  169. os_event_signal(ffm->io.new_data_available_event);
  170. pthread_mutex_unlock(&ffm->io.data_mutex);
  171. pthread_join(ffm->io.io_thread, NULL);
  172. // Cleanup everything else
  173. av_free(ffm->output->pb->buffer);
  174. avio_context_free(&ffm->output->pb);
  175. os_event_destroy(ffm->io.new_data_available_event);
  176. os_event_destroy(ffm->io.buffer_space_available_event);
  177. pthread_mutex_destroy(&ffm->io.data_mutex);
  178. circlebuf_free(&ffm->io.data);
  179. }
  180. free_avformat(ffm);
  181. header_free(&ffm->video_header);
  182. if (ffm->audio_header) {
  183. for (int i = 0; i < ffm->params.tracks; i++) {
  184. header_free(&ffm->audio_header[i]);
  185. }
  186. free(ffm->audio_header);
  187. }
  188. if (ffm->audio) {
  189. free(ffm->audio);
  190. }
  191. dstr_free(&ffm->params.printable_file);
  192. av_packet_free(&ffm->packet);
  193. memset(ffm, 0, sizeof(*ffm));
  194. }
  195. static bool get_opt_str(int *p_argc, char ***p_argv, char **str,
  196. const char *opt)
  197. {
  198. int argc = *p_argc;
  199. char **argv = *p_argv;
  200. if (!argc) {
  201. printf("Missing expected option: '%s'\n", opt);
  202. return false;
  203. }
  204. (*p_argc)--;
  205. (*p_argv)++;
  206. *str = argv[0];
  207. return true;
  208. }
  209. static bool get_opt_int(int *p_argc, char ***p_argv, int *i, const char *opt)
  210. {
  211. char *str;
  212. if (!get_opt_str(p_argc, p_argv, &str, opt)) {
  213. return false;
  214. }
  215. *i = atoi(str);
  216. return true;
  217. }
  218. static bool get_audio_params(struct audio_params *audio, int *argc,
  219. char ***argv)
  220. {
  221. if (!get_opt_str(argc, argv, &audio->name, "audio track name"))
  222. return false;
  223. if (!get_opt_int(argc, argv, &audio->abitrate, "audio bitrate"))
  224. return false;
  225. if (!get_opt_int(argc, argv, &audio->sample_rate, "audio sample rate"))
  226. return false;
  227. if (!get_opt_int(argc, argv, &audio->frame_size, "audio frame size"))
  228. return false;
  229. if (!get_opt_int(argc, argv, &audio->channels, "audio channels"))
  230. return false;
  231. return true;
  232. }
  233. static void ffmpeg_log_callback(void *param, int level, const char *format,
  234. va_list args)
  235. {
  236. #ifdef ENABLE_FFMPEG_MUX_DEBUG
  237. char out_buffer[4096];
  238. struct dstr out = {0};
  239. vsnprintf(out_buffer, sizeof(out_buffer), format, args);
  240. dstr_copy(&out, out_buffer);
  241. if (global_stream_key && *global_stream_key) {
  242. dstr_replace(&out, global_stream_key, "{stream_key}");
  243. }
  244. switch (level) {
  245. case AV_LOG_INFO:
  246. fprintf(stdout, "info: [ffmpeg_muxer] %s", out.array);
  247. fflush(stdout);
  248. break;
  249. case AV_LOG_WARNING:
  250. fprintf(stdout, "%swarning: [ffmpeg_muxer] %s%s",
  251. ANSI_COLOR_MAGENTA, out.array, ANSI_COLOR_RESET);
  252. fflush(stdout);
  253. break;
  254. case AV_LOG_ERROR:
  255. fprintf(stderr, "%serror: [ffmpeg_muxer] %s%s", ANSI_COLOR_RED,
  256. out.array, ANSI_COLOR_RESET);
  257. fflush(stderr);
  258. }
  259. dstr_free(&out);
  260. #else
  261. UNUSED_PARAMETER(level);
  262. UNUSED_PARAMETER(format);
  263. UNUSED_PARAMETER(args);
  264. #endif
  265. UNUSED_PARAMETER(param);
  266. }
  267. static bool init_params(int *argc, char ***argv, struct main_params *params,
  268. struct audio_params **p_audio)
  269. {
  270. struct audio_params *audio = NULL;
  271. if (!get_opt_str(argc, argv, &params->file, "file name"))
  272. return false;
  273. if (!get_opt_int(argc, argv, &params->has_video, "video track count"))
  274. return false;
  275. if (!get_opt_int(argc, argv, &params->tracks, "audio track count"))
  276. return false;
  277. if (params->has_video > 1 || params->has_video < 0) {
  278. puts("Invalid number of video tracks\n");
  279. return false;
  280. }
  281. if (params->tracks < 0) {
  282. puts("Invalid number of audio tracks\n");
  283. return false;
  284. }
  285. if (params->has_video == 0 && params->tracks == 0) {
  286. puts("Must have at least 1 audio track or 1 video track\n");
  287. return false;
  288. }
  289. if (params->has_video) {
  290. if (!get_opt_str(argc, argv, &params->vcodec, "video codec"))
  291. return false;
  292. if (!get_opt_int(argc, argv, &params->vbitrate,
  293. "video bitrate"))
  294. return false;
  295. if (!get_opt_int(argc, argv, &params->width, "video width"))
  296. return false;
  297. if (!get_opt_int(argc, argv, &params->height, "video height"))
  298. return false;
  299. if (!get_opt_int(argc, argv, &params->color_primaries,
  300. "video color primaries"))
  301. return false;
  302. if (!get_opt_int(argc, argv, &params->color_trc,
  303. "video color trc"))
  304. return false;
  305. if (!get_opt_int(argc, argv, &params->colorspace,
  306. "video colorspace"))
  307. return false;
  308. if (!get_opt_int(argc, argv, &params->color_range,
  309. "video color range"))
  310. return false;
  311. if (!get_opt_int(argc, argv, &params->max_luminance,
  312. "video max luminance"))
  313. return false;
  314. if (!get_opt_int(argc, argv, &params->fps_num, "video fps num"))
  315. return false;
  316. if (!get_opt_int(argc, argv, &params->fps_den, "video fps den"))
  317. return false;
  318. }
  319. if (params->tracks) {
  320. if (!get_opt_str(argc, argv, &params->acodec, "audio codec"))
  321. return false;
  322. audio = calloc(params->tracks, sizeof(*audio));
  323. for (int i = 0; i < params->tracks; i++) {
  324. if (!get_audio_params(&audio[i], argc, argv)) {
  325. free(audio);
  326. return false;
  327. }
  328. }
  329. }
  330. *p_audio = audio;
  331. dstr_copy(&params->printable_file, params->file);
  332. get_opt_str(argc, argv, &global_stream_key, "stream key");
  333. if (strcmp(global_stream_key, "") != 0) {
  334. dstr_replace(&params->printable_file, global_stream_key,
  335. "{stream_key}");
  336. }
  337. av_log_set_callback(ffmpeg_log_callback);
  338. get_opt_str(argc, argv, &params->muxer_settings, "muxer settings");
  339. return true;
  340. }
  341. static bool new_stream(struct ffmpeg_mux *ffm, AVStream **stream,
  342. const char *name)
  343. {
  344. *stream = avformat_new_stream(ffm->output, NULL);
  345. if (!*stream) {
  346. fprintf(stderr, "Couldn't create stream for encoder '%s'\n",
  347. name);
  348. return false;
  349. }
  350. (*stream)->id = ffm->output->nb_streams - 1;
  351. return true;
  352. }
  353. static void create_video_stream(struct ffmpeg_mux *ffm)
  354. {
  355. AVCodecContext *context;
  356. void *extradata = NULL;
  357. const char *name = ffm->params.vcodec;
  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, &ffm->video_stream, name))
  364. return;
  365. if (ffm->video_header.size) {
  366. extradata = av_memdup(ffm->video_header.data,
  367. ffm->video_header.size);
  368. }
  369. context = avcodec_alloc_context3(NULL);
  370. context->codec_type = codec->type;
  371. context->codec_id = codec->id;
  372. context->bit_rate = (int64_t)ffm->params.vbitrate * 1000;
  373. context->width = ffm->params.width;
  374. context->height = ffm->params.height;
  375. context->coded_width = ffm->params.width;
  376. context->coded_height = ffm->params.height;
  377. context->color_primaries = ffm->params.color_primaries;
  378. context->color_trc = ffm->params.color_trc;
  379. context->colorspace = ffm->params.colorspace;
  380. context->color_range = ffm->params.color_range;
  381. context->extradata = extradata;
  382. context->extradata_size = ffm->video_header.size;
  383. context->time_base =
  384. (AVRational){ffm->params.fps_den, ffm->params.fps_num};
  385. ffm->video_stream->time_base = context->time_base;
  386. #if LIBAVFORMAT_VERSION_MAJOR < 59
  387. // codec->time_base may still be used if LIBAVFORMAT_VERSION_MAJOR < 59
  388. ffm->video_stream->codec->time_base = context->time_base;
  389. #endif
  390. ffm->video_stream->avg_frame_rate = av_inv_q(context->time_base);
  391. const int max_luminance = ffm->params.max_luminance;
  392. if (max_luminance > 0) {
  393. size_t content_size;
  394. AVContentLightMetadata *const content =
  395. av_content_light_metadata_alloc(&content_size);
  396. content->MaxCLL = max_luminance;
  397. content->MaxFALL = max_luminance;
  398. av_stream_add_side_data(ffm->video_stream,
  399. AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
  400. (uint8_t *)content, content_size);
  401. AVMasteringDisplayMetadata *const mastering =
  402. av_mastering_display_metadata_alloc();
  403. mastering->display_primaries[0][0] = av_make_q(17, 25);
  404. mastering->display_primaries[0][1] = av_make_q(8, 25);
  405. mastering->display_primaries[1][0] = av_make_q(53, 200);
  406. mastering->display_primaries[1][1] = av_make_q(69, 100);
  407. mastering->display_primaries[2][0] = av_make_q(3, 20);
  408. mastering->display_primaries[2][1] = av_make_q(3, 50);
  409. mastering->white_point[0] = av_make_q(3127, 10000);
  410. mastering->white_point[1] = av_make_q(329, 1000);
  411. mastering->min_luminance = av_make_q(0, 1);
  412. mastering->max_luminance = av_make_q(max_luminance, 1);
  413. mastering->has_primaries = 1;
  414. mastering->has_luminance = 1;
  415. av_stream_add_side_data(ffm->video_stream,
  416. AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
  417. (uint8_t *)mastering,
  418. sizeof(*mastering));
  419. }
  420. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  421. context->flags |= CODEC_FLAG_GLOBAL_H;
  422. avcodec_parameters_from_context(ffm->video_stream->codecpar, context);
  423. ffm->video_ctx = context;
  424. }
  425. static void create_audio_stream(struct ffmpeg_mux *ffm, int idx)
  426. {
  427. AVCodecContext *context;
  428. AVStream *stream;
  429. void *extradata = NULL;
  430. const char *name = ffm->params.acodec;
  431. const AVCodecDescriptor *codec = avcodec_descriptor_get_by_name(name);
  432. if (!codec) {
  433. fprintf(stderr, "Couldn't find codec '%s'\n", name);
  434. return;
  435. }
  436. if (!new_stream(ffm, &stream, name))
  437. return;
  438. av_dict_set(&stream->metadata, "title", ffm->audio[idx].name, 0);
  439. stream->time_base = (AVRational){1, ffm->audio[idx].sample_rate};
  440. if (ffm->audio_header[idx].size) {
  441. extradata = av_memdup(ffm->audio_header[idx].data,
  442. ffm->audio_header[idx].size);
  443. }
  444. context = avcodec_alloc_context3(NULL);
  445. context->codec_type = codec->type;
  446. context->codec_id = codec->id;
  447. context->bit_rate = (int64_t)ffm->audio[idx].abitrate * 1000;
  448. context->channels = ffm->audio[idx].channels;
  449. context->sample_rate = ffm->audio[idx].sample_rate;
  450. context->frame_size = ffm->audio[idx].frame_size;
  451. context->sample_fmt = AV_SAMPLE_FMT_S16;
  452. context->time_base = stream->time_base;
  453. context->extradata = extradata;
  454. context->extradata_size = ffm->audio_header[idx].size;
  455. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(59, 24, 100)
  456. context->channel_layout =
  457. av_get_default_channel_layout(context->channels);
  458. //avutil default channel layout for 5 channels is 5.0 ; fix for 4.1
  459. if (context->channels == 5)
  460. context->channel_layout = av_get_channel_layout("4.1");
  461. #else
  462. av_channel_layout_default(&context->ch_layout, context->channels);
  463. //avutil default channel layout for 5 channels is 5.0 ; fix for 4.1
  464. if (context->channels == 5)
  465. context->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1;
  466. #endif
  467. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  468. context->flags |= CODEC_FLAG_GLOBAL_H;
  469. avcodec_parameters_from_context(stream->codecpar, context);
  470. ffm->audio_infos[ffm->num_audio_streams].stream = stream;
  471. ffm->audio_infos[ffm->num_audio_streams].ctx = context;
  472. ffm->num_audio_streams++;
  473. }
  474. static bool init_streams(struct ffmpeg_mux *ffm)
  475. {
  476. if (ffm->params.has_video)
  477. create_video_stream(ffm);
  478. if (ffm->params.tracks) {
  479. ffm->audio_infos =
  480. calloc(ffm->params.tracks, sizeof(*ffm->audio_infos));
  481. for (int i = 0; i < ffm->params.tracks; i++)
  482. create_audio_stream(ffm, i);
  483. }
  484. if (!ffm->video_stream && !ffm->num_audio_streams)
  485. return false;
  486. return true;
  487. }
  488. static void set_header(struct header *header, uint8_t *data, size_t size)
  489. {
  490. header->size = (int)size;
  491. header->data = malloc(size);
  492. memcpy(header->data, data, size);
  493. }
  494. static void ffmpeg_mux_header(struct ffmpeg_mux *ffm, uint8_t *data,
  495. struct ffm_packet_info *info)
  496. {
  497. if (info->type == FFM_PACKET_VIDEO) {
  498. set_header(&ffm->video_header, data, (size_t)info->size);
  499. } else {
  500. set_header(&ffm->audio_header[info->index], data,
  501. (size_t)info->size);
  502. }
  503. }
  504. static size_t safe_read(void *vdata, size_t size)
  505. {
  506. uint8_t *data = vdata;
  507. size_t total = size;
  508. while (size > 0) {
  509. size_t in_size = fread(data, 1, size, stdin);
  510. if (in_size == 0)
  511. return 0;
  512. size -= in_size;
  513. data += in_size;
  514. }
  515. return total;
  516. }
  517. static bool ffmpeg_mux_get_header(struct ffmpeg_mux *ffm)
  518. {
  519. struct ffm_packet_info info = {0};
  520. bool success = safe_read(&info, sizeof(info)) == sizeof(info);
  521. if (success) {
  522. uint8_t *data = malloc(info.size);
  523. if (safe_read(data, info.size) == info.size) {
  524. ffmpeg_mux_header(ffm, data, &info);
  525. } else {
  526. success = false;
  527. }
  528. free(data);
  529. }
  530. return success;
  531. }
  532. static inline bool ffmpeg_mux_get_extra_data(struct ffmpeg_mux *ffm)
  533. {
  534. if (ffm->params.has_video) {
  535. if (!ffmpeg_mux_get_header(ffm)) {
  536. return false;
  537. }
  538. }
  539. for (int i = 0; i < ffm->params.tracks; i++) {
  540. if (!ffmpeg_mux_get_header(ffm)) {
  541. return false;
  542. }
  543. }
  544. return true;
  545. }
  546. #ifdef _MSC_VER
  547. #pragma warning(disable : 4996)
  548. #endif
  549. #define CHUNK_SIZE 1048576
  550. static void *ffmpeg_mux_io_thread(void *data)
  551. {
  552. struct ffmpeg_mux *ffm = data;
  553. // Chunk collects the writes into a larger batch
  554. size_t chunk_used = 0;
  555. unsigned char *chunk = malloc(CHUNK_SIZE);
  556. if (!chunk) {
  557. os_atomic_set_bool(&ffm->io.output_error, true);
  558. fprintf(stderr, "Error allocating memory for output\n");
  559. goto error;
  560. }
  561. bool shutting_down;
  562. bool want_seek = false;
  563. bool force_flush_chunk = false;
  564. // current_seek_position is a virtual position updated as we read from
  565. // the buffer, if it becomes discontinuous due to a seek request from
  566. // ffmpeg, then we flush the chunk. next_seek_position is the actual
  567. // offset we should seek to when we write the chunk.
  568. uint64_t current_seek_position = 0;
  569. uint64_t next_seek_position;
  570. for (;;) {
  571. // Wait for ffmpeg to write data to the buffer
  572. os_event_wait(ffm->io.new_data_available_event);
  573. // Loop to write in chunk_size chunks
  574. for (;;) {
  575. shutting_down = os_atomic_load_bool(
  576. &ffm->io.shutdown_requested);
  577. pthread_mutex_lock(&ffm->io.data_mutex);
  578. // Fetch as many writes as possible from the circlebuf
  579. // and fill up our local chunk. This may involve seeking
  580. // if ffmpeg needs to, so take care of that as well.
  581. for (;;) {
  582. size_t available = ffm->io.data.size;
  583. // Buffer is empty (now) or was already empty (we got
  584. // woken up to exit)
  585. if (!available)
  586. break;
  587. // Get seek offset and data size
  588. struct io_header header;
  589. circlebuf_peek_front(&ffm->io.data, &header,
  590. sizeof(header));
  591. // Do we need to seek?
  592. if (header.seek_offset !=
  593. current_seek_position) {
  594. // If there's already part of a chunk pending,
  595. // flush it at the current offset. Similarly,
  596. // if we already plan to seek, then seek.
  597. if (chunk_used || want_seek) {
  598. force_flush_chunk = true;
  599. break;
  600. }
  601. // Mark that we need to seek and where to
  602. want_seek = true;
  603. next_seek_position = header.seek_offset;
  604. // Update our virtual position
  605. current_seek_position =
  606. header.seek_offset;
  607. }
  608. // Make sure there's enough room for the data, if
  609. // not then force a flush
  610. if (header.data_length + chunk_used >
  611. CHUNK_SIZE) {
  612. force_flush_chunk = true;
  613. break;
  614. }
  615. // Remove header that we already read
  616. circlebuf_pop_front(&ffm->io.data, NULL,
  617. sizeof(header));
  618. // Copy from the buffer to our local chunk
  619. circlebuf_pop_front(&ffm->io.data,
  620. chunk + chunk_used,
  621. header.data_length);
  622. // Update offsets
  623. chunk_used += header.data_length;
  624. current_seek_position += header.data_length;
  625. }
  626. // Signal that there is more room in the buffer
  627. os_event_signal(ffm->io.buffer_space_available_event);
  628. // Try to avoid lots of small writes unless this was the final
  629. // data left in the buffer. The buffer might be entirely empty
  630. // if we were woken up to exit.
  631. if (!force_flush_chunk &&
  632. (!chunk_used ||
  633. (chunk_used < 65536 && !shutting_down))) {
  634. os_event_reset(
  635. ffm->io.new_data_available_event);
  636. pthread_mutex_unlock(&ffm->io.data_mutex);
  637. break;
  638. }
  639. pthread_mutex_unlock(&ffm->io.data_mutex);
  640. // Seek if we need to
  641. if (want_seek) {
  642. os_fseeki64(ffm->io.output_file,
  643. next_seek_position, SEEK_SET);
  644. current_seek_position = next_seek_position;
  645. want_seek = false;
  646. }
  647. // Write the current chunk to the output file
  648. if (fwrite(chunk, chunk_used, 1, ffm->io.output_file) !=
  649. 1) {
  650. os_atomic_set_bool(&ffm->io.output_error, true);
  651. fprintf(stderr, "Error writing to '%s', %s\n",
  652. ffm->params.printable_file.array,
  653. strerror(errno));
  654. goto error;
  655. }
  656. chunk_used = 0;
  657. force_flush_chunk = false;
  658. }
  659. // If this was the last chunk, time to exit
  660. if (shutting_down)
  661. break;
  662. }
  663. error:
  664. if (chunk)
  665. free(chunk);
  666. fclose(ffm->io.output_file);
  667. return NULL;
  668. }
  669. static int64_t ffmpeg_mux_seek_av_buffer(void *opaque, int64_t offset,
  670. int whence)
  671. {
  672. struct ffmpeg_mux *ffm = opaque;
  673. // If the output thread failed, signal that back up the stack
  674. if (os_atomic_load_bool(&ffm->io.output_error))
  675. return -1;
  676. // Update where the next write should go
  677. pthread_mutex_lock(&ffm->io.data_mutex);
  678. if (whence == SEEK_SET)
  679. ffm->io.next_pos = offset;
  680. else if (whence == SEEK_CUR)
  681. ffm->io.next_pos += offset;
  682. pthread_mutex_unlock(&ffm->io.data_mutex);
  683. return 0;
  684. }
  685. static int ffmpeg_mux_write_av_buffer(void *opaque, uint8_t *buf, int buf_size)
  686. {
  687. struct ffmpeg_mux *ffm = opaque;
  688. // If the output thread failed, signal that back up the stack
  689. if (os_atomic_load_bool(&ffm->io.output_error))
  690. return -1;
  691. for (;;) {
  692. pthread_mutex_lock(&ffm->io.data_mutex);
  693. // Avoid unbounded growth of the circlebuf, cap to 256 MB
  694. if (ffm->io.data.capacity >= 256 * 1048576 &&
  695. ffm->io.data.capacity - ffm->io.data.size <
  696. buf_size + sizeof(struct io_header)) {
  697. // No space, wait for the I/O thread to make space
  698. os_event_reset(ffm->io.buffer_space_available_event);
  699. pthread_mutex_unlock(&ffm->io.data_mutex);
  700. os_event_wait(ffm->io.buffer_space_available_event);
  701. } else {
  702. break;
  703. }
  704. }
  705. struct io_header header;
  706. header.data_length = buf_size;
  707. header.seek_offset = ffm->io.next_pos;
  708. // Copy the data into the buffer
  709. circlebuf_push_back(&ffm->io.data, &header, sizeof(header));
  710. circlebuf_push_back(&ffm->io.data, buf, buf_size);
  711. // Advance the next write position
  712. ffm->io.next_pos += buf_size;
  713. // Tell the I/O thread that there's new data to be written
  714. os_event_signal(ffm->io.new_data_available_event);
  715. pthread_mutex_unlock(&ffm->io.data_mutex);
  716. return buf_size;
  717. }
  718. static inline int open_output_file(struct ffmpeg_mux *ffm)
  719. {
  720. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  721. AVOutputFormat *format = ffm->output->oformat;
  722. #else
  723. const AVOutputFormat *format = ffm->output->oformat;
  724. #endif
  725. int ret;
  726. if ((format->flags & AVFMT_NOFILE) == 0) {
  727. // If not outputting to a network, write to a circlebuf
  728. // instead of relying on ffmpeg disk output. This hopefully
  729. // works around too small buffers somewhere causing output
  730. // stalls when recording.
  731. // We're in charge of managing the actual file now
  732. ffm->io.output_file = os_fopen(ffm->params.file, "wb");
  733. if (!ffm->io.output_file) {
  734. fprintf(stderr, "Couldn't open '%s', %s\n",
  735. ffm->params.printable_file.array,
  736. strerror(errno));
  737. return FFM_ERROR;
  738. }
  739. // Start at 1MB, this can grow up to 256 MB depending
  740. // how fast data is going in and out (limited in
  741. // ffmpeg_mux_write_av_buffer)
  742. circlebuf_reserve(&ffm->io.data, 1048576);
  743. pthread_mutex_init(&ffm->io.data_mutex, NULL);
  744. os_event_init(&ffm->io.buffer_space_available_event,
  745. OS_EVENT_TYPE_AUTO);
  746. os_event_init(&ffm->io.new_data_available_event,
  747. OS_EVENT_TYPE_AUTO);
  748. pthread_create(&ffm->io.io_thread, NULL, ffmpeg_mux_io_thread,
  749. ffm);
  750. unsigned char *avio_ctx_buffer = av_malloc(AVIO_BUFFER_SIZE);
  751. ffm->output->pb = avio_alloc_context(
  752. avio_ctx_buffer, AVIO_BUFFER_SIZE, 1, ffm, NULL,
  753. ffmpeg_mux_write_av_buffer, ffmpeg_mux_seek_av_buffer);
  754. ffm->io.active = true;
  755. }
  756. AVDictionary *dict = NULL;
  757. if ((ret = av_dict_parse_string(&dict, ffm->params.muxer_settings, "=",
  758. " ", 0))) {
  759. fprintf(stderr, "Failed to parse muxer settings: %s\n%s\n",
  760. av_err2str(ret), ffm->params.muxer_settings);
  761. av_dict_free(&dict);
  762. }
  763. if (av_dict_count(dict) > 0) {
  764. printf("Using muxer settings:");
  765. AVDictionaryEntry *entry = NULL;
  766. while ((entry = av_dict_get(dict, "", entry,
  767. AV_DICT_IGNORE_SUFFIX)))
  768. printf("\n\t%s=%s", entry->key, entry->value);
  769. printf("\n");
  770. }
  771. ret = avformat_write_header(ffm->output, &dict);
  772. if (ret < 0) {
  773. fprintf(stderr, "Error opening '%s': %s",
  774. ffm->params.printable_file.array, av_err2str(ret));
  775. av_dict_free(&dict);
  776. return ret == -22 ? FFM_UNSUPPORTED : FFM_ERROR;
  777. }
  778. av_dict_free(&dict);
  779. return FFM_SUCCESS;
  780. }
  781. #define SRT_PROTO "srt"
  782. #define UDP_PROTO "udp"
  783. #define TCP_PROTO "tcp"
  784. #define HTTP_PROTO "http"
  785. #define RIST_PROTO "rist"
  786. static bool ffmpeg_mux_is_network(struct ffmpeg_mux *ffm)
  787. {
  788. return !strncmp(ffm->params.file, SRT_PROTO, sizeof(SRT_PROTO) - 1) ||
  789. !strncmp(ffm->params.file, UDP_PROTO, sizeof(UDP_PROTO) - 1) ||
  790. !strncmp(ffm->params.file, TCP_PROTO, sizeof(TCP_PROTO) - 1) ||
  791. !strncmp(ffm->params.file, HTTP_PROTO, sizeof(HTTP_PROTO) - 1) ||
  792. !strncmp(ffm->params.file, RIST_PROTO, sizeof(RIST_PROTO) - 1);
  793. }
  794. static int ffmpeg_mux_init_context(struct ffmpeg_mux *ffm)
  795. {
  796. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  797. AVOutputFormat *output_format;
  798. #else
  799. const AVOutputFormat *output_format;
  800. #endif
  801. int ret;
  802. bool is_http = false;
  803. is_http = (strncmp(ffm->params.file, HTTP_PROTO,
  804. sizeof(HTTP_PROTO) - 1) == 0);
  805. bool is_network = ffmpeg_mux_is_network(ffm);
  806. if (is_network) {
  807. avformat_network_init();
  808. }
  809. if (is_network && !is_http)
  810. output_format = av_guess_format("mpegts", NULL, "video/M2PT");
  811. else
  812. output_format = av_guess_format(NULL, ffm->params.file, NULL);
  813. if (output_format == NULL) {
  814. fprintf(stderr, "Couldn't find an appropriate muxer for '%s'\n",
  815. ffm->params.printable_file.array);
  816. return FFM_ERROR;
  817. }
  818. #ifdef ENABLE_FFMPEG_MUX_DEBUG
  819. printf("info: Output format name and long_name: %s, %s\n",
  820. output_format->name ? output_format->name : "unknown",
  821. output_format->long_name ? output_format->long_name : "unknown");
  822. #endif
  823. ret = avformat_alloc_output_context2(&ffm->output, output_format, NULL,
  824. ffm->params.file);
  825. if (ret < 0) {
  826. fprintf(stderr, "Couldn't initialize output context: %s\n",
  827. av_err2str(ret));
  828. return FFM_ERROR;
  829. }
  830. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  831. ffm->output->oformat->video_codec = AV_CODEC_ID_NONE;
  832. ffm->output->oformat->audio_codec = AV_CODEC_ID_NONE;
  833. #endif
  834. if (!init_streams(ffm)) {
  835. free_avformat(ffm);
  836. return FFM_ERROR;
  837. }
  838. ret = open_output_file(ffm);
  839. if (ret != FFM_SUCCESS) {
  840. free_avformat(ffm);
  841. return ret;
  842. }
  843. return FFM_SUCCESS;
  844. }
  845. static int ffmpeg_mux_init_internal(struct ffmpeg_mux *ffm, int argc,
  846. char *argv[])
  847. {
  848. argc--;
  849. argv++;
  850. if (!init_params(&argc, &argv, &ffm->params, &ffm->audio))
  851. return FFM_ERROR;
  852. if (ffm->params.tracks) {
  853. ffm->audio_header =
  854. calloc(ffm->params.tracks, sizeof(*ffm->audio_header));
  855. }
  856. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
  857. av_register_all();
  858. #endif
  859. if (!ffmpeg_mux_get_extra_data(ffm))
  860. return FFM_ERROR;
  861. ffm->packet = av_packet_alloc();
  862. /* ffmpeg does not have a way of telling what's supported
  863. * for a given output format, so we try each possibility */
  864. return ffmpeg_mux_init_context(ffm);
  865. }
  866. static int ffmpeg_mux_init(struct ffmpeg_mux *ffm, int argc, char *argv[])
  867. {
  868. int ret = ffmpeg_mux_init_internal(ffm, argc, argv);
  869. if (ret != FFM_SUCCESS) {
  870. ffmpeg_mux_free(ffm);
  871. return ret;
  872. }
  873. ffm->initialized = true;
  874. return ret;
  875. }
  876. static inline int get_index(struct ffmpeg_mux *ffm,
  877. struct ffm_packet_info *info)
  878. {
  879. if (info->type == FFM_PACKET_VIDEO) {
  880. if (ffm->video_stream) {
  881. return ffm->video_stream->id;
  882. }
  883. } else {
  884. if ((int)info->index < ffm->num_audio_streams) {
  885. return ffm->audio_infos[info->index].stream->id;
  886. }
  887. }
  888. return -1;
  889. }
  890. static AVCodecContext *get_codec_context(struct ffmpeg_mux *ffm,
  891. struct ffm_packet_info *info)
  892. {
  893. if (info->type == FFM_PACKET_VIDEO) {
  894. if (ffm->video_stream) {
  895. return ffm->video_ctx;
  896. }
  897. } else {
  898. if ((int)info->index < ffm->num_audio_streams) {
  899. return ffm->audio_infos[info->index].ctx;
  900. }
  901. }
  902. return NULL;
  903. }
  904. static inline AVStream *get_stream(struct ffmpeg_mux *ffm, int idx)
  905. {
  906. return ffm->output->streams[idx];
  907. }
  908. static inline int64_t rescale_ts(struct ffmpeg_mux *ffm,
  909. AVRational codec_time_base, int64_t val,
  910. int idx)
  911. {
  912. AVStream *stream = get_stream(ffm, idx);
  913. return av_rescale_q_rnd(val / codec_time_base.num, codec_time_base,
  914. stream->time_base,
  915. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  916. }
  917. static inline bool ffmpeg_mux_packet(struct ffmpeg_mux *ffm, uint8_t *buf,
  918. struct ffm_packet_info *info)
  919. {
  920. int idx = get_index(ffm, info);
  921. /* The muxer might not support video/audio, or multiple audio tracks */
  922. if (idx == -1) {
  923. return true;
  924. }
  925. const AVRational codec_time_base =
  926. get_codec_context(ffm, info)->time_base;
  927. ffm->packet->data = buf;
  928. ffm->packet->size = (int)info->size;
  929. ffm->packet->stream_index = idx;
  930. ffm->packet->pts = rescale_ts(ffm, codec_time_base, info->pts, idx);
  931. ffm->packet->dts = rescale_ts(ffm, codec_time_base, info->dts, idx);
  932. if (info->keyframe)
  933. ffm->packet->flags = AV_PKT_FLAG_KEY;
  934. int ret = av_interleaved_write_frame(ffm->output, ffm->packet);
  935. if (ret < 0) {
  936. fprintf(stderr, "av_interleaved_write_frame failed: %d: %s\n",
  937. ret, av_err2str(ret));
  938. }
  939. /* Treat "Invalid data found when processing input" and "Invalid argument" as non-fatal */
  940. if (ret == AVERROR_INVALIDDATA || ret == -EINVAL) {
  941. return true;
  942. }
  943. return ret >= 0;
  944. }
  945. static inline bool read_change_file(struct ffmpeg_mux *ffm, uint32_t size,
  946. struct resize_buf *filename, int argc,
  947. char **argv)
  948. {
  949. resize_buf_resize(filename, size + 1);
  950. if (safe_read(filename->buf, size) != size) {
  951. return false;
  952. }
  953. filename->buf[size] = 0;
  954. #ifdef ENABLE_FFMPEG_MUX_DEBUG
  955. fprintf(stderr, "info: New output file name: %s\n", filename->buf);
  956. #endif
  957. int ret;
  958. char *argv1_backup = argv[1];
  959. argv[1] = (char *)filename->buf;
  960. ffmpeg_mux_free(ffm);
  961. ret = ffmpeg_mux_init(ffm, argc, argv);
  962. if (ret != FFM_SUCCESS) {
  963. fprintf(stderr, "Couldn't initialize muxer\n");
  964. return false;
  965. }
  966. argv[1] = argv1_backup;
  967. return true;
  968. }
  969. /* ------------------------------------------------------------------------- */
  970. #ifdef _WIN32
  971. int wmain(int argc, wchar_t *argv_w[])
  972. #else
  973. int main(int argc, char *argv[])
  974. #endif
  975. {
  976. struct ffm_packet_info info = {0};
  977. struct ffmpeg_mux ffm = {0};
  978. struct resize_buf rb = {0};
  979. struct resize_buf rb_filename = {0};
  980. bool fail = false;
  981. int ret;
  982. #ifdef _WIN32
  983. char **argv;
  984. SetErrorMode(SEM_FAILCRITICALERRORS);
  985. argv = malloc(argc * sizeof(char *));
  986. for (int i = 0; i < argc; i++) {
  987. size_t len = wcslen(argv_w[i]);
  988. int size;
  989. size = WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len,
  990. NULL, 0, NULL, NULL);
  991. argv[i] = malloc(size + 1);
  992. WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len, argv[i],
  993. size + 1, NULL, NULL);
  994. argv[i][size] = 0;
  995. }
  996. _setmode(_fileno(stdin), O_BINARY);
  997. #endif
  998. setvbuf(stderr, NULL, _IONBF, 0);
  999. ret = ffmpeg_mux_init(&ffm, argc, argv);
  1000. if (ret != FFM_SUCCESS) {
  1001. fprintf(stderr, "Couldn't initialize muxer\n");
  1002. return ret;
  1003. }
  1004. while (!fail && safe_read(&info, sizeof(info)) == sizeof(info)) {
  1005. if (info.type == FFM_PACKET_CHANGE_FILE) {
  1006. fail = !read_change_file(&ffm, info.size, &rb_filename,
  1007. argc, argv);
  1008. continue;
  1009. }
  1010. resize_buf_resize(&rb, info.size);
  1011. if (safe_read(rb.buf, info.size) == info.size) {
  1012. fail = !ffmpeg_mux_packet(&ffm, rb.buf, &info);
  1013. } else {
  1014. fail = true;
  1015. }
  1016. }
  1017. ffmpeg_mux_free(&ffm);
  1018. resize_buf_free(&rb);
  1019. resize_buf_free(&rb_filename);
  1020. #ifdef _WIN32
  1021. for (int i = 0; i < argc; i++)
  1022. free(argv[i]);
  1023. free(argv);
  1024. #endif
  1025. return 0;
  1026. }