obs-ffmpeg-output.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  1. /******************************************************************************
  2. Copyright (C) 2014 by Hugh Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <obs-module.h>
  15. #include <util/circlebuf.h>
  16. #include <util/threading.h>
  17. #include <util/dstr.h>
  18. #include <util/darray.h>
  19. #include <util/platform.h>
  20. #include <libavutil/opt.h>
  21. #include <libavutil/pixdesc.h>
  22. #include <libavformat/avformat.h>
  23. #include <libswscale/swscale.h>
  24. #include "obs-ffmpeg-formats.h"
  25. #include "closest-pixel-format.h"
  26. #include "obs-ffmpeg-compat.h"
  27. struct ffmpeg_cfg {
  28. const char *url;
  29. const char *format_name;
  30. const char *format_mime_type;
  31. const char *muxer_settings;
  32. int gop_size;
  33. int video_bitrate;
  34. int audio_bitrate;
  35. const char *video_encoder;
  36. int video_encoder_id;
  37. const char *audio_encoder;
  38. int audio_encoder_id;
  39. const char *video_settings;
  40. const char *audio_settings;
  41. int audio_mix_count;
  42. int audio_tracks;
  43. enum AVPixelFormat format;
  44. enum AVColorRange color_range;
  45. enum AVColorSpace color_space;
  46. int scale_width;
  47. int scale_height;
  48. int width;
  49. int height;
  50. };
  51. struct ffmpeg_data {
  52. AVStream *video;
  53. AVStream **audio_streams;
  54. AVCodec *acodec;
  55. AVCodec *vcodec;
  56. AVFormatContext *output;
  57. struct SwsContext *swscale;
  58. int64_t total_frames;
  59. AVFrame *vframe;
  60. int frame_size;
  61. uint64_t start_timestamp;
  62. int64_t total_samples[MAX_AUDIO_MIXES];
  63. uint32_t audio_samplerate;
  64. enum audio_format audio_format;
  65. size_t audio_planes;
  66. size_t audio_size;
  67. int num_audio_streams;
  68. /* audio_tracks is a bitmask storing the indices of the mixes */
  69. int audio_tracks;
  70. struct circlebuf excess_frames[MAX_AUDIO_MIXES][MAX_AV_PLANES];
  71. uint8_t *samples[MAX_AUDIO_MIXES][MAX_AV_PLANES];
  72. AVFrame *aframe[MAX_AUDIO_MIXES];
  73. struct ffmpeg_cfg config;
  74. bool initialized;
  75. char *last_error;
  76. };
  77. struct ffmpeg_output {
  78. obs_output_t *output;
  79. volatile bool active;
  80. struct ffmpeg_data ff_data;
  81. bool connecting;
  82. pthread_t start_thread;
  83. uint64_t total_bytes;
  84. uint64_t audio_start_ts;
  85. uint64_t video_start_ts;
  86. uint64_t stop_ts;
  87. volatile bool stopping;
  88. bool write_thread_active;
  89. pthread_mutex_t write_mutex;
  90. pthread_t write_thread;
  91. os_sem_t *write_sem;
  92. os_event_t *stop_event;
  93. DARRAY(AVPacket) packets;
  94. };
  95. /* ------------------------------------------------------------------------- */
  96. static void ffmpeg_output_set_last_error(struct ffmpeg_data *data,
  97. const char *error)
  98. {
  99. if (data->last_error)
  100. bfree(data->last_error);
  101. data->last_error = bstrdup(error);
  102. }
  103. void ffmpeg_log_error(int log_level, struct ffmpeg_data *data,
  104. const char *format, ...)
  105. {
  106. va_list args;
  107. char out[4096];
  108. va_start(args, format);
  109. vsnprintf(out, sizeof(out), format, args);
  110. va_end(args);
  111. ffmpeg_output_set_last_error(data, out);
  112. blog(log_level, "%s", out);
  113. }
  114. static bool new_stream(struct ffmpeg_data *data, AVStream **stream,
  115. AVCodec **codec, enum AVCodecID id, const char *name)
  116. {
  117. *codec = (!!name && *name) ? avcodec_find_encoder_by_name(name)
  118. : avcodec_find_encoder(id);
  119. if (!*codec) {
  120. ffmpeg_log_error(LOG_WARNING, data,
  121. "Couldn't find encoder '%s'",
  122. avcodec_get_name(id));
  123. return false;
  124. }
  125. *stream = avformat_new_stream(data->output, *codec);
  126. if (!*stream) {
  127. ffmpeg_log_error(LOG_WARNING, data,
  128. "Couldn't create stream for encoder '%s'",
  129. avcodec_get_name(id));
  130. return false;
  131. }
  132. (*stream)->id = data->output->nb_streams - 1;
  133. return true;
  134. }
  135. static bool parse_params(AVCodecContext *context, char **opts)
  136. {
  137. bool ret = true;
  138. if (!context || !context->priv_data)
  139. return true;
  140. while (*opts) {
  141. char *opt = *opts;
  142. char *assign = strchr(opt, '=');
  143. if (assign) {
  144. char *name = opt;
  145. char *value;
  146. *assign = 0;
  147. value = assign + 1;
  148. if (av_opt_set(context->priv_data, name, value, 0)) {
  149. blog(LOG_WARNING, "Failed to set %s=%s", name,
  150. value);
  151. ret = false;
  152. }
  153. }
  154. opts++;
  155. }
  156. return ret;
  157. }
  158. static bool open_video_codec(struct ffmpeg_data *data)
  159. {
  160. AVCodecContext *context = data->video->codec;
  161. char **opts = strlist_split(data->config.video_settings, ' ', false);
  162. int ret;
  163. if (strcmp(data->vcodec->name, "libx264") == 0)
  164. av_opt_set(context->priv_data, "preset", "veryfast", 0);
  165. if (opts) {
  166. // libav requires x264 parameters in a special format which may be non-obvious
  167. if (!parse_params(context, opts) &&
  168. strcmp(data->vcodec->name, "libx264") == 0)
  169. blog(LOG_WARNING,
  170. "If you're trying to set x264 parameters, use x264-params=name=value:name=value");
  171. strlist_free(opts);
  172. }
  173. ret = avcodec_open2(context, data->vcodec, NULL);
  174. if (ret < 0) {
  175. ffmpeg_log_error(LOG_WARNING, data,
  176. "Failed to open video codec: %s",
  177. av_err2str(ret));
  178. return false;
  179. }
  180. data->vframe = av_frame_alloc();
  181. if (!data->vframe) {
  182. ffmpeg_log_error(LOG_WARNING, data,
  183. "Failed to allocate video frame");
  184. return false;
  185. }
  186. data->vframe->format = context->pix_fmt;
  187. data->vframe->width = context->width;
  188. data->vframe->height = context->height;
  189. data->vframe->colorspace = data->config.color_space;
  190. data->vframe->color_range = data->config.color_range;
  191. ret = av_frame_get_buffer(data->vframe, base_get_alignment());
  192. if (ret < 0) {
  193. ffmpeg_log_error(LOG_WARNING, data,
  194. "Failed to allocate vframe: %s",
  195. av_err2str(ret));
  196. return false;
  197. }
  198. return true;
  199. }
  200. static bool init_swscale(struct ffmpeg_data *data, AVCodecContext *context)
  201. {
  202. data->swscale = sws_getContext(
  203. data->config.width, data->config.height, data->config.format,
  204. data->config.scale_width, data->config.scale_height,
  205. context->pix_fmt, SWS_BICUBIC, NULL, NULL, NULL);
  206. if (!data->swscale) {
  207. ffmpeg_log_error(LOG_WARNING, data,
  208. "Could not initialize swscale");
  209. return false;
  210. }
  211. return true;
  212. }
  213. static bool create_video_stream(struct ffmpeg_data *data)
  214. {
  215. enum AVPixelFormat closest_format;
  216. AVCodecContext *context;
  217. struct obs_video_info ovi;
  218. if (!obs_get_video_info(&ovi)) {
  219. ffmpeg_log_error(LOG_WARNING, data, "No active video");
  220. return false;
  221. }
  222. if (!new_stream(data, &data->video, &data->vcodec,
  223. data->output->oformat->video_codec,
  224. data->config.video_encoder))
  225. return false;
  226. closest_format =
  227. get_closest_format(data->config.format, data->vcodec->pix_fmts);
  228. context = data->video->codec;
  229. context->bit_rate = data->config.video_bitrate * 1000;
  230. context->width = data->config.scale_width;
  231. context->height = data->config.scale_height;
  232. context->time_base = (AVRational){ovi.fps_den, ovi.fps_num};
  233. context->gop_size = data->config.gop_size;
  234. context->pix_fmt = closest_format;
  235. context->colorspace = data->config.color_space;
  236. context->color_range = data->config.color_range;
  237. context->thread_count = 0;
  238. data->video->time_base = context->time_base;
  239. if (data->output->oformat->flags & AVFMT_GLOBALHEADER)
  240. context->flags |= CODEC_FLAG_GLOBAL_H;
  241. if (!open_video_codec(data))
  242. return false;
  243. if (context->pix_fmt != data->config.format ||
  244. data->config.width != data->config.scale_width ||
  245. data->config.height != data->config.scale_height) {
  246. if (!init_swscale(data, context))
  247. return false;
  248. }
  249. return true;
  250. }
  251. static bool open_audio_codec(struct ffmpeg_data *data, int idx)
  252. {
  253. AVCodecContext *context = data->audio_streams[idx]->codec;
  254. char **opts = strlist_split(data->config.audio_settings, ' ', false);
  255. int ret;
  256. if (opts) {
  257. parse_params(context, opts);
  258. strlist_free(opts);
  259. }
  260. data->aframe[idx] = av_frame_alloc();
  261. if (!data->aframe[idx]) {
  262. ffmpeg_log_error(LOG_WARNING, data,
  263. "Failed to allocate audio frame");
  264. return false;
  265. }
  266. data->aframe[idx]->format = context->sample_fmt;
  267. data->aframe[idx]->channels = context->channels;
  268. data->aframe[idx]->channel_layout = context->channel_layout;
  269. data->aframe[idx]->sample_rate = context->sample_rate;
  270. context->strict_std_compliance = -2;
  271. ret = avcodec_open2(context, data->acodec, NULL);
  272. if (ret < 0) {
  273. ffmpeg_log_error(LOG_WARNING, data,
  274. "Failed to open audio codec: %s",
  275. av_err2str(ret));
  276. return false;
  277. }
  278. data->frame_size = context->frame_size ? context->frame_size : 1024;
  279. ret = av_samples_alloc(data->samples[idx], NULL, context->channels,
  280. data->frame_size, context->sample_fmt, 0);
  281. if (ret < 0) {
  282. ffmpeg_log_error(LOG_WARNING, data,
  283. "Failed to create audio buffer: %s",
  284. av_err2str(ret));
  285. return false;
  286. }
  287. return true;
  288. }
  289. static bool create_audio_stream(struct ffmpeg_data *data, int idx)
  290. {
  291. AVCodecContext *context;
  292. AVStream *stream;
  293. struct obs_audio_info aoi;
  294. if (!obs_get_audio_info(&aoi)) {
  295. ffmpeg_log_error(LOG_WARNING, data, "No active audio");
  296. return false;
  297. }
  298. if (!new_stream(data, &stream, &data->acodec,
  299. data->output->oformat->audio_codec,
  300. data->config.audio_encoder))
  301. return false;
  302. data->audio_streams[idx] = stream;
  303. context = data->audio_streams[idx]->codec;
  304. context->bit_rate = data->config.audio_bitrate * 1000;
  305. context->time_base = (AVRational){1, aoi.samples_per_sec};
  306. context->channels = get_audio_channels(aoi.speakers);
  307. context->sample_rate = aoi.samples_per_sec;
  308. context->channel_layout =
  309. av_get_default_channel_layout(context->channels);
  310. //AVlib default channel layout for 5 channels is 5.0 ; fix for 4.1
  311. if (aoi.speakers == SPEAKERS_4POINT1)
  312. context->channel_layout = av_get_channel_layout("4.1");
  313. context->sample_fmt = data->acodec->sample_fmts
  314. ? data->acodec->sample_fmts[0]
  315. : AV_SAMPLE_FMT_FLTP;
  316. data->audio_streams[idx]->time_base = context->time_base;
  317. data->audio_samplerate = aoi.samples_per_sec;
  318. data->audio_format = convert_ffmpeg_sample_format(context->sample_fmt);
  319. data->audio_planes = get_audio_planes(data->audio_format, aoi.speakers);
  320. data->audio_size = get_audio_size(data->audio_format, aoi.speakers, 1);
  321. if (data->output->oformat->flags & AVFMT_GLOBALHEADER)
  322. context->flags |= CODEC_FLAG_GLOBAL_H;
  323. return open_audio_codec(data, idx);
  324. }
  325. static inline bool init_streams(struct ffmpeg_data *data)
  326. {
  327. AVOutputFormat *format = data->output->oformat;
  328. if (format->video_codec != AV_CODEC_ID_NONE)
  329. if (!create_video_stream(data))
  330. return false;
  331. if (format->audio_codec != AV_CODEC_ID_NONE &&
  332. data->num_audio_streams) {
  333. data->audio_streams =
  334. calloc(1, data->num_audio_streams * sizeof(void *));
  335. for (int i = 0; i < data->num_audio_streams; i++) {
  336. if (!create_audio_stream(data, i))
  337. return false;
  338. }
  339. }
  340. return true;
  341. }
  342. static inline bool open_output_file(struct ffmpeg_data *data)
  343. {
  344. AVOutputFormat *format = data->output->oformat;
  345. int ret;
  346. AVDictionary *dict = NULL;
  347. if ((ret = av_dict_parse_string(&dict, data->config.muxer_settings, "=",
  348. " ", 0))) {
  349. ffmpeg_log_error(LOG_WARNING, data,
  350. "Failed to parse muxer settings: %s\n%s",
  351. av_err2str(ret), data->config.muxer_settings);
  352. av_dict_free(&dict);
  353. return false;
  354. }
  355. if (av_dict_count(dict) > 0) {
  356. struct dstr str = {0};
  357. AVDictionaryEntry *entry = NULL;
  358. while ((entry = av_dict_get(dict, "", entry,
  359. AV_DICT_IGNORE_SUFFIX)))
  360. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  361. blog(LOG_INFO, "Using muxer settings: %s", str.array);
  362. dstr_free(&str);
  363. }
  364. if ((format->flags & AVFMT_NOFILE) == 0) {
  365. ret = avio_open2(&data->output->pb, data->config.url,
  366. AVIO_FLAG_WRITE, NULL, &dict);
  367. if (ret < 0) {
  368. ffmpeg_log_error(LOG_WARNING, data,
  369. "Couldn't open '%s', %s",
  370. data->config.url, av_err2str(ret));
  371. av_dict_free(&dict);
  372. return false;
  373. }
  374. }
  375. strncpy(data->output->filename, data->config.url,
  376. sizeof(data->output->filename));
  377. data->output->filename[sizeof(data->output->filename) - 1] = 0;
  378. ret = avformat_write_header(data->output, &dict);
  379. if (ret < 0) {
  380. ffmpeg_log_error(LOG_WARNING, data, "Error opening '%s': %s",
  381. data->config.url, av_err2str(ret));
  382. return false;
  383. }
  384. if (av_dict_count(dict) > 0) {
  385. struct dstr str = {0};
  386. AVDictionaryEntry *entry = NULL;
  387. while ((entry = av_dict_get(dict, "", entry,
  388. AV_DICT_IGNORE_SUFFIX)))
  389. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  390. blog(LOG_INFO, "Invalid muxer settings: %s", str.array);
  391. dstr_free(&str);
  392. }
  393. av_dict_free(&dict);
  394. return true;
  395. }
  396. static void close_video(struct ffmpeg_data *data)
  397. {
  398. avcodec_close(data->video->codec);
  399. av_frame_unref(data->vframe);
  400. // This format for some reason derefs video frame
  401. // too many times
  402. if (data->vcodec->id == AV_CODEC_ID_A64_MULTI ||
  403. data->vcodec->id == AV_CODEC_ID_A64_MULTI5)
  404. return;
  405. av_frame_free(&data->vframe);
  406. }
  407. static void close_audio(struct ffmpeg_data *data)
  408. {
  409. for (int idx = 0; idx < data->num_audio_streams; idx++) {
  410. for (size_t i = 0; i < MAX_AV_PLANES; i++)
  411. circlebuf_free(&data->excess_frames[idx][i]);
  412. if (data->samples[idx][0])
  413. av_freep(&data->samples[idx][0]);
  414. if (data->audio_streams[idx])
  415. avcodec_close(data->audio_streams[idx]->codec);
  416. if (data->aframe[idx])
  417. av_frame_free(&data->aframe[idx]);
  418. }
  419. }
  420. static void ffmpeg_data_free(struct ffmpeg_data *data)
  421. {
  422. if (data->initialized)
  423. av_write_trailer(data->output);
  424. if (data->video)
  425. close_video(data);
  426. if (data->audio_streams) {
  427. close_audio(data);
  428. free(data->audio_streams);
  429. data->audio_streams = NULL;
  430. }
  431. if (data->output) {
  432. if ((data->output->oformat->flags & AVFMT_NOFILE) == 0)
  433. avio_close(data->output->pb);
  434. avformat_free_context(data->output);
  435. }
  436. if (data->last_error)
  437. bfree(data->last_error);
  438. memset(data, 0, sizeof(struct ffmpeg_data));
  439. }
  440. static inline const char *safe_str(const char *s)
  441. {
  442. if (s == NULL)
  443. return "(NULL)";
  444. else
  445. return s;
  446. }
  447. static enum AVCodecID get_codec_id(const char *name, int id)
  448. {
  449. AVCodec *codec;
  450. if (id != 0)
  451. return (enum AVCodecID)id;
  452. if (!name || !*name)
  453. return AV_CODEC_ID_NONE;
  454. codec = avcodec_find_encoder_by_name(name);
  455. if (!codec)
  456. return AV_CODEC_ID_NONE;
  457. return codec->id;
  458. }
  459. static void set_encoder_ids(struct ffmpeg_data *data)
  460. {
  461. data->output->oformat->video_codec = get_codec_id(
  462. data->config.video_encoder, data->config.video_encoder_id);
  463. data->output->oformat->audio_codec = get_codec_id(
  464. data->config.audio_encoder, data->config.audio_encoder_id);
  465. }
  466. static bool ffmpeg_data_init(struct ffmpeg_data *data,
  467. struct ffmpeg_cfg *config)
  468. {
  469. bool is_rtmp = false;
  470. memset(data, 0, sizeof(struct ffmpeg_data));
  471. data->config = *config;
  472. data->num_audio_streams = config->audio_mix_count;
  473. data->audio_tracks = config->audio_tracks;
  474. if (!config->url || !*config->url)
  475. return false;
  476. av_register_all();
  477. avformat_network_init();
  478. is_rtmp = (astrcmpi_n(config->url, "rtmp://", 7) == 0);
  479. AVOutputFormat *output_format = av_guess_format(
  480. is_rtmp ? "flv" : data->config.format_name, data->config.url,
  481. is_rtmp ? NULL : data->config.format_mime_type);
  482. if (output_format == NULL) {
  483. ffmpeg_log_error(
  484. LOG_WARNING, data,
  485. "Couldn't find matching output format with "
  486. "parameters: name=%s, url=%s, mime=%s",
  487. safe_str(is_rtmp ? "flv" : data->config.format_name),
  488. safe_str(data->config.url),
  489. safe_str(is_rtmp ? NULL
  490. : data->config.format_mime_type));
  491. goto fail;
  492. }
  493. avformat_alloc_output_context2(&data->output, output_format, NULL,
  494. NULL);
  495. if (!data->output) {
  496. ffmpeg_log_error(LOG_WARNING, data,
  497. "Couldn't create avformat context");
  498. goto fail;
  499. }
  500. if (is_rtmp) {
  501. data->output->oformat->video_codec = AV_CODEC_ID_H264;
  502. data->output->oformat->audio_codec = AV_CODEC_ID_AAC;
  503. } else {
  504. if (data->config.format_name)
  505. set_encoder_ids(data);
  506. }
  507. if (!init_streams(data))
  508. goto fail;
  509. if (!open_output_file(data))
  510. goto fail;
  511. av_dump_format(data->output, 0, NULL, 1);
  512. data->initialized = true;
  513. return true;
  514. fail:
  515. blog(LOG_WARNING, "ffmpeg_data_init failed");
  516. return false;
  517. }
  518. /* ------------------------------------------------------------------------- */
  519. static inline bool stopping(struct ffmpeg_output *output)
  520. {
  521. return os_atomic_load_bool(&output->stopping);
  522. }
  523. static const char *ffmpeg_output_getname(void *unused)
  524. {
  525. UNUSED_PARAMETER(unused);
  526. return obs_module_text("FFmpegOutput");
  527. }
  528. static void ffmpeg_log_callback(void *param, int level, const char *format,
  529. va_list args)
  530. {
  531. if (level <= AV_LOG_INFO)
  532. blogva(LOG_DEBUG, format, args);
  533. UNUSED_PARAMETER(param);
  534. }
  535. static void *ffmpeg_output_create(obs_data_t *settings, obs_output_t *output)
  536. {
  537. struct ffmpeg_output *data = bzalloc(sizeof(struct ffmpeg_output));
  538. pthread_mutex_init_value(&data->write_mutex);
  539. data->output = output;
  540. if (pthread_mutex_init(&data->write_mutex, NULL) != 0)
  541. goto fail;
  542. if (os_event_init(&data->stop_event, OS_EVENT_TYPE_AUTO) != 0)
  543. goto fail;
  544. if (os_sem_init(&data->write_sem, 0) != 0)
  545. goto fail;
  546. av_log_set_callback(ffmpeg_log_callback);
  547. UNUSED_PARAMETER(settings);
  548. return data;
  549. fail:
  550. pthread_mutex_destroy(&data->write_mutex);
  551. os_event_destroy(data->stop_event);
  552. bfree(data);
  553. return NULL;
  554. }
  555. static void ffmpeg_output_full_stop(void *data);
  556. static void ffmpeg_deactivate(struct ffmpeg_output *output);
  557. static void ffmpeg_output_destroy(void *data)
  558. {
  559. struct ffmpeg_output *output = data;
  560. if (output) {
  561. if (output->connecting)
  562. pthread_join(output->start_thread, NULL);
  563. ffmpeg_output_full_stop(output);
  564. pthread_mutex_destroy(&output->write_mutex);
  565. os_sem_destroy(output->write_sem);
  566. os_event_destroy(output->stop_event);
  567. bfree(data);
  568. }
  569. }
  570. static inline void copy_data(AVFrame *pic, const struct video_data *frame,
  571. int height, enum AVPixelFormat format)
  572. {
  573. int h_chroma_shift, v_chroma_shift;
  574. av_pix_fmt_get_chroma_sub_sample(format, &h_chroma_shift,
  575. &v_chroma_shift);
  576. for (int plane = 0; plane < MAX_AV_PLANES; plane++) {
  577. if (!frame->data[plane])
  578. continue;
  579. int frame_rowsize = (int)frame->linesize[plane];
  580. int pic_rowsize = pic->linesize[plane];
  581. int bytes = frame_rowsize < pic_rowsize ? frame_rowsize
  582. : pic_rowsize;
  583. int plane_height = height >> (plane ? v_chroma_shift : 0);
  584. for (int y = 0; y < plane_height; y++) {
  585. int pos_frame = y * frame_rowsize;
  586. int pos_pic = y * pic_rowsize;
  587. memcpy(pic->data[plane] + pos_pic,
  588. frame->data[plane] + pos_frame, bytes);
  589. }
  590. }
  591. }
  592. static void receive_video(void *param, struct video_data *frame)
  593. {
  594. struct ffmpeg_output *output = param;
  595. struct ffmpeg_data *data = &output->ff_data;
  596. // codec doesn't support video or none configured
  597. if (!data->video)
  598. return;
  599. AVCodecContext *context = data->video->codec;
  600. AVPacket packet = {0};
  601. int ret = 0, got_packet;
  602. av_init_packet(&packet);
  603. if (!output->video_start_ts)
  604. output->video_start_ts = frame->timestamp;
  605. if (!data->start_timestamp)
  606. data->start_timestamp = frame->timestamp;
  607. if (!!data->swscale)
  608. sws_scale(data->swscale, (const uint8_t *const *)frame->data,
  609. (const int *)frame->linesize, 0, data->config.height,
  610. data->vframe->data, data->vframe->linesize);
  611. else
  612. copy_data(data->vframe, frame, context->height,
  613. context->pix_fmt);
  614. #if LIBAVFORMAT_VERSION_MAJOR < 58
  615. if (data->output->flags & AVFMT_RAWPICTURE) {
  616. packet.flags |= AV_PKT_FLAG_KEY;
  617. packet.stream_index = data->video->index;
  618. packet.data = data->vframe->data[0];
  619. packet.size = sizeof(AVPicture);
  620. pthread_mutex_lock(&output->write_mutex);
  621. da_push_back(output->packets, &packet);
  622. pthread_mutex_unlock(&output->write_mutex);
  623. os_sem_post(output->write_sem);
  624. } else {
  625. #endif
  626. data->vframe->pts = data->total_frames;
  627. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
  628. ret = avcodec_send_frame(context, data->vframe);
  629. if (ret == 0)
  630. ret = avcodec_receive_packet(context, &packet);
  631. got_packet = (ret == 0);
  632. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  633. ret = 0;
  634. #else
  635. ret = avcodec_encode_video2(context, &packet, data->vframe,
  636. &got_packet);
  637. #endif
  638. if (ret < 0) {
  639. blog(LOG_WARNING,
  640. "receive_video: Error encoding "
  641. "video: %s",
  642. av_err2str(ret));
  643. //FIXME: stop the encode with an error
  644. return;
  645. }
  646. if (!ret && got_packet && packet.size) {
  647. packet.pts = rescale_ts(packet.pts, context,
  648. data->video->time_base);
  649. packet.dts = rescale_ts(packet.dts, context,
  650. data->video->time_base);
  651. packet.duration = (int)av_rescale_q(
  652. packet.duration, context->time_base,
  653. data->video->time_base);
  654. pthread_mutex_lock(&output->write_mutex);
  655. da_push_back(output->packets, &packet);
  656. pthread_mutex_unlock(&output->write_mutex);
  657. os_sem_post(output->write_sem);
  658. } else {
  659. ret = 0;
  660. }
  661. #if LIBAVFORMAT_VERSION_MAJOR < 58
  662. }
  663. #endif
  664. if (ret != 0) {
  665. blog(LOG_WARNING, "receive_video: Error writing video: %s",
  666. av_err2str(ret));
  667. //FIXME: stop the encode with an error
  668. }
  669. data->total_frames++;
  670. }
  671. static void encode_audio(struct ffmpeg_output *output, int idx,
  672. struct AVCodecContext *context, size_t block_size)
  673. {
  674. struct ffmpeg_data *data = &output->ff_data;
  675. AVPacket packet = {0};
  676. int ret, got_packet;
  677. size_t total_size = data->frame_size * block_size * context->channels;
  678. data->aframe[idx]->nb_samples = data->frame_size;
  679. data->aframe[idx]->pts = av_rescale_q(
  680. data->total_samples[idx], (AVRational){1, context->sample_rate},
  681. context->time_base);
  682. ret = avcodec_fill_audio_frame(data->aframe[idx], context->channels,
  683. context->sample_fmt,
  684. data->samples[idx][0], (int)total_size,
  685. 1);
  686. if (ret < 0) {
  687. blog(LOG_WARNING,
  688. "encode_audio: avcodec_fill_audio_frame "
  689. "failed: %s",
  690. av_err2str(ret));
  691. //FIXME: stop the encode with an error
  692. return;
  693. }
  694. data->total_samples[idx] += data->frame_size;
  695. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
  696. ret = avcodec_send_frame(context, data->aframe[idx]);
  697. if (ret == 0)
  698. ret = avcodec_receive_packet(context, &packet);
  699. got_packet = (ret == 0);
  700. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  701. ret = 0;
  702. #else
  703. ret = avcodec_encode_audio2(context, &packet, data->aframe[idx],
  704. &got_packet);
  705. #endif
  706. if (ret < 0) {
  707. blog(LOG_WARNING, "encode_audio: Error encoding audio: %s",
  708. av_err2str(ret));
  709. //FIXME: stop the encode with an error
  710. return;
  711. }
  712. if (!got_packet)
  713. return;
  714. packet.pts = rescale_ts(packet.pts, context,
  715. data->audio_streams[idx]->time_base);
  716. packet.dts = rescale_ts(packet.dts, context,
  717. data->audio_streams[idx]->time_base);
  718. packet.duration =
  719. (int)av_rescale_q(packet.duration, context->time_base,
  720. data->audio_streams[idx]->time_base);
  721. packet.stream_index = data->audio_streams[idx]->index;
  722. pthread_mutex_lock(&output->write_mutex);
  723. da_push_back(output->packets, &packet);
  724. pthread_mutex_unlock(&output->write_mutex);
  725. os_sem_post(output->write_sem);
  726. }
  727. /* Given a bitmask for the selected tracks and the mix index,
  728. * this returns the stream index which will be passed to the muxer. */
  729. static int get_track_order(int track_config, size_t mix_index)
  730. {
  731. int position = 0;
  732. for (size_t i = 0; i < mix_index; i++) {
  733. if (track_config & 1 << i)
  734. position++;
  735. }
  736. return position;
  737. }
  738. static void receive_audio(void *param, size_t mix_idx, struct audio_data *frame)
  739. {
  740. struct ffmpeg_output *output = param;
  741. struct ffmpeg_data *data = &output->ff_data;
  742. size_t frame_size_bytes;
  743. struct audio_data in = *frame;
  744. int track_order;
  745. // codec doesn't support audio or none configured
  746. if (!data->audio_streams)
  747. return;
  748. /* check that the track was selected */
  749. if ((data->audio_tracks & (1 << mix_idx)) == 0)
  750. return;
  751. /* get track order (first selected, etc ...) */
  752. track_order = get_track_order(data->audio_tracks, mix_idx);
  753. AVCodecContext *context = data->audio_streams[track_order]->codec;
  754. if (!data->start_timestamp)
  755. return;
  756. if (!output->audio_start_ts)
  757. output->audio_start_ts = in.timestamp;
  758. frame_size_bytes = (size_t)data->frame_size * data->audio_size;
  759. for (size_t i = 0; i < data->audio_planes; i++)
  760. circlebuf_push_back(&data->excess_frames[track_order][i],
  761. in.data[i], in.frames * data->audio_size);
  762. while (data->excess_frames[track_order][0].size >= frame_size_bytes) {
  763. for (size_t i = 0; i < data->audio_planes; i++)
  764. circlebuf_pop_front(
  765. &data->excess_frames[track_order][i],
  766. data->samples[track_order][i],
  767. frame_size_bytes);
  768. encode_audio(output, track_order, context, data->audio_size);
  769. }
  770. }
  771. static uint64_t get_packet_sys_dts(struct ffmpeg_output *output,
  772. AVPacket *packet)
  773. {
  774. struct ffmpeg_data *data = &output->ff_data;
  775. uint64_t pause_offset = obs_output_get_pause_offset(output->output);
  776. uint64_t start_ts;
  777. AVRational time_base;
  778. if (data->video && data->video->index == packet->stream_index) {
  779. time_base = data->video->time_base;
  780. start_ts = output->video_start_ts;
  781. } else {
  782. time_base = data->audio_streams[0]->time_base;
  783. start_ts = output->audio_start_ts;
  784. }
  785. return start_ts + pause_offset +
  786. (uint64_t)av_rescale_q(packet->dts, time_base,
  787. (AVRational){1, 1000000000});
  788. }
  789. static int process_packet(struct ffmpeg_output *output)
  790. {
  791. AVPacket packet;
  792. bool new_packet = false;
  793. int ret;
  794. pthread_mutex_lock(&output->write_mutex);
  795. if (output->packets.num) {
  796. packet = output->packets.array[0];
  797. da_erase(output->packets, 0);
  798. new_packet = true;
  799. }
  800. pthread_mutex_unlock(&output->write_mutex);
  801. if (!new_packet)
  802. return 0;
  803. /*blog(LOG_DEBUG, "size = %d, flags = %lX, stream = %d, "
  804. "packets queued: %lu",
  805. packet.size, packet.flags,
  806. packet.stream_index, output->packets.num);*/
  807. if (stopping(output)) {
  808. uint64_t sys_ts = get_packet_sys_dts(output, &packet);
  809. if (sys_ts >= output->stop_ts) {
  810. ffmpeg_output_full_stop(output);
  811. return 0;
  812. }
  813. }
  814. output->total_bytes += packet.size;
  815. ret = av_interleaved_write_frame(output->ff_data.output, &packet);
  816. if (ret < 0) {
  817. av_free_packet(&packet);
  818. ffmpeg_log_error(LOG_WARNING, &output->ff_data,
  819. "receive_audio: Error writing packet: %s",
  820. av_err2str(ret));
  821. return ret;
  822. }
  823. return 0;
  824. }
  825. static void *write_thread(void *data)
  826. {
  827. struct ffmpeg_output *output = data;
  828. while (os_sem_wait(output->write_sem) == 0) {
  829. /* check to see if shutting down */
  830. if (os_event_try(output->stop_event) == 0)
  831. break;
  832. int ret = process_packet(output);
  833. if (ret != 0) {
  834. int code = OBS_OUTPUT_ERROR;
  835. pthread_detach(output->write_thread);
  836. output->write_thread_active = false;
  837. if (ret == -ENOSPC)
  838. code = OBS_OUTPUT_NO_SPACE;
  839. obs_output_signal_stop(output->output, code);
  840. ffmpeg_deactivate(output);
  841. break;
  842. }
  843. }
  844. output->active = false;
  845. return NULL;
  846. }
  847. static inline const char *get_string_or_null(obs_data_t *settings,
  848. const char *name)
  849. {
  850. const char *value = obs_data_get_string(settings, name);
  851. if (!value || !strlen(value))
  852. return NULL;
  853. return value;
  854. }
  855. static int get_audio_mix_count(int audio_mix_mask)
  856. {
  857. int mix_count = 0;
  858. for (int i = 0; i < MAX_AUDIO_MIXES; i++) {
  859. if ((audio_mix_mask & (1 << i)) != 0) {
  860. mix_count++;
  861. }
  862. }
  863. return mix_count;
  864. }
  865. static bool try_connect(struct ffmpeg_output *output)
  866. {
  867. video_t *video = obs_output_video(output->output);
  868. const struct video_output_info *voi = video_output_get_info(video);
  869. struct ffmpeg_cfg config;
  870. obs_data_t *settings;
  871. bool success;
  872. int ret;
  873. settings = obs_output_get_settings(output->output);
  874. obs_data_set_default_int(settings, "gop_size", 120);
  875. config.url = obs_data_get_string(settings, "url");
  876. config.format_name = get_string_or_null(settings, "format_name");
  877. config.format_mime_type =
  878. get_string_or_null(settings, "format_mime_type");
  879. config.muxer_settings = obs_data_get_string(settings, "muxer_settings");
  880. config.video_bitrate = (int)obs_data_get_int(settings, "video_bitrate");
  881. config.audio_bitrate = (int)obs_data_get_int(settings, "audio_bitrate");
  882. config.gop_size = (int)obs_data_get_int(settings, "gop_size");
  883. config.video_encoder = get_string_or_null(settings, "video_encoder");
  884. config.video_encoder_id =
  885. (int)obs_data_get_int(settings, "video_encoder_id");
  886. config.audio_encoder = get_string_or_null(settings, "audio_encoder");
  887. config.audio_encoder_id =
  888. (int)obs_data_get_int(settings, "audio_encoder_id");
  889. config.video_settings = obs_data_get_string(settings, "video_settings");
  890. config.audio_settings = obs_data_get_string(settings, "audio_settings");
  891. config.scale_width = (int)obs_data_get_int(settings, "scale_width");
  892. config.scale_height = (int)obs_data_get_int(settings, "scale_height");
  893. config.width = (int)obs_output_get_width(output->output);
  894. config.height = (int)obs_output_get_height(output->output);
  895. config.format =
  896. obs_to_ffmpeg_video_format(video_output_get_format(video));
  897. config.audio_tracks = (int)obs_output_get_mixers(output->output);
  898. config.audio_mix_count = get_audio_mix_count(config.audio_tracks);
  899. if (format_is_yuv(voi->format)) {
  900. config.color_range = voi->range == VIDEO_RANGE_FULL
  901. ? AVCOL_RANGE_JPEG
  902. : AVCOL_RANGE_MPEG;
  903. config.color_space = voi->colorspace == VIDEO_CS_709
  904. ? AVCOL_SPC_BT709
  905. : AVCOL_SPC_BT470BG;
  906. } else {
  907. config.color_range = AVCOL_RANGE_UNSPECIFIED;
  908. config.color_space = AVCOL_SPC_RGB;
  909. }
  910. if (config.format == AV_PIX_FMT_NONE) {
  911. blog(LOG_DEBUG, "invalid pixel format used for FFmpeg output");
  912. return false;
  913. }
  914. if (!config.scale_width)
  915. config.scale_width = config.width;
  916. if (!config.scale_height)
  917. config.scale_height = config.height;
  918. success = ffmpeg_data_init(&output->ff_data, &config);
  919. obs_data_release(settings);
  920. if (!success) {
  921. if (output->ff_data.last_error) {
  922. obs_output_set_last_error(output->output,
  923. output->ff_data.last_error);
  924. }
  925. ffmpeg_data_free(&output->ff_data);
  926. return false;
  927. }
  928. struct audio_convert_info aci = {.format =
  929. output->ff_data.audio_format};
  930. output->active = true;
  931. if (!obs_output_can_begin_data_capture(output->output, 0))
  932. return false;
  933. ret = pthread_create(&output->write_thread, NULL, write_thread, output);
  934. if (ret != 0) {
  935. ffmpeg_log_error(LOG_WARNING, &output->ff_data,
  936. "ffmpeg_output_start: failed to create write "
  937. "thread.");
  938. ffmpeg_output_full_stop(output);
  939. return false;
  940. }
  941. obs_output_set_video_conversion(output->output, NULL);
  942. obs_output_set_audio_conversion(output->output, &aci);
  943. obs_output_begin_data_capture(output->output, 0);
  944. output->write_thread_active = true;
  945. return true;
  946. }
  947. static void *start_thread(void *data)
  948. {
  949. struct ffmpeg_output *output = data;
  950. if (!try_connect(output))
  951. obs_output_signal_stop(output->output,
  952. OBS_OUTPUT_CONNECT_FAILED);
  953. output->connecting = false;
  954. return NULL;
  955. }
  956. static bool ffmpeg_output_start(void *data)
  957. {
  958. struct ffmpeg_output *output = data;
  959. int ret;
  960. if (output->connecting)
  961. return false;
  962. os_atomic_set_bool(&output->stopping, false);
  963. output->audio_start_ts = 0;
  964. output->video_start_ts = 0;
  965. output->total_bytes = 0;
  966. ret = pthread_create(&output->start_thread, NULL, start_thread, output);
  967. return (output->connecting = (ret == 0));
  968. }
  969. static void ffmpeg_output_full_stop(void *data)
  970. {
  971. struct ffmpeg_output *output = data;
  972. if (output->active) {
  973. obs_output_end_data_capture(output->output);
  974. ffmpeg_deactivate(output);
  975. }
  976. }
  977. static void ffmpeg_output_stop(void *data, uint64_t ts)
  978. {
  979. struct ffmpeg_output *output = data;
  980. if (output->active) {
  981. if (ts == 0) {
  982. ffmpeg_output_full_stop(output);
  983. } else {
  984. os_atomic_set_bool(&output->stopping, true);
  985. output->stop_ts = ts;
  986. }
  987. }
  988. }
  989. static void ffmpeg_deactivate(struct ffmpeg_output *output)
  990. {
  991. if (output->write_thread_active) {
  992. os_event_signal(output->stop_event);
  993. os_sem_post(output->write_sem);
  994. pthread_join(output->write_thread, NULL);
  995. output->write_thread_active = false;
  996. }
  997. pthread_mutex_lock(&output->write_mutex);
  998. for (size_t i = 0; i < output->packets.num; i++)
  999. av_free_packet(output->packets.array + i);
  1000. da_free(output->packets);
  1001. pthread_mutex_unlock(&output->write_mutex);
  1002. ffmpeg_data_free(&output->ff_data);
  1003. }
  1004. static uint64_t ffmpeg_output_total_bytes(void *data)
  1005. {
  1006. struct ffmpeg_output *output = data;
  1007. return output->total_bytes;
  1008. }
  1009. struct obs_output_info ffmpeg_output = {
  1010. .id = "ffmpeg_output",
  1011. .flags = OBS_OUTPUT_AUDIO | OBS_OUTPUT_VIDEO | OBS_OUTPUT_MULTI_TRACK |
  1012. OBS_OUTPUT_CAN_PAUSE,
  1013. .get_name = ffmpeg_output_getname,
  1014. .create = ffmpeg_output_create,
  1015. .destroy = ffmpeg_output_destroy,
  1016. .start = ffmpeg_output_start,
  1017. .stop = ffmpeg_output_stop,
  1018. .raw_video = receive_video,
  1019. .raw_audio2 = receive_audio,
  1020. .get_total_bytes = ffmpeg_output_total_bytes,
  1021. };