obs-ffmpeg-mpegts.c 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain 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 "obs-ffmpeg-output.h"
  21. #include "obs-ffmpeg-formats.h"
  22. #include "obs-ffmpeg-compat.h"
  23. #include "obs-ffmpeg-rist.h"
  24. #include "obs-ffmpeg-srt.h"
  25. #include <libavutil/channel_layout.h>
  26. #include <libavutil/mastering_display_metadata.h>
  27. /* ------------------------------------------------------------------------- */
  28. #define do_log(level, format, ...) \
  29. blog(level, "[obs-ffmpeg mpegts muxer: '%s']: " format, \
  30. obs_output_get_name(stream->output), ##__VA_ARGS__)
  31. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  32. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  33. #define error(format, ...) do_log(LOG_ERROR, format, ##__VA_ARGS__)
  34. static void ffmpeg_mpegts_set_last_error(struct ffmpeg_data *data,
  35. const char *error)
  36. {
  37. if (data->last_error)
  38. bfree(data->last_error);
  39. data->last_error = bstrdup(error);
  40. }
  41. void ffmpeg_mpegts_log_error(int log_level, struct ffmpeg_data *data,
  42. const char *format, ...)
  43. {
  44. va_list args;
  45. char out[4096];
  46. va_start(args, format);
  47. vsnprintf(out, sizeof(out), format, args);
  48. va_end(args);
  49. ffmpeg_mpegts_set_last_error(data, out);
  50. blog(log_level, "%s", out);
  51. }
  52. static bool is_rist(struct ffmpeg_output *stream)
  53. {
  54. return !strncmp(stream->ff_data.config.url, RIST_PROTO,
  55. sizeof(RIST_PROTO) - 1);
  56. }
  57. static bool is_srt(struct ffmpeg_output *stream)
  58. {
  59. return !strncmp(stream->ff_data.config.url, SRT_PROTO,
  60. sizeof(SRT_PROTO) - 1);
  61. }
  62. static bool proto_is_allowed(struct ffmpeg_output *stream)
  63. {
  64. return !strncmp(stream->ff_data.config.url, UDP_PROTO,
  65. sizeof(UDP_PROTO) - 1) ||
  66. !strncmp(stream->ff_data.config.url, TCP_PROTO,
  67. sizeof(TCP_PROTO) - 1) ||
  68. !strncmp(stream->ff_data.config.url, HTTP_PROTO,
  69. sizeof(HTTP_PROTO) - 1);
  70. }
  71. static bool new_stream(struct ffmpeg_data *data, AVStream **stream,
  72. const char *name)
  73. {
  74. *stream = avformat_new_stream(data->output, NULL);
  75. if (!*stream) {
  76. ffmpeg_mpegts_log_error(
  77. LOG_WARNING, data,
  78. "Couldn't create stream for encoder '%s'", name);
  79. return false;
  80. }
  81. (*stream)->id = data->output->nb_streams - 1;
  82. return true;
  83. }
  84. static bool get_audio_headers(struct ffmpeg_output *stream,
  85. struct ffmpeg_data *data, int idx)
  86. {
  87. AVCodecParameters *par = data->audio_infos[idx].stream->codecpar;
  88. obs_encoder_t *aencoder =
  89. obs_output_get_audio_encoder(stream->output, idx);
  90. struct encoder_packet packet = {
  91. .type = OBS_ENCODER_AUDIO, .timebase_den = 1, .track_idx = idx};
  92. if (obs_encoder_get_extra_data(aencoder, &packet.data, &packet.size)) {
  93. par->extradata = av_memdup(packet.data, packet.size);
  94. par->extradata_size = (int)packet.size;
  95. avcodec_parameters_to_context(data->audio_infos[idx].ctx, par);
  96. return 1;
  97. }
  98. return 0;
  99. }
  100. static bool get_video_headers(struct ffmpeg_output *stream,
  101. struct ffmpeg_data *data)
  102. {
  103. AVCodecParameters *par = data->video->codecpar;
  104. obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output);
  105. struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO,
  106. .timebase_den = 1};
  107. if (obs_encoder_get_extra_data(vencoder, &packet.data, &packet.size)) {
  108. par->extradata = av_memdup(packet.data, packet.size);
  109. par->extradata_size = (int)packet.size;
  110. avcodec_parameters_to_context(data->video_ctx,
  111. data->video->codecpar);
  112. return 1;
  113. }
  114. return 0;
  115. }
  116. static bool create_video_stream(struct ffmpeg_output *stream,
  117. struct ffmpeg_data *data)
  118. {
  119. AVCodecContext *context;
  120. struct obs_video_info ovi;
  121. if (!obs_get_video_info(&ovi)) {
  122. ffmpeg_mpegts_log_error(LOG_WARNING, data, "No active video");
  123. return false;
  124. }
  125. const char *name = data->config.video_encoder;
  126. const AVCodecDescriptor *codec = avcodec_descriptor_get_by_name(name);
  127. if (!codec) {
  128. error("Couldn't find codec '%s'", name);
  129. return false;
  130. }
  131. if (!new_stream(data, &data->video, name))
  132. return false;
  133. const bool pq = data->config.color_trc == AVCOL_TRC_SMPTE2084;
  134. const bool hlg = data->config.color_trc == AVCOL_TRC_ARIB_STD_B67;
  135. if (pq || hlg) {
  136. const int hdr_nominal_peak_level =
  137. pq ? (int)obs_get_video_hdr_nominal_peak_level()
  138. : (hlg ? 1000 : 0);
  139. size_t content_size;
  140. AVContentLightMetadata *const content =
  141. av_content_light_metadata_alloc(&content_size);
  142. content->MaxCLL = hdr_nominal_peak_level;
  143. content->MaxFALL = hdr_nominal_peak_level;
  144. av_stream_add_side_data(data->video,
  145. AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
  146. (uint8_t *)content, content_size);
  147. AVMasteringDisplayMetadata *const mastering =
  148. av_mastering_display_metadata_alloc();
  149. mastering->display_primaries[0][0] = av_make_q(17, 25);
  150. mastering->display_primaries[0][1] = av_make_q(8, 25);
  151. mastering->display_primaries[1][0] = av_make_q(53, 200);
  152. mastering->display_primaries[1][1] = av_make_q(69, 100);
  153. mastering->display_primaries[2][0] = av_make_q(3, 20);
  154. mastering->display_primaries[2][1] = av_make_q(3, 50);
  155. mastering->white_point[0] = av_make_q(3127, 10000);
  156. mastering->white_point[1] = av_make_q(329, 1000);
  157. mastering->min_luminance = av_make_q(0, 1);
  158. mastering->max_luminance = av_make_q(hdr_nominal_peak_level, 1);
  159. mastering->has_primaries = 1;
  160. mastering->has_luminance = 1;
  161. av_stream_add_side_data(data->video,
  162. AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
  163. (uint8_t *)mastering,
  164. sizeof(*mastering));
  165. }
  166. context = avcodec_alloc_context3(NULL);
  167. context->codec_type = codec->type;
  168. context->codec_id = codec->id;
  169. context->bit_rate = (int64_t)data->config.video_bitrate * 1000;
  170. context->width = data->config.scale_width;
  171. context->height = data->config.scale_height;
  172. context->coded_width = data->config.scale_width;
  173. context->coded_height = data->config.scale_height;
  174. context->time_base = (AVRational){ovi.fps_den, ovi.fps_num};
  175. context->gop_size = data->config.gop_size;
  176. context->pix_fmt = data->config.format;
  177. context->color_range = data->config.color_range;
  178. context->color_primaries = data->config.color_primaries;
  179. context->color_trc = data->config.color_trc;
  180. context->colorspace = data->config.colorspace;
  181. context->chroma_sample_location = determine_chroma_location(
  182. data->config.format, data->config.colorspace);
  183. context->thread_count = 0;
  184. data->video->time_base = context->time_base;
  185. #if LIBAVFORMAT_VERSION_MAJOR < 59
  186. data->video->codec->time_base = context->time_base;
  187. #endif
  188. data->video->avg_frame_rate = av_inv_q(context->time_base);
  189. data->video_ctx = context;
  190. data->config.width = data->config.scale_width;
  191. data->config.height = data->config.scale_height;
  192. avcodec_parameters_from_context(data->video->codecpar, context);
  193. return true;
  194. }
  195. static bool create_audio_stream(struct ffmpeg_output *stream,
  196. struct ffmpeg_data *data, int idx)
  197. {
  198. AVCodecContext *context;
  199. AVStream *avstream;
  200. struct obs_audio_info aoi;
  201. const char *name = data->config.audio_encoder;
  202. int channels;
  203. const AVCodecDescriptor *codec = avcodec_descriptor_get_by_name(name);
  204. if (!codec) {
  205. warn("Couldn't find codec '%s'", name);
  206. return false;
  207. }
  208. if (!obs_get_audio_info(&aoi)) {
  209. ffmpeg_mpegts_log_error(LOG_WARNING, data, "No active audio");
  210. return false;
  211. }
  212. if (!new_stream(data, &avstream, data->config.audio_encoder))
  213. return false;
  214. context = avcodec_alloc_context3(NULL);
  215. context->codec_type = codec->type;
  216. context->codec_id = codec->id;
  217. context->bit_rate = (int64_t)data->config.audio_bitrate * 1000;
  218. context->time_base = (AVRational){1, aoi.samples_per_sec};
  219. channels = get_audio_channels(aoi.speakers);
  220. #if LIBAVUTIL_VERSION_INT < AV_VERSION_INT(57, 24, 100)
  221. context->channels = get_audio_channels(aoi.speakers);
  222. #endif
  223. context->sample_rate = aoi.samples_per_sec;
  224. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(59, 24, 100)
  225. context->channel_layout =
  226. av_get_default_channel_layout(context->channels);
  227. //avutil default channel layout for 5 channels is 5.0 ; fix for 4.1
  228. if (aoi.speakers == SPEAKERS_4POINT1)
  229. context->channel_layout = av_get_channel_layout("4.1");
  230. #else
  231. av_channel_layout_default(&context->ch_layout, channels);
  232. if (aoi.speakers == SPEAKERS_4POINT1)
  233. context->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1;
  234. #endif
  235. context->sample_fmt = AV_SAMPLE_FMT_S16;
  236. context->frame_size = data->config.frame_size;
  237. avstream->time_base = context->time_base;
  238. data->audio_samplerate = aoi.samples_per_sec;
  239. data->audio_format = convert_ffmpeg_sample_format(context->sample_fmt);
  240. data->audio_planes = get_audio_planes(data->audio_format, aoi.speakers);
  241. data->audio_size = get_audio_size(data->audio_format, aoi.speakers, 1);
  242. data->audio_infos[idx].stream = avstream;
  243. data->audio_infos[idx].ctx = context;
  244. avcodec_parameters_from_context(data->audio_infos[idx].stream->codecpar,
  245. context);
  246. return true;
  247. }
  248. static inline bool init_streams(struct ffmpeg_output *stream,
  249. struct ffmpeg_data *data)
  250. {
  251. if (!create_video_stream(stream, data))
  252. return false;
  253. if (data->num_audio_streams) {
  254. data->audio_infos = calloc(data->num_audio_streams,
  255. sizeof(*data->audio_infos));
  256. for (int i = 0; i < data->num_audio_streams; i++) {
  257. if (!create_audio_stream(stream, data, i))
  258. return false;
  259. }
  260. }
  261. return true;
  262. }
  263. int ff_network_init(void)
  264. {
  265. #if HAVE_WINSOCK2_H
  266. WSADATA wsaData;
  267. if (WSAStartup(MAKEWORD(1, 1), &wsaData))
  268. return 0;
  269. #endif
  270. return 1;
  271. }
  272. static inline int connect_mpegts_url(struct ffmpeg_output *stream, bool is_rist)
  273. {
  274. int err = 0;
  275. const char *url = stream->ff_data.config.url;
  276. if (!ff_network_init()) {
  277. ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data,
  278. "Couldn't initialize network");
  279. return AVERROR(EIO);
  280. }
  281. URLContext *uc = av_mallocz(sizeof(URLContext) + strlen(url) + 1);
  282. if (!uc) {
  283. ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data,
  284. "Couldn't allocate memory");
  285. goto fail;
  286. }
  287. uc->url = (char *)url;
  288. uc->max_packet_size = is_rist ? RIST_MAX_PAYLOAD_SIZE
  289. : SRT_LIVE_DEFAULT_PAYLOAD_SIZE;
  290. uc->priv_data = is_rist ? av_mallocz(sizeof(RISTContext))
  291. : av_mallocz(sizeof(SRTContext));
  292. if (!uc->priv_data) {
  293. ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data,
  294. "Couldn't allocate memory");
  295. goto fail;
  296. }
  297. /* For SRT, pass streamid & passphrase; for RIST, pass passphrase, username
  298. * & password.
  299. */
  300. if (!is_rist) {
  301. SRTContext *context = (SRTContext *)uc->priv_data;
  302. context->streamid = NULL;
  303. if (stream->ff_data.config.stream_id != NULL) {
  304. if (strlen(stream->ff_data.config.stream_id))
  305. context->streamid = av_strdup(
  306. stream->ff_data.config.stream_id);
  307. }
  308. context->passphrase = NULL;
  309. if (stream->ff_data.config.encrypt_passphrase != NULL) {
  310. if (strlen(stream->ff_data.config.encrypt_passphrase))
  311. context->passphrase =
  312. av_strdup(stream->ff_data.config
  313. .encrypt_passphrase);
  314. }
  315. } else {
  316. RISTContext *context = (RISTContext *)uc->priv_data;
  317. context->secret = NULL;
  318. if (stream->ff_data.config.encrypt_passphrase != NULL) {
  319. if (strlen(stream->ff_data.config.encrypt_passphrase))
  320. context->secret =
  321. bstrdup(stream->ff_data.config
  322. .encrypt_passphrase);
  323. }
  324. context->username = NULL;
  325. if (stream->ff_data.config.username != NULL) {
  326. if (strlen(stream->ff_data.config.username))
  327. context->username = bstrdup(
  328. stream->ff_data.config.username);
  329. }
  330. context->password = NULL;
  331. if (stream->ff_data.config.password != NULL) {
  332. if (strlen(stream->ff_data.config.password))
  333. context->password = bstrdup(
  334. stream->ff_data.config.password);
  335. }
  336. }
  337. stream->h = uc;
  338. if (is_rist)
  339. err = librist_open(uc, uc->url);
  340. else
  341. err = libsrt_open(uc, uc->url);
  342. if (err < 0)
  343. goto fail;
  344. return 0;
  345. fail:
  346. if (uc)
  347. av_freep(&uc->priv_data);
  348. av_freep(&uc);
  349. #if HAVE_WINSOCK2_H
  350. WSACleanup();
  351. #endif
  352. return err;
  353. }
  354. static inline int allocate_custom_aviocontext(struct ffmpeg_output *stream,
  355. bool is_rist)
  356. {
  357. /* allocate buffers */
  358. uint8_t *buffer = NULL;
  359. int buffer_size;
  360. URLContext *h = stream->h;
  361. AVIOContext *s = NULL;
  362. buffer_size = UDP_DEFAULT_PAYLOAD_SIZE;
  363. buffer = av_malloc(buffer_size);
  364. if (!buffer)
  365. return AVERROR(ENOMEM);
  366. /* allocate custom avio_context */
  367. if (is_rist)
  368. s = avio_alloc_context(
  369. buffer, buffer_size, AVIO_FLAG_WRITE, h, NULL,
  370. (int (*)(void *, uint8_t *, int))librist_write, NULL);
  371. else
  372. s = avio_alloc_context(
  373. buffer, buffer_size, AVIO_FLAG_WRITE, h, NULL,
  374. (int (*)(void *, uint8_t *, int))libsrt_write, NULL);
  375. if (!s)
  376. goto fail;
  377. s->max_packet_size = h->max_packet_size;
  378. s->opaque = h;
  379. stream->s = s;
  380. stream->ff_data.output->pb = s;
  381. return 0;
  382. fail:
  383. av_freep(&buffer);
  384. return AVERROR(ENOMEM);
  385. }
  386. static inline int open_output_file(struct ffmpeg_output *stream,
  387. struct ffmpeg_data *data)
  388. {
  389. int ret;
  390. bool rist = is_rist(stream);
  391. bool srt = is_srt(stream);
  392. bool allowed_proto = proto_is_allowed(stream);
  393. AVDictionary *dict = NULL;
  394. /* Retrieve protocol settings for udp, tcp, rtp ... (not srt or rist).
  395. * These options will be passed to protocol by avio_open2 through dict.
  396. * The invalid options will be left in dict. */
  397. if (!rist && !srt) {
  398. if ((ret = av_dict_parse_string(&dict,
  399. data->config.protocol_settings,
  400. "=", " ", 0))) {
  401. ffmpeg_mpegts_log_error(
  402. LOG_WARNING, data,
  403. "Failed to parse protocol settings: %s, %s",
  404. data->config.protocol_settings,
  405. av_err2str(ret));
  406. av_dict_free(&dict);
  407. return OBS_OUTPUT_INVALID_STREAM;
  408. }
  409. if (av_dict_count(dict) > 0) {
  410. struct dstr str = {0};
  411. AVDictionaryEntry *entry = NULL;
  412. while ((entry = av_dict_get(dict, "", entry,
  413. AV_DICT_IGNORE_SUFFIX)))
  414. dstr_catf(&str, "\n\t%s=%s", entry->key,
  415. entry->value);
  416. info("Using protocol settings: %s", str.array);
  417. dstr_free(&str);
  418. }
  419. }
  420. /* Ensure h264 bitstream auto conversion from avcc to annex B */
  421. data->output->flags |= AVFMT_FLAG_AUTO_BSF;
  422. /* Open URL for rist, srt or other protocols compatible with mpegts
  423. * muxer supported by avformat (udp, tcp, rtp ...).
  424. */
  425. if (rist) {
  426. ret = connect_mpegts_url(stream, true);
  427. } else if (srt) {
  428. ret = connect_mpegts_url(stream, false);
  429. } else if (allowed_proto) {
  430. ret = avio_open2(&data->output->pb, data->config.url,
  431. AVIO_FLAG_WRITE, NULL, &dict);
  432. } else {
  433. info("[ffmpeg mpegts muxer]: Invalid protocol: %s",
  434. data->config.url);
  435. return OBS_OUTPUT_BAD_PATH;
  436. }
  437. if (ret < 0) {
  438. if ((rist || srt) && (ret == OBS_OUTPUT_CONNECT_FAILED ||
  439. ret == OBS_OUTPUT_INVALID_STREAM)) {
  440. error("Failed to open the url or invalid stream");
  441. } else {
  442. ffmpeg_mpegts_log_error(LOG_WARNING, data,
  443. "Couldn't open '%s', %s",
  444. data->config.url,
  445. av_err2str(ret));
  446. av_dict_free(&dict);
  447. }
  448. return ret;
  449. }
  450. /* Log invalid protocol settings for all protocols except srt or rist.
  451. * Or for srt & rist, allocate custom avio_ctx which will host the
  452. * protocols write callbacks.
  453. */
  454. if (!rist && !srt) {
  455. if (av_dict_count(dict) > 0) {
  456. struct dstr str = {0};
  457. AVDictionaryEntry *entry = NULL;
  458. while ((entry = av_dict_get(dict, "", entry,
  459. AV_DICT_IGNORE_SUFFIX)))
  460. dstr_catf(&str, "\n\t%s=%s", entry->key,
  461. entry->value);
  462. info("[ffmpeg mpegts muxer]: Invalid protocol settings: %s",
  463. str.array);
  464. dstr_free(&str);
  465. }
  466. av_dict_free(&dict);
  467. } else {
  468. ret = allocate_custom_aviocontext(stream, rist);
  469. if (ret < 0) {
  470. info("Couldn't allocate custom avio_context for url: '%s', %s",
  471. data->config.url, av_err2str(ret));
  472. return OBS_OUTPUT_INVALID_STREAM;
  473. }
  474. }
  475. return 0;
  476. }
  477. static void close_video(struct ffmpeg_data *data)
  478. {
  479. avcodec_free_context(&data->video_ctx);
  480. }
  481. static void close_audio(struct ffmpeg_data *data)
  482. {
  483. for (int idx = 0; idx < data->num_audio_streams; idx++) {
  484. for (size_t i = 0; i < MAX_AV_PLANES; i++)
  485. circlebuf_free(&data->excess_frames[idx][i]);
  486. if (data->samples[idx][0])
  487. av_freep(&data->samples[idx][0]);
  488. if (data->audio_infos[idx].ctx) {
  489. avcodec_free_context(&data->audio_infos[idx].ctx);
  490. }
  491. if (data->aframe[idx])
  492. av_frame_free(&data->aframe[idx]);
  493. }
  494. }
  495. static void close_mpegts_url(struct ffmpeg_output *stream, bool is_rist)
  496. {
  497. int err = 0;
  498. AVIOContext *s = stream->s;
  499. if (!s)
  500. return;
  501. URLContext *h = s->opaque;
  502. if (!h)
  503. return; /* can happen when opening the url fails */
  504. /* close rist or srt URLs ; free URLContext */
  505. if (is_rist) {
  506. err = librist_close(h);
  507. } else {
  508. err = libsrt_close(h);
  509. }
  510. av_freep(&h->priv_data);
  511. av_freep(h);
  512. /* close custom avio_context for srt or rist */
  513. avio_flush(stream->s);
  514. stream->s->opaque = NULL;
  515. av_freep(&stream->s->buffer);
  516. avio_context_free(&stream->s);
  517. if (err)
  518. info("[ffmpeg mpegts muxer]: Error closing URL %s",
  519. stream->ff_data.config.url);
  520. }
  521. void ffmpeg_mpegts_data_free(struct ffmpeg_output *stream,
  522. struct ffmpeg_data *data)
  523. {
  524. if (data->initialized)
  525. av_write_trailer(data->output);
  526. if (data->video)
  527. close_video(data);
  528. if (data->audio_infos) {
  529. close_audio(data);
  530. free(data->audio_infos);
  531. }
  532. if (data->output) {
  533. if (is_rist(stream) || is_srt(stream)) {
  534. close_mpegts_url(stream, is_rist(stream));
  535. } else {
  536. avio_close(data->output->pb);
  537. }
  538. avformat_free_context(data->output);
  539. data->video = NULL;
  540. data->audio_infos = NULL;
  541. data->output = NULL;
  542. data->num_audio_streams = 0;
  543. }
  544. if (data->last_error)
  545. bfree(data->last_error);
  546. memset(data, 0, sizeof(struct ffmpeg_data));
  547. }
  548. static inline const char *safe_str(const char *s)
  549. {
  550. if (s == NULL)
  551. return "(NULL)";
  552. else
  553. return s;
  554. }
  555. bool ffmpeg_mpegts_data_init(struct ffmpeg_output *stream,
  556. struct ffmpeg_data *data,
  557. struct ffmpeg_cfg *config)
  558. {
  559. memset(data, 0, sizeof(struct ffmpeg_data));
  560. data->config = *config;
  561. data->num_audio_streams = config->audio_mix_count;
  562. data->audio_tracks = config->audio_tracks;
  563. if (!config->url || !*config->url)
  564. return false;
  565. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
  566. av_register_all();
  567. #endif
  568. avformat_network_init();
  569. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  570. AVOutputFormat *output_format;
  571. #else
  572. const AVOutputFormat *output_format;
  573. #endif
  574. output_format = av_guess_format("mpegts", NULL, "video/M2PT");
  575. if (output_format == NULL) {
  576. ffmpeg_mpegts_log_error(LOG_WARNING, data,
  577. "Couldn't set output format to mpegts");
  578. goto fail;
  579. } else {
  580. info("Output format name and long_name: %s, %s",
  581. output_format->name ? output_format->name : "unknown",
  582. output_format->long_name ? output_format->long_name
  583. : "unknown");
  584. }
  585. avformat_alloc_output_context2(&data->output, output_format, NULL,
  586. data->config.url);
  587. if (!data->output) {
  588. ffmpeg_mpegts_log_error(LOG_WARNING, data,
  589. "Couldn't create avformat context");
  590. goto fail;
  591. }
  592. return true;
  593. fail:
  594. warn("ffmpeg_data_init failed");
  595. return false;
  596. }
  597. /* ------------------------------------------------------------------------- */
  598. static inline bool stopping(struct ffmpeg_output *output)
  599. {
  600. return os_atomic_load_bool(&output->stopping);
  601. }
  602. static const char *ffmpeg_mpegts_getname(void *unused)
  603. {
  604. UNUSED_PARAMETER(unused);
  605. return obs_module_text("FFmpegMpegts");
  606. }
  607. static void ffmpeg_mpegts_log_callback(void *param, int level,
  608. const char *format, va_list args)
  609. {
  610. if (level <= AV_LOG_INFO)
  611. blogva(LOG_DEBUG, format, args);
  612. UNUSED_PARAMETER(param);
  613. }
  614. static void *ffmpeg_mpegts_create(obs_data_t *settings, obs_output_t *output)
  615. {
  616. struct ffmpeg_output *data = bzalloc(sizeof(struct ffmpeg_output));
  617. pthread_mutex_init_value(&data->write_mutex);
  618. data->output = output;
  619. if (pthread_mutex_init(&data->write_mutex, NULL) != 0)
  620. goto fail;
  621. if (os_event_init(&data->stop_event, OS_EVENT_TYPE_AUTO) != 0)
  622. goto fail;
  623. if (os_sem_init(&data->write_sem, 0) != 0)
  624. goto fail;
  625. av_log_set_callback(ffmpeg_mpegts_log_callback);
  626. UNUSED_PARAMETER(settings);
  627. return data;
  628. fail:
  629. pthread_mutex_destroy(&data->write_mutex);
  630. os_event_destroy(data->stop_event);
  631. bfree(data);
  632. return NULL;
  633. }
  634. static void ffmpeg_mpegts_full_stop(void *data);
  635. static void ffmpeg_mpegts_deactivate(struct ffmpeg_output *output);
  636. static void ffmpeg_mpegts_destroy(void *data)
  637. {
  638. struct ffmpeg_output *output = data;
  639. if (output) {
  640. if (output->connecting)
  641. pthread_join(output->start_thread, NULL);
  642. ffmpeg_mpegts_full_stop(output);
  643. pthread_mutex_destroy(&output->write_mutex);
  644. os_sem_destroy(output->write_sem);
  645. os_event_destroy(output->stop_event);
  646. bfree(data);
  647. }
  648. }
  649. static uint64_t get_packet_sys_dts(struct ffmpeg_output *output,
  650. AVPacket *packet)
  651. {
  652. struct ffmpeg_data *data = &output->ff_data;
  653. uint64_t pause_offset = obs_output_get_pause_offset(output->output);
  654. uint64_t start_ts;
  655. AVRational time_base;
  656. if (data->video && data->video->index == packet->stream_index) {
  657. time_base = data->video->time_base;
  658. start_ts = output->video_start_ts;
  659. } else {
  660. time_base = data->audio_infos[0].stream->time_base;
  661. start_ts = output->audio_start_ts;
  662. }
  663. return start_ts + pause_offset +
  664. (uint64_t)av_rescale_q(packet->dts, time_base,
  665. (AVRational){1, 1000000000});
  666. }
  667. static int mpegts_process_packet(struct ffmpeg_output *output)
  668. {
  669. AVPacket *packet = NULL;
  670. int ret = 0;
  671. pthread_mutex_lock(&output->write_mutex);
  672. if (output->packets.num) {
  673. packet = output->packets.array[0];
  674. da_erase(output->packets, 0);
  675. }
  676. pthread_mutex_unlock(&output->write_mutex);
  677. if (!packet)
  678. return 0;
  679. //blog(LOG_DEBUG,
  680. // "size = %d, flags = %lX, stream = %d, "
  681. // "packets queued: %lu",
  682. // packet->size, packet->flags, packet->stream_index,
  683. // output->packets.num);
  684. if (stopping(output)) {
  685. uint64_t sys_ts = get_packet_sys_dts(output, packet);
  686. if (sys_ts >= output->stop_ts) {
  687. ret = 0;
  688. goto end;
  689. }
  690. }
  691. output->total_bytes += packet->size;
  692. uint8_t *buf = packet->data;
  693. ret = av_interleaved_write_frame(output->ff_data.output, packet);
  694. av_freep(&buf);
  695. if (ret < 0) {
  696. ffmpeg_mpegts_log_error(
  697. LOG_WARNING, &output->ff_data,
  698. "process_packet: Error writing packet: %s",
  699. av_err2str(ret));
  700. /* Treat "Invalid data found when processing input" and
  701. * "Invalid argument" as non-fatal */
  702. if (ret == AVERROR_INVALIDDATA || ret == -EINVAL) {
  703. ret = 0;
  704. }
  705. }
  706. end:
  707. av_packet_free(&packet);
  708. return ret;
  709. }
  710. static void *write_thread(void *data)
  711. {
  712. struct ffmpeg_output *output = data;
  713. while (os_sem_wait(output->write_sem) == 0) {
  714. /* check to see if shutting down */
  715. if (os_event_try(output->stop_event) == 0)
  716. break;
  717. int ret = mpegts_process_packet(output);
  718. if (ret != 0) {
  719. int code = OBS_OUTPUT_DISCONNECTED;
  720. pthread_detach(output->write_thread);
  721. output->write_thread_active = false;
  722. if (ret == -ENOSPC)
  723. code = OBS_OUTPUT_NO_SPACE;
  724. obs_output_signal_stop(output->output, code);
  725. ffmpeg_mpegts_deactivate(output);
  726. break;
  727. }
  728. }
  729. os_atomic_set_bool(&output->active, false);
  730. return NULL;
  731. }
  732. static bool get_extradata(struct ffmpeg_output *stream)
  733. {
  734. struct ffmpeg_data *ff_data = &stream->ff_data;
  735. /* get extradata for av headers from encoders */
  736. if (!get_video_headers(stream, ff_data))
  737. return false;
  738. for (int i = 0; i < ff_data->num_audio_streams; i++) {
  739. if (!get_audio_headers(stream, ff_data, i))
  740. return false;
  741. }
  742. return true;
  743. }
  744. /* set ffmpeg_config & init write_thread & capture */
  745. static bool set_config(struct ffmpeg_output *stream)
  746. {
  747. struct ffmpeg_cfg config;
  748. bool success;
  749. int ret;
  750. int code;
  751. /* 1. Get URL/username/password from service & set format + mime-type. */
  752. obs_service_t *service;
  753. service = obs_output_get_service(stream->output);
  754. if (!service)
  755. return false;
  756. config.url = obs_service_get_connect_info(
  757. service, OBS_SERVICE_CONNECT_INFO_SERVER_URL);
  758. config.username = obs_service_get_connect_info(
  759. service, OBS_SERVICE_CONNECT_INFO_USERNAME);
  760. config.password = obs_service_get_connect_info(
  761. service, OBS_SERVICE_CONNECT_INFO_PASSWORD);
  762. config.stream_id = obs_service_get_connect_info(
  763. service, OBS_SERVICE_CONNECT_INFO_STREAM_ID);
  764. config.encrypt_passphrase = obs_service_get_connect_info(
  765. service, OBS_SERVICE_CONNECT_INFO_ENCRYPT_PASSPHRASE);
  766. config.format_name = "mpegts";
  767. config.format_mime_type = "video/M2PT";
  768. /* 2. video settings */
  769. // 2.a) set video format from obs to FFmpeg
  770. video_t *video = obs_output_video(stream->output);
  771. config.format =
  772. obs_to_ffmpeg_video_format(video_output_get_format(video));
  773. if (config.format == AV_PIX_FMT_NONE) {
  774. blog(LOG_WARNING,
  775. "Invalid pixel format used for mpegts output");
  776. return false;
  777. }
  778. // 2.b) set colorspace, color_range & transfer characteristic (from voi)
  779. const struct video_output_info *voi = video_output_get_info(video);
  780. config.color_range = voi->range == VIDEO_RANGE_FULL ? AVCOL_RANGE_JPEG
  781. : AVCOL_RANGE_MPEG;
  782. config.colorspace = format_is_yuv(voi->format) ? AVCOL_SPC_BT709
  783. : AVCOL_SPC_RGB;
  784. switch (voi->colorspace) {
  785. case VIDEO_CS_601:
  786. config.color_primaries = AVCOL_PRI_SMPTE170M;
  787. config.color_trc = AVCOL_TRC_SMPTE170M;
  788. config.colorspace = AVCOL_SPC_SMPTE170M;
  789. break;
  790. case VIDEO_CS_DEFAULT:
  791. case VIDEO_CS_709:
  792. config.color_primaries = AVCOL_PRI_BT709;
  793. config.color_trc = AVCOL_TRC_BT709;
  794. config.colorspace = AVCOL_SPC_BT709;
  795. break;
  796. case VIDEO_CS_SRGB:
  797. config.color_primaries = AVCOL_PRI_BT709;
  798. config.color_trc = AVCOL_TRC_IEC61966_2_1;
  799. config.colorspace = AVCOL_SPC_BT709;
  800. break;
  801. case VIDEO_CS_2100_PQ:
  802. config.color_primaries = AVCOL_PRI_BT2020;
  803. config.color_trc = AVCOL_TRC_SMPTE2084;
  804. config.colorspace = AVCOL_SPC_BT2020_NCL;
  805. break;
  806. case VIDEO_CS_2100_HLG:
  807. config.color_primaries = AVCOL_PRI_BT2020;
  808. config.color_trc = AVCOL_TRC_ARIB_STD_B67;
  809. config.colorspace = AVCOL_SPC_BT2020_NCL;
  810. }
  811. // 2.c) set width & height
  812. config.width = (int)obs_output_get_width(stream->output);
  813. config.height = (int)obs_output_get_height(stream->output);
  814. config.scale_width = config.width;
  815. config.scale_height = config.height;
  816. // 2.d) set video codec & id from video encoder
  817. obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output);
  818. config.video_encoder = obs_encoder_get_codec(vencoder);
  819. if (strcmp(config.video_encoder, "h264") == 0)
  820. config.video_encoder_id = AV_CODEC_ID_H264;
  821. else
  822. config.video_encoder_id = AV_CODEC_ID_AV1;
  823. // 2.e) set video bitrate & gop through video encoder settings
  824. obs_data_t *settings = obs_encoder_get_settings(vencoder);
  825. config.video_bitrate = (int)obs_data_get_int(settings, "bitrate");
  826. int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
  827. config.gop_size = keyint_sec ? keyint_sec * voi->fps_num / voi->fps_den
  828. : 250;
  829. obs_data_release(settings);
  830. /* 3. Audio settings */
  831. // 3.a) set audio codec & id from audio encoder
  832. obs_encoder_t *aencoder =
  833. obs_output_get_audio_encoder(stream->output, 0);
  834. config.audio_encoder = obs_encoder_get_codec(aencoder);
  835. if (strcmp(config.audio_encoder, "aac") == 0)
  836. config.audio_encoder_id = AV_CODEC_ID_AAC;
  837. else if (strcmp(config.audio_encoder, "opus") == 0)
  838. config.audio_encoder_id = AV_CODEC_ID_OPUS;
  839. // 3.b) get audio bitrate from the audio encoder.
  840. settings = obs_encoder_get_settings(aencoder);
  841. config.audio_bitrate = (int)obs_data_get_int(settings, "bitrate");
  842. obs_data_release(settings);
  843. // 3.c set audio frame size
  844. config.frame_size = (int)obs_encoder_get_frame_size(aencoder);
  845. // 3.d) set the number of tracks
  846. // The UI for multiple tracks is not written for streaming outputs.
  847. // When it is, modify write_packet & uncomment :
  848. // config.audio_tracks = (int)obs_output_get_mixers(stream->output);
  849. // config.audio_mix_count = get_audio_mix_count(config.audio_tracks);
  850. config.audio_tracks = 1;
  851. config.audio_mix_count = 1;
  852. /* 4. Muxer & protocol settings */
  853. // This requires some UI to be written for the output.
  854. // at the service level unless one can load the output in the settings/stream screen.
  855. settings = obs_output_get_settings(stream->output);
  856. obs_data_set_default_string(settings, "muxer_settings", "");
  857. config.muxer_settings = obs_data_get_string(settings, "muxer_settings");
  858. obs_data_release(settings);
  859. config.protocol_settings = "";
  860. /* 5. unused ffmpeg codec settings */
  861. config.video_settings = "";
  862. config.audio_settings = "";
  863. success = ffmpeg_mpegts_data_init(stream, &stream->ff_data, &config);
  864. if (!success) {
  865. if (stream->ff_data.last_error) {
  866. obs_output_set_last_error(stream->output,
  867. stream->ff_data.last_error);
  868. }
  869. ffmpeg_mpegts_data_free(stream, &stream->ff_data);
  870. code = OBS_OUTPUT_INVALID_STREAM;
  871. goto fail;
  872. }
  873. struct ffmpeg_data *ff_data = &stream->ff_data;
  874. if (!stream->got_headers) {
  875. if (!init_streams(stream, ff_data)) {
  876. error("mpegts avstream failed to be created");
  877. code = OBS_OUTPUT_INVALID_STREAM;
  878. goto fail;
  879. }
  880. code = open_output_file(stream, ff_data);
  881. if (code != 0) {
  882. error("Failed to open the url");
  883. goto fail;
  884. }
  885. av_dump_format(ff_data->output, 0, NULL, 1);
  886. }
  887. if (!obs_output_can_begin_data_capture2(stream->output))
  888. return false;
  889. if (!obs_output_initialize_encoders2(stream->output))
  890. return false;
  891. ret = pthread_create(&stream->write_thread, NULL, write_thread, stream);
  892. if (ret != 0) {
  893. ffmpeg_mpegts_log_error(
  894. LOG_WARNING, &stream->ff_data,
  895. "ffmpeg_output_start: Failed to create write "
  896. "thread.");
  897. code = OBS_OUTPUT_ERROR;
  898. goto fail;
  899. }
  900. os_atomic_set_bool(&stream->active, true);
  901. stream->write_thread_active = true;
  902. stream->total_bytes = 0;
  903. obs_output_begin_data_capture2(stream->output);
  904. return true;
  905. fail:
  906. obs_output_signal_stop(stream->output, code);
  907. ffmpeg_mpegts_full_stop(stream);
  908. return false;
  909. }
  910. static void *start_thread(void *data)
  911. {
  912. struct ffmpeg_output *output = data;
  913. set_config(output);
  914. output->connecting = false;
  915. return NULL;
  916. }
  917. static bool ffmpeg_mpegts_start(void *data)
  918. {
  919. struct ffmpeg_output *output = data;
  920. int ret;
  921. if (output->connecting)
  922. return false;
  923. os_atomic_set_bool(&output->stopping, false);
  924. output->audio_start_ts = 0;
  925. output->video_start_ts = 0;
  926. output->total_bytes = 0;
  927. output->got_headers = false;
  928. ret = pthread_create(&output->start_thread, NULL, start_thread, output);
  929. return (output->connecting = (ret == 0));
  930. }
  931. static void ffmpeg_mpegts_full_stop(void *data)
  932. {
  933. struct ffmpeg_output *output = data;
  934. if (output->active) {
  935. obs_output_end_data_capture(output->output);
  936. ffmpeg_mpegts_deactivate(output);
  937. }
  938. }
  939. static void ffmpeg_mpegts_stop(void *data, uint64_t ts)
  940. {
  941. struct ffmpeg_output *output = data;
  942. if (output->active) {
  943. if (ts > 0) {
  944. output->stop_ts = ts;
  945. os_atomic_set_bool(&output->stopping, true);
  946. }
  947. ffmpeg_mpegts_full_stop(output);
  948. } else {
  949. obs_output_signal_stop(output->output, OBS_OUTPUT_SUCCESS);
  950. }
  951. }
  952. static void ffmpeg_mpegts_deactivate(struct ffmpeg_output *output)
  953. {
  954. if (output->write_thread_active) {
  955. os_event_signal(output->stop_event);
  956. os_sem_post(output->write_sem);
  957. pthread_join(output->write_thread, NULL);
  958. output->write_thread_active = false;
  959. }
  960. pthread_mutex_lock(&output->write_mutex);
  961. for (size_t i = 0; i < output->packets.num; i++)
  962. av_packet_free(output->packets.array + i);
  963. da_free(output->packets);
  964. pthread_mutex_unlock(&output->write_mutex);
  965. ffmpeg_mpegts_data_free(output, &output->ff_data);
  966. }
  967. static uint64_t ffmpeg_mpegts_total_bytes(void *data)
  968. {
  969. struct ffmpeg_output *output = data;
  970. return output->total_bytes;
  971. }
  972. static inline int64_t rescale_ts2(AVStream *stream, AVRational codec_time_base,
  973. int64_t val)
  974. {
  975. return av_rescale_q_rnd(val / codec_time_base.num, codec_time_base,
  976. stream->time_base,
  977. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  978. }
  979. /* Convert obs encoder_packet to FFmpeg AVPacket and write to circular buffer
  980. * where it will be processed in the write_thread by process_packet.
  981. */
  982. void mpegts_write_packet(struct ffmpeg_output *stream,
  983. struct encoder_packet *encpacket)
  984. {
  985. if (stopping(stream) || !stream->ff_data.video ||
  986. !stream->ff_data.video_ctx || !stream->ff_data.audio_infos)
  987. return;
  988. if (!stream->ff_data.audio_infos[encpacket->track_idx].stream)
  989. return;
  990. bool is_video = encpacket->type == OBS_ENCODER_VIDEO;
  991. AVStream *avstream =
  992. is_video ? stream->ff_data.video
  993. : stream->ff_data.audio_infos[encpacket->track_idx]
  994. .stream;
  995. AVPacket *packet = NULL;
  996. const AVRational codec_time_base =
  997. is_video ? stream->ff_data.video_ctx->time_base
  998. : stream->ff_data.audio_infos[encpacket->track_idx]
  999. .ctx->time_base;
  1000. packet = av_packet_alloc();
  1001. packet->data = av_memdup(encpacket->data, (int)encpacket->size);
  1002. if (packet->data == NULL) {
  1003. error("Couldn't allocate packet data");
  1004. goto fail;
  1005. }
  1006. packet->size = (int)encpacket->size;
  1007. packet->stream_index = avstream->id;
  1008. packet->pts = rescale_ts2(avstream, codec_time_base, encpacket->pts);
  1009. packet->dts = rescale_ts2(avstream, codec_time_base, encpacket->dts);
  1010. if (encpacket->keyframe)
  1011. packet->flags = AV_PKT_FLAG_KEY;
  1012. pthread_mutex_lock(&stream->write_mutex);
  1013. da_push_back(stream->packets, &packet);
  1014. pthread_mutex_unlock(&stream->write_mutex);
  1015. os_sem_post(stream->write_sem);
  1016. return;
  1017. fail:
  1018. av_packet_free(&packet);
  1019. }
  1020. static bool write_header(struct ffmpeg_output *stream, struct ffmpeg_data *data)
  1021. {
  1022. AVDictionary *dict = NULL;
  1023. int ret;
  1024. /* get mpegts muxer settings (can be used with rist, srt, rtp, etc ... */
  1025. if ((ret = av_dict_parse_string(&dict, data->config.muxer_settings, "=",
  1026. " ", 0))) {
  1027. ffmpeg_mpegts_log_error(
  1028. LOG_WARNING, data,
  1029. "Failed to parse muxer settings: %s, %s",
  1030. data->config.muxer_settings, av_err2str(ret));
  1031. av_dict_free(&dict);
  1032. return false;
  1033. }
  1034. if (av_dict_count(dict) > 0) {
  1035. struct dstr str = {0};
  1036. AVDictionaryEntry *entry = NULL;
  1037. while ((entry = av_dict_get(dict, "", entry,
  1038. AV_DICT_IGNORE_SUFFIX)))
  1039. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  1040. info("Using muxer settings: %s", str.array);
  1041. dstr_free(&str);
  1042. }
  1043. /* Allocate the stream private data and write the stream header. */
  1044. ret = avformat_write_header(data->output, &dict);
  1045. if (ret < 0) {
  1046. ffmpeg_mpegts_log_error(
  1047. LOG_WARNING, data,
  1048. "Error setting stream header for '%s': %s",
  1049. data->config.url, av_err2str(ret));
  1050. return false;
  1051. }
  1052. /* Log invalid muxer settings. */
  1053. if (av_dict_count(dict) > 0) {
  1054. struct dstr str = {0};
  1055. AVDictionaryEntry *entry = NULL;
  1056. while ((entry = av_dict_get(dict, "", entry,
  1057. AV_DICT_IGNORE_SUFFIX)))
  1058. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  1059. info("[ffmpeg mpegts muxer]: Invalid mpegts muxer settings: %s",
  1060. str.array);
  1061. dstr_free(&str);
  1062. }
  1063. av_dict_free(&dict);
  1064. return true;
  1065. }
  1066. static void ffmpeg_mpegts_data(void *data, struct encoder_packet *packet)
  1067. {
  1068. struct ffmpeg_output *stream = data;
  1069. struct ffmpeg_data *ff_data = &stream->ff_data;
  1070. int code;
  1071. if (!stream->got_headers) {
  1072. if (get_extradata(stream)) {
  1073. stream->got_headers = true;
  1074. } else {
  1075. warn("Failed to retrieve headers");
  1076. code = OBS_OUTPUT_INVALID_STREAM;
  1077. goto fail;
  1078. }
  1079. if (!write_header(stream, ff_data)) {
  1080. error("Failed to write headers");
  1081. code = OBS_OUTPUT_INVALID_STREAM;
  1082. goto fail;
  1083. }
  1084. av_dump_format(ff_data->output, 0, NULL, 1);
  1085. ff_data->initialized = true;
  1086. }
  1087. if (!stream->active)
  1088. return;
  1089. /* encoder failure */
  1090. if (!packet) {
  1091. obs_output_signal_stop(stream->output, OBS_OUTPUT_ENCODE_ERROR);
  1092. ffmpeg_mpegts_deactivate(stream);
  1093. return;
  1094. }
  1095. if (stopping(stream)) {
  1096. if (packet->sys_dts_usec >= (int64_t)stream->stop_ts) {
  1097. ffmpeg_mpegts_deactivate(stream);
  1098. return;
  1099. }
  1100. }
  1101. mpegts_write_packet(stream, packet);
  1102. return;
  1103. fail:
  1104. obs_output_signal_stop(stream->output, code);
  1105. ffmpeg_mpegts_full_stop(stream);
  1106. }
  1107. static obs_properties_t *ffmpeg_mpegts_properties(void *unused)
  1108. {
  1109. UNUSED_PARAMETER(unused);
  1110. obs_properties_t *props = obs_properties_create();
  1111. obs_properties_add_text(props, "path", obs_module_text("FilePath"),
  1112. OBS_TEXT_DEFAULT);
  1113. return props;
  1114. }
  1115. struct obs_output_info ffmpeg_mpegts_muxer = {
  1116. .id = "ffmpeg_mpegts_muxer",
  1117. .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK |
  1118. OBS_OUTPUT_SERVICE,
  1119. .protocols = "SRT;RIST",
  1120. #ifdef ENABLE_HEVC
  1121. .encoded_video_codecs = "h264;hevc",
  1122. #else
  1123. .encoded_video_codecs = "h264",
  1124. #endif
  1125. .encoded_audio_codecs = "aac;opus",
  1126. .get_name = ffmpeg_mpegts_getname,
  1127. .create = ffmpeg_mpegts_create,
  1128. .destroy = ffmpeg_mpegts_destroy,
  1129. .start = ffmpeg_mpegts_start,
  1130. .stop = ffmpeg_mpegts_stop,
  1131. .encoded_packet = ffmpeg_mpegts_data,
  1132. .get_total_bytes = ffmpeg_mpegts_total_bytes,
  1133. .get_properties = ffmpeg_mpegts_properties,
  1134. };