obs-ffmpeg-mpegts.c 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310
  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 "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.key != NULL) {
  304. if (strlen(stream->ff_data.config.key))
  305. context->streamid =
  306. av_strdup(stream->ff_data.config.key);
  307. }
  308. context->passphrase = NULL;
  309. if (stream->ff_data.config.password != NULL) {
  310. if (strlen(stream->ff_data.config.password))
  311. context->passphrase = av_strdup(
  312. stream->ff_data.config.password);
  313. }
  314. } else {
  315. RISTContext *context = (RISTContext *)uc->priv_data;
  316. context->secret = NULL;
  317. if (stream->ff_data.config.key != NULL) {
  318. if (strlen(stream->ff_data.config.key))
  319. context->secret =
  320. bstrdup(stream->ff_data.config.key);
  321. }
  322. context->username = NULL;
  323. if (stream->ff_data.config.username != NULL) {
  324. if (strlen(stream->ff_data.config.username))
  325. context->username = bstrdup(
  326. stream->ff_data.config.username);
  327. }
  328. context->password = NULL;
  329. if (stream->ff_data.config.password != NULL) {
  330. if (strlen(stream->ff_data.config.password))
  331. context->password = bstrdup(
  332. stream->ff_data.config.password);
  333. }
  334. }
  335. stream->h = uc;
  336. if (is_rist)
  337. err = librist_open(uc, uc->url);
  338. else
  339. err = libsrt_open(uc, uc->url);
  340. if (err < 0)
  341. goto fail;
  342. return 0;
  343. fail:
  344. if (uc)
  345. av_freep(&uc->priv_data);
  346. av_freep(&uc);
  347. #if HAVE_WINSOCK2_H
  348. WSACleanup();
  349. #endif
  350. return err;
  351. }
  352. static inline int allocate_custom_aviocontext(struct ffmpeg_output *stream,
  353. bool is_rist)
  354. {
  355. /* allocate buffers */
  356. uint8_t *buffer = NULL;
  357. int buffer_size;
  358. URLContext *h = stream->h;
  359. AVIOContext *s = NULL;
  360. buffer_size = UDP_DEFAULT_PAYLOAD_SIZE;
  361. buffer = av_malloc(buffer_size);
  362. if (!buffer)
  363. return AVERROR(ENOMEM);
  364. /* allocate custom avio_context */
  365. if (is_rist)
  366. s = avio_alloc_context(
  367. buffer, buffer_size, AVIO_FLAG_WRITE, h, NULL,
  368. (int (*)(void *, uint8_t *, int))librist_write, NULL);
  369. else
  370. s = avio_alloc_context(
  371. buffer, buffer_size, AVIO_FLAG_WRITE, h, NULL,
  372. (int (*)(void *, uint8_t *, int))libsrt_write, NULL);
  373. if (!s)
  374. goto fail;
  375. s->max_packet_size = h->max_packet_size;
  376. s->opaque = h;
  377. stream->s = s;
  378. stream->ff_data.output->pb = s;
  379. return 0;
  380. fail:
  381. av_freep(&buffer);
  382. return AVERROR(ENOMEM);
  383. }
  384. static inline int open_output_file(struct ffmpeg_output *stream,
  385. struct ffmpeg_data *data)
  386. {
  387. int ret;
  388. bool rist = is_rist(stream);
  389. bool srt = is_srt(stream);
  390. bool allowed_proto = proto_is_allowed(stream);
  391. AVDictionary *dict = NULL;
  392. /* Retrieve protocol settings for udp, tcp, rtp ... (not srt or rist).
  393. * These options will be passed to protocol by avio_open2 through dict.
  394. * The invalid options will be left in dict. */
  395. if (!rist && !srt) {
  396. if ((ret = av_dict_parse_string(&dict,
  397. data->config.protocol_settings,
  398. "=", " ", 0))) {
  399. ffmpeg_mpegts_log_error(
  400. LOG_WARNING, data,
  401. "Failed to parse protocol settings: %s, %s",
  402. data->config.protocol_settings,
  403. av_err2str(ret));
  404. av_dict_free(&dict);
  405. return OBS_OUTPUT_INVALID_STREAM;
  406. }
  407. if (av_dict_count(dict) > 0) {
  408. struct dstr str = {0};
  409. AVDictionaryEntry *entry = NULL;
  410. while ((entry = av_dict_get(dict, "", entry,
  411. AV_DICT_IGNORE_SUFFIX)))
  412. dstr_catf(&str, "\n\t%s=%s", entry->key,
  413. entry->value);
  414. info("Using protocol settings: %s", str.array);
  415. dstr_free(&str);
  416. }
  417. }
  418. /* Ensure h264 bitstream auto conversion from avcc to annex B */
  419. data->output->flags |= AVFMT_FLAG_AUTO_BSF;
  420. /* Open URL for rist, srt or other protocols compatible with mpegts
  421. * muxer supported by avformat (udp, tcp, rtp ...).
  422. */
  423. if (rist) {
  424. ret = connect_mpegts_url(stream, true);
  425. } else if (srt) {
  426. ret = connect_mpegts_url(stream, false);
  427. } else if (allowed_proto) {
  428. ret = avio_open2(&data->output->pb, data->config.url,
  429. AVIO_FLAG_WRITE, NULL, &dict);
  430. } else {
  431. info("[ffmpeg mpegts muxer]: Invalid protocol: %s",
  432. data->config.url);
  433. return OBS_OUTPUT_BAD_PATH;
  434. }
  435. if (ret < 0) {
  436. if ((rist || srt) && (ret == OBS_OUTPUT_CONNECT_FAILED ||
  437. ret == OBS_OUTPUT_INVALID_STREAM)) {
  438. error("Failed to open the url or invalid stream");
  439. } else {
  440. ffmpeg_mpegts_log_error(LOG_WARNING, data,
  441. "Couldn't open '%s', %s",
  442. data->config.url,
  443. av_err2str(ret));
  444. av_dict_free(&dict);
  445. }
  446. return ret;
  447. }
  448. /* Log invalid protocol settings for all protocols except srt or rist.
  449. * Or for srt & rist, allocate custom avio_ctx which will host the
  450. * protocols write callbacks.
  451. */
  452. if (!rist && !srt) {
  453. if (av_dict_count(dict) > 0) {
  454. struct dstr str = {0};
  455. AVDictionaryEntry *entry = NULL;
  456. while ((entry = av_dict_get(dict, "", entry,
  457. AV_DICT_IGNORE_SUFFIX)))
  458. dstr_catf(&str, "\n\t%s=%s", entry->key,
  459. entry->value);
  460. info("[ffmpeg mpegts muxer]: Invalid protocol settings: %s",
  461. str.array);
  462. dstr_free(&str);
  463. }
  464. av_dict_free(&dict);
  465. } else {
  466. ret = allocate_custom_aviocontext(stream, rist);
  467. if (ret < 0) {
  468. info("Couldn't allocate custom avio_context for url: '%s', %s",
  469. data->config.url, av_err2str(ret));
  470. return OBS_OUTPUT_INVALID_STREAM;
  471. }
  472. }
  473. return 0;
  474. }
  475. static void close_video(struct ffmpeg_data *data)
  476. {
  477. avcodec_free_context(&data->video_ctx);
  478. }
  479. static void close_audio(struct ffmpeg_data *data)
  480. {
  481. for (int idx = 0; idx < data->num_audio_streams; idx++) {
  482. for (size_t i = 0; i < MAX_AV_PLANES; i++)
  483. circlebuf_free(&data->excess_frames[idx][i]);
  484. if (data->samples[idx][0])
  485. av_freep(&data->samples[idx][0]);
  486. if (data->audio_infos[idx].ctx) {
  487. avcodec_free_context(&data->audio_infos[idx].ctx);
  488. }
  489. if (data->aframe[idx])
  490. av_frame_free(&data->aframe[idx]);
  491. }
  492. }
  493. static void close_mpegts_url(struct ffmpeg_output *stream, bool is_rist)
  494. {
  495. int err = 0;
  496. AVIOContext *s = stream->s;
  497. if (!s)
  498. return;
  499. URLContext *h = s->opaque;
  500. if (!h)
  501. return; /* can happen when opening the url fails */
  502. /* close rist or srt URLs ; free URLContext */
  503. if (is_rist) {
  504. err = librist_close(h);
  505. } else {
  506. err = libsrt_close(h);
  507. }
  508. av_freep(&h->priv_data);
  509. av_freep(h);
  510. /* close custom avio_context for srt or rist */
  511. avio_flush(stream->s);
  512. stream->s->opaque = NULL;
  513. av_freep(&stream->s->buffer);
  514. avio_context_free(&stream->s);
  515. if (err)
  516. info("[ffmpeg mpegts muxer]: Error closing URL %s",
  517. stream->ff_data.config.url);
  518. }
  519. void ffmpeg_mpegts_data_free(struct ffmpeg_output *stream,
  520. struct ffmpeg_data *data)
  521. {
  522. if (data->initialized)
  523. av_write_trailer(data->output);
  524. if (data->video)
  525. close_video(data);
  526. if (data->audio_infos) {
  527. close_audio(data);
  528. free(data->audio_infos);
  529. }
  530. if (data->output) {
  531. if (is_rist(stream) || is_srt(stream)) {
  532. close_mpegts_url(stream, is_rist(stream));
  533. } else {
  534. avio_close(data->output->pb);
  535. }
  536. avformat_free_context(data->output);
  537. data->video = NULL;
  538. data->audio_infos = NULL;
  539. data->output = NULL;
  540. data->num_audio_streams = 0;
  541. }
  542. if (data->last_error)
  543. bfree(data->last_error);
  544. memset(data, 0, sizeof(struct ffmpeg_data));
  545. }
  546. static inline const char *safe_str(const char *s)
  547. {
  548. if (s == NULL)
  549. return "(NULL)";
  550. else
  551. return s;
  552. }
  553. bool ffmpeg_mpegts_data_init(struct ffmpeg_output *stream,
  554. struct ffmpeg_data *data,
  555. struct ffmpeg_cfg *config)
  556. {
  557. memset(data, 0, sizeof(struct ffmpeg_data));
  558. data->config = *config;
  559. data->num_audio_streams = config->audio_mix_count;
  560. data->audio_tracks = config->audio_tracks;
  561. if (!config->url || !*config->url)
  562. return false;
  563. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
  564. av_register_all();
  565. #endif
  566. avformat_network_init();
  567. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  568. AVOutputFormat *output_format;
  569. #else
  570. const AVOutputFormat *output_format;
  571. #endif
  572. output_format = av_guess_format("mpegts", NULL, "video/M2PT");
  573. if (output_format == NULL) {
  574. ffmpeg_mpegts_log_error(LOG_WARNING, data,
  575. "Couldn't set output format to mpegts");
  576. goto fail;
  577. } else {
  578. info("Output format name and long_name: %s, %s",
  579. output_format->name ? output_format->name : "unknown",
  580. output_format->long_name ? output_format->long_name
  581. : "unknown");
  582. }
  583. avformat_alloc_output_context2(&data->output, output_format, NULL,
  584. data->config.url);
  585. if (!data->output) {
  586. ffmpeg_mpegts_log_error(LOG_WARNING, data,
  587. "Couldn't create avformat context");
  588. goto fail;
  589. }
  590. return true;
  591. fail:
  592. warn("ffmpeg_data_init failed");
  593. return false;
  594. }
  595. /* ------------------------------------------------------------------------- */
  596. static inline bool stopping(struct ffmpeg_output *output)
  597. {
  598. return os_atomic_load_bool(&output->stopping);
  599. }
  600. static const char *ffmpeg_mpegts_getname(void *unused)
  601. {
  602. UNUSED_PARAMETER(unused);
  603. return obs_module_text("FFmpegMpegts");
  604. }
  605. static void ffmpeg_mpegts_log_callback(void *param, int level,
  606. const char *format, va_list args)
  607. {
  608. if (level <= AV_LOG_INFO)
  609. blogva(LOG_DEBUG, format, args);
  610. UNUSED_PARAMETER(param);
  611. }
  612. static void *ffmpeg_mpegts_create(obs_data_t *settings, obs_output_t *output)
  613. {
  614. struct ffmpeg_output *data = bzalloc(sizeof(struct ffmpeg_output));
  615. pthread_mutex_init_value(&data->write_mutex);
  616. data->output = output;
  617. if (pthread_mutex_init(&data->write_mutex, NULL) != 0)
  618. goto fail;
  619. if (os_event_init(&data->stop_event, OS_EVENT_TYPE_AUTO) != 0)
  620. goto fail;
  621. if (os_sem_init(&data->write_sem, 0) != 0)
  622. goto fail;
  623. av_log_set_callback(ffmpeg_mpegts_log_callback);
  624. UNUSED_PARAMETER(settings);
  625. return data;
  626. fail:
  627. pthread_mutex_destroy(&data->write_mutex);
  628. os_event_destroy(data->stop_event);
  629. bfree(data);
  630. return NULL;
  631. }
  632. static void ffmpeg_mpegts_full_stop(void *data);
  633. static void ffmpeg_mpegts_deactivate(struct ffmpeg_output *output);
  634. static void ffmpeg_mpegts_destroy(void *data)
  635. {
  636. struct ffmpeg_output *output = data;
  637. if (output) {
  638. if (output->connecting)
  639. pthread_join(output->start_thread, NULL);
  640. ffmpeg_mpegts_full_stop(output);
  641. pthread_mutex_destroy(&output->write_mutex);
  642. os_sem_destroy(output->write_sem);
  643. os_event_destroy(output->stop_event);
  644. bfree(data);
  645. }
  646. }
  647. static uint64_t get_packet_sys_dts(struct ffmpeg_output *output,
  648. AVPacket *packet)
  649. {
  650. struct ffmpeg_data *data = &output->ff_data;
  651. uint64_t pause_offset = obs_output_get_pause_offset(output->output);
  652. uint64_t start_ts;
  653. AVRational time_base;
  654. if (data->video && data->video->index == packet->stream_index) {
  655. time_base = data->video->time_base;
  656. start_ts = output->video_start_ts;
  657. } else {
  658. time_base = data->audio_infos[0].stream->time_base;
  659. start_ts = output->audio_start_ts;
  660. }
  661. return start_ts + pause_offset +
  662. (uint64_t)av_rescale_q(packet->dts, time_base,
  663. (AVRational){1, 1000000000});
  664. }
  665. static int mpegts_process_packet(struct ffmpeg_output *output)
  666. {
  667. AVPacket *packet = NULL;
  668. int ret = 0;
  669. pthread_mutex_lock(&output->write_mutex);
  670. if (output->packets.num) {
  671. packet = output->packets.array[0];
  672. da_erase(output->packets, 0);
  673. }
  674. pthread_mutex_unlock(&output->write_mutex);
  675. if (!packet)
  676. return 0;
  677. //blog(LOG_DEBUG,
  678. // "size = %d, flags = %lX, stream = %d, "
  679. // "packets queued: %lu",
  680. // packet->size, packet->flags, packet->stream_index,
  681. // output->packets.num);
  682. if (stopping(output)) {
  683. uint64_t sys_ts = get_packet_sys_dts(output, packet);
  684. if (sys_ts >= output->stop_ts) {
  685. ret = 0;
  686. goto end;
  687. }
  688. }
  689. output->total_bytes += packet->size;
  690. uint8_t *buf = packet->data;
  691. ret = av_interleaved_write_frame(output->ff_data.output, packet);
  692. av_freep(&buf);
  693. if (ret < 0) {
  694. ffmpeg_mpegts_log_error(
  695. LOG_WARNING, &output->ff_data,
  696. "process_packet: Error writing packet: %s",
  697. av_err2str(ret));
  698. /* Treat "Invalid data found when processing input" and
  699. * "Invalid argument" as non-fatal */
  700. if (ret == AVERROR_INVALIDDATA || ret == -EINVAL) {
  701. ret = 0;
  702. }
  703. }
  704. end:
  705. av_packet_free(&packet);
  706. return ret;
  707. }
  708. static void *write_thread(void *data)
  709. {
  710. struct ffmpeg_output *output = data;
  711. while (os_sem_wait(output->write_sem) == 0) {
  712. /* check to see if shutting down */
  713. if (os_event_try(output->stop_event) == 0)
  714. break;
  715. int ret = mpegts_process_packet(output);
  716. if (ret != 0) {
  717. int code = OBS_OUTPUT_DISCONNECTED;
  718. pthread_detach(output->write_thread);
  719. output->write_thread_active = false;
  720. if (ret == -ENOSPC)
  721. code = OBS_OUTPUT_NO_SPACE;
  722. obs_output_signal_stop(output->output, code);
  723. ffmpeg_mpegts_deactivate(output);
  724. break;
  725. }
  726. }
  727. os_atomic_set_bool(&output->active, false);
  728. return NULL;
  729. }
  730. static bool get_extradata(struct ffmpeg_output *stream)
  731. {
  732. struct ffmpeg_data *ff_data = &stream->ff_data;
  733. /* get extradata for av headers from encoders */
  734. if (!get_video_headers(stream, ff_data))
  735. return false;
  736. for (int i = 0; i < ff_data->num_audio_streams; i++) {
  737. if (!get_audio_headers(stream, ff_data, i))
  738. return false;
  739. }
  740. return true;
  741. }
  742. /* set ffmpeg_config & init write_thread & capture */
  743. static bool set_config(struct ffmpeg_output *stream)
  744. {
  745. struct ffmpeg_cfg config;
  746. bool success;
  747. int ret;
  748. int code;
  749. /* 1. Get URL/username/password from service & set format + mime-type. */
  750. obs_service_t *service;
  751. service = obs_output_get_service(stream->output);
  752. if (!service)
  753. return false;
  754. config.url = obs_service_get_url(service);
  755. config.username = obs_service_get_username(service);
  756. config.password = obs_service_get_password(service);
  757. config.key = obs_service_get_key(service);
  758. config.format_name = "mpegts";
  759. config.format_mime_type = "video/M2PT";
  760. /* 2. video settings */
  761. // 2.a) set video format from obs to FFmpeg
  762. video_t *video = obs_output_video(stream->output);
  763. config.format =
  764. obs_to_ffmpeg_video_format(video_output_get_format(video));
  765. if (config.format == AV_PIX_FMT_NONE) {
  766. blog(LOG_WARNING,
  767. "Invalid pixel format used for mpegts output");
  768. return false;
  769. }
  770. // 2.b) set colorspace, color_range & transfer characteristic (from voi)
  771. const struct video_output_info *voi = video_output_get_info(video);
  772. config.color_range = voi->range == VIDEO_RANGE_FULL ? AVCOL_RANGE_JPEG
  773. : AVCOL_RANGE_MPEG;
  774. config.colorspace = format_is_yuv(voi->format) ? AVCOL_SPC_BT709
  775. : AVCOL_SPC_RGB;
  776. switch (voi->colorspace) {
  777. case VIDEO_CS_601:
  778. config.color_primaries = AVCOL_PRI_SMPTE170M;
  779. config.color_trc = AVCOL_TRC_SMPTE170M;
  780. config.colorspace = AVCOL_SPC_SMPTE170M;
  781. break;
  782. case VIDEO_CS_DEFAULT:
  783. case VIDEO_CS_709:
  784. config.color_primaries = AVCOL_PRI_BT709;
  785. config.color_trc = AVCOL_TRC_BT709;
  786. config.colorspace = AVCOL_SPC_BT709;
  787. break;
  788. case VIDEO_CS_SRGB:
  789. config.color_primaries = AVCOL_PRI_BT709;
  790. config.color_trc = AVCOL_TRC_IEC61966_2_1;
  791. config.colorspace = AVCOL_SPC_BT709;
  792. break;
  793. case VIDEO_CS_2100_PQ:
  794. config.color_primaries = AVCOL_PRI_BT2020;
  795. config.color_trc = AVCOL_TRC_SMPTE2084;
  796. config.colorspace = AVCOL_SPC_BT2020_NCL;
  797. break;
  798. case VIDEO_CS_2100_HLG:
  799. config.color_primaries = AVCOL_PRI_BT2020;
  800. config.color_trc = AVCOL_TRC_ARIB_STD_B67;
  801. config.colorspace = AVCOL_SPC_BT2020_NCL;
  802. }
  803. // 2.c) set width & height
  804. config.width = (int)obs_output_get_width(stream->output);
  805. config.height = (int)obs_output_get_height(stream->output);
  806. config.scale_width = config.width;
  807. config.scale_height = config.height;
  808. // 2.d) set video codec & id from video encoder
  809. obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output);
  810. config.video_encoder = obs_encoder_get_codec(vencoder);
  811. if (strcmp(config.video_encoder, "h264") == 0)
  812. config.video_encoder_id = AV_CODEC_ID_H264;
  813. else
  814. config.video_encoder_id = AV_CODEC_ID_AV1;
  815. // 2.e) set video bitrate & gop through video encoder settings
  816. obs_data_t *settings = obs_encoder_get_settings(vencoder);
  817. config.video_bitrate = (int)obs_data_get_int(settings, "bitrate");
  818. int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
  819. config.gop_size = keyint_sec ? keyint_sec * voi->fps_num / voi->fps_den
  820. : 250;
  821. obs_data_release(settings);
  822. /* 3. Audio settings */
  823. // 3.a) set audio codec & id from audio encoder
  824. obs_encoder_t *aencoder =
  825. obs_output_get_audio_encoder(stream->output, 0);
  826. config.audio_encoder = obs_encoder_get_codec(aencoder);
  827. if (strcmp(config.audio_encoder, "aac") == 0)
  828. config.audio_encoder_id = AV_CODEC_ID_AAC;
  829. else if (strcmp(config.audio_encoder, "opus") == 0)
  830. config.audio_encoder_id = AV_CODEC_ID_OPUS;
  831. // 3.b) get audio bitrate from the audio encoder.
  832. settings = obs_encoder_get_settings(aencoder);
  833. config.audio_bitrate = (int)obs_data_get_int(settings, "bitrate");
  834. obs_data_release(settings);
  835. // 3.c set audio frame size
  836. config.frame_size = (int)obs_encoder_get_frame_size(aencoder);
  837. // 3.d) set the number of tracks
  838. // The UI for multiple tracks is not written for streaming outputs.
  839. // When it is, modify write_packet & uncomment :
  840. // config.audio_tracks = (int)obs_output_get_mixers(stream->output);
  841. // config.audio_mix_count = get_audio_mix_count(config.audio_tracks);
  842. config.audio_tracks = 1;
  843. config.audio_mix_count = 1;
  844. /* 4. Muxer & protocol settings */
  845. // This requires some UI to be written for the output.
  846. // at the service level unless one can load the output in the settings/stream screen.
  847. settings = obs_output_get_settings(stream->output);
  848. obs_data_set_default_string(settings, "muxer_settings", "");
  849. config.muxer_settings = obs_data_get_string(settings, "muxer_settings");
  850. obs_data_release(settings);
  851. config.protocol_settings = "";
  852. /* 5. unused ffmpeg codec settings */
  853. config.video_settings = "";
  854. config.audio_settings = "";
  855. success = ffmpeg_mpegts_data_init(stream, &stream->ff_data, &config);
  856. if (!success) {
  857. if (stream->ff_data.last_error) {
  858. obs_output_set_last_error(stream->output,
  859. stream->ff_data.last_error);
  860. }
  861. ffmpeg_mpegts_data_free(stream, &stream->ff_data);
  862. code = OBS_OUTPUT_INVALID_STREAM;
  863. goto fail;
  864. }
  865. struct ffmpeg_data *ff_data = &stream->ff_data;
  866. if (!stream->got_headers) {
  867. if (!init_streams(stream, ff_data)) {
  868. error("mpegts avstream failed to be created");
  869. code = OBS_OUTPUT_INVALID_STREAM;
  870. goto fail;
  871. }
  872. code = open_output_file(stream, ff_data);
  873. if (code != 0) {
  874. error("Failed to open the url");
  875. goto fail;
  876. }
  877. av_dump_format(ff_data->output, 0, NULL, 1);
  878. }
  879. if (!obs_output_can_begin_data_capture(stream->output, 0))
  880. return false;
  881. if (!obs_output_initialize_encoders(stream->output, 0))
  882. return false;
  883. ret = pthread_create(&stream->write_thread, NULL, write_thread, stream);
  884. if (ret != 0) {
  885. ffmpeg_mpegts_log_error(
  886. LOG_WARNING, &stream->ff_data,
  887. "ffmpeg_output_start: Failed to create write "
  888. "thread.");
  889. code = OBS_OUTPUT_ERROR;
  890. goto fail;
  891. }
  892. os_atomic_set_bool(&stream->active, true);
  893. stream->write_thread_active = true;
  894. stream->total_bytes = 0;
  895. obs_output_begin_data_capture(stream->output, 0);
  896. return true;
  897. fail:
  898. obs_output_signal_stop(stream->output, code);
  899. ffmpeg_mpegts_full_stop(stream);
  900. return false;
  901. }
  902. static void *start_thread(void *data)
  903. {
  904. struct ffmpeg_output *output = data;
  905. set_config(output);
  906. output->connecting = false;
  907. return NULL;
  908. }
  909. static bool ffmpeg_mpegts_start(void *data)
  910. {
  911. struct ffmpeg_output *output = data;
  912. int ret;
  913. if (output->connecting)
  914. return false;
  915. os_atomic_set_bool(&output->stopping, false);
  916. output->audio_start_ts = 0;
  917. output->video_start_ts = 0;
  918. output->total_bytes = 0;
  919. output->got_headers = false;
  920. ret = pthread_create(&output->start_thread, NULL, start_thread, output);
  921. return (output->connecting = (ret == 0));
  922. }
  923. static void ffmpeg_mpegts_full_stop(void *data)
  924. {
  925. struct ffmpeg_output *output = data;
  926. if (output->active) {
  927. obs_output_end_data_capture(output->output);
  928. ffmpeg_mpegts_deactivate(output);
  929. }
  930. }
  931. static void ffmpeg_mpegts_stop(void *data, uint64_t ts)
  932. {
  933. struct ffmpeg_output *output = data;
  934. if (output->active) {
  935. if (ts > 0) {
  936. output->stop_ts = ts;
  937. os_atomic_set_bool(&output->stopping, true);
  938. }
  939. ffmpeg_mpegts_full_stop(output);
  940. } else {
  941. obs_output_signal_stop(output->output, OBS_OUTPUT_SUCCESS);
  942. }
  943. }
  944. static void ffmpeg_mpegts_deactivate(struct ffmpeg_output *output)
  945. {
  946. if (output->write_thread_active) {
  947. os_event_signal(output->stop_event);
  948. os_sem_post(output->write_sem);
  949. pthread_join(output->write_thread, NULL);
  950. output->write_thread_active = false;
  951. }
  952. pthread_mutex_lock(&output->write_mutex);
  953. for (size_t i = 0; i < output->packets.num; i++)
  954. av_packet_free(output->packets.array + i);
  955. da_free(output->packets);
  956. pthread_mutex_unlock(&output->write_mutex);
  957. ffmpeg_mpegts_data_free(output, &output->ff_data);
  958. }
  959. static uint64_t ffmpeg_mpegts_total_bytes(void *data)
  960. {
  961. struct ffmpeg_output *output = data;
  962. return output->total_bytes;
  963. }
  964. static inline int64_t rescale_ts2(AVStream *stream, AVRational codec_time_base,
  965. int64_t val)
  966. {
  967. return av_rescale_q_rnd(val / codec_time_base.num, codec_time_base,
  968. stream->time_base,
  969. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  970. }
  971. /* Convert obs encoder_packet to FFmpeg AVPacket and write to circular buffer
  972. * where it will be processed in the write_thread by process_packet.
  973. */
  974. void mpegts_write_packet(struct ffmpeg_output *stream,
  975. struct encoder_packet *encpacket)
  976. {
  977. if (stopping(stream) || !stream->ff_data.video ||
  978. !stream->ff_data.video_ctx || !stream->ff_data.audio_infos)
  979. return;
  980. if (!stream->ff_data.audio_infos[encpacket->track_idx].stream)
  981. return;
  982. bool is_video = encpacket->type == OBS_ENCODER_VIDEO;
  983. AVStream *avstream =
  984. is_video ? stream->ff_data.video
  985. : stream->ff_data.audio_infos[encpacket->track_idx]
  986. .stream;
  987. AVPacket *packet = NULL;
  988. const AVRational codec_time_base =
  989. is_video ? stream->ff_data.video_ctx->time_base
  990. : stream->ff_data.audio_infos[encpacket->track_idx]
  991. .ctx->time_base;
  992. packet = av_packet_alloc();
  993. packet->data = av_memdup(encpacket->data, (int)encpacket->size);
  994. if (packet->data == NULL) {
  995. error("Couldn't allocate packet data");
  996. goto fail;
  997. }
  998. packet->size = (int)encpacket->size;
  999. packet->stream_index = avstream->id;
  1000. packet->pts = rescale_ts2(avstream, codec_time_base, encpacket->pts);
  1001. packet->dts = rescale_ts2(avstream, codec_time_base, encpacket->dts);
  1002. if (encpacket->keyframe)
  1003. packet->flags = AV_PKT_FLAG_KEY;
  1004. pthread_mutex_lock(&stream->write_mutex);
  1005. da_push_back(stream->packets, &packet);
  1006. pthread_mutex_unlock(&stream->write_mutex);
  1007. os_sem_post(stream->write_sem);
  1008. return;
  1009. fail:
  1010. av_packet_free(&packet);
  1011. }
  1012. static bool write_header(struct ffmpeg_output *stream, struct ffmpeg_data *data)
  1013. {
  1014. AVDictionary *dict = NULL;
  1015. int ret;
  1016. /* get mpegts muxer settings (can be used with rist, srt, rtp, etc ... */
  1017. if ((ret = av_dict_parse_string(&dict, data->config.muxer_settings, "=",
  1018. " ", 0))) {
  1019. ffmpeg_mpegts_log_error(
  1020. LOG_WARNING, data,
  1021. "Failed to parse muxer settings: %s, %s",
  1022. data->config.muxer_settings, av_err2str(ret));
  1023. av_dict_free(&dict);
  1024. return false;
  1025. }
  1026. if (av_dict_count(dict) > 0) {
  1027. struct dstr str = {0};
  1028. AVDictionaryEntry *entry = NULL;
  1029. while ((entry = av_dict_get(dict, "", entry,
  1030. AV_DICT_IGNORE_SUFFIX)))
  1031. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  1032. info("Using muxer settings: %s", str.array);
  1033. dstr_free(&str);
  1034. }
  1035. /* Allocate the stream private data and write the stream header. */
  1036. ret = avformat_write_header(data->output, &dict);
  1037. if (ret < 0) {
  1038. ffmpeg_mpegts_log_error(
  1039. LOG_WARNING, data,
  1040. "Error setting stream header for '%s': %s",
  1041. data->config.url, av_err2str(ret));
  1042. return false;
  1043. }
  1044. /* Log invalid muxer settings. */
  1045. if (av_dict_count(dict) > 0) {
  1046. struct dstr str = {0};
  1047. AVDictionaryEntry *entry = NULL;
  1048. while ((entry = av_dict_get(dict, "", entry,
  1049. AV_DICT_IGNORE_SUFFIX)))
  1050. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  1051. info("[ffmpeg mpegts muxer]: Invalid mpegts muxer settings: %s",
  1052. str.array);
  1053. dstr_free(&str);
  1054. }
  1055. av_dict_free(&dict);
  1056. return true;
  1057. }
  1058. static void ffmpeg_mpegts_data(void *data, struct encoder_packet *packet)
  1059. {
  1060. struct ffmpeg_output *stream = data;
  1061. struct ffmpeg_data *ff_data = &stream->ff_data;
  1062. int code;
  1063. if (!stream->got_headers) {
  1064. if (get_extradata(stream)) {
  1065. stream->got_headers = true;
  1066. } else {
  1067. warn("Failed to retrieve headers");
  1068. code = OBS_OUTPUT_INVALID_STREAM;
  1069. goto fail;
  1070. }
  1071. if (!write_header(stream, ff_data)) {
  1072. error("Failed to write headers");
  1073. code = OBS_OUTPUT_INVALID_STREAM;
  1074. goto fail;
  1075. }
  1076. av_dump_format(ff_data->output, 0, NULL, 1);
  1077. ff_data->initialized = true;
  1078. }
  1079. if (!stream->active)
  1080. return;
  1081. /* encoder failure */
  1082. if (!packet) {
  1083. obs_output_signal_stop(stream->output, OBS_OUTPUT_ENCODE_ERROR);
  1084. ffmpeg_mpegts_deactivate(stream);
  1085. return;
  1086. }
  1087. if (stopping(stream)) {
  1088. if (packet->sys_dts_usec >= (int64_t)stream->stop_ts) {
  1089. ffmpeg_mpegts_deactivate(stream);
  1090. return;
  1091. }
  1092. }
  1093. mpegts_write_packet(stream, packet);
  1094. return;
  1095. fail:
  1096. obs_output_signal_stop(stream->output, code);
  1097. ffmpeg_mpegts_full_stop(stream);
  1098. }
  1099. static obs_properties_t *ffmpeg_mpegts_properties(void *unused)
  1100. {
  1101. UNUSED_PARAMETER(unused);
  1102. obs_properties_t *props = obs_properties_create();
  1103. obs_properties_add_text(props, "path", obs_module_text("FilePath"),
  1104. OBS_TEXT_DEFAULT);
  1105. return props;
  1106. }
  1107. struct obs_output_info ffmpeg_mpegts_muxer = {
  1108. .id = "ffmpeg_mpegts_muxer",
  1109. .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK |
  1110. OBS_OUTPUT_SERVICE,
  1111. .protocols = "SRT;RIST",
  1112. #ifdef ENABLE_HEVC
  1113. .encoded_video_codecs = "h264;hevc",
  1114. #else
  1115. .encoded_video_codecs = "h264",
  1116. #endif
  1117. .encoded_audio_codecs = "aac;opus",
  1118. .get_name = ffmpeg_mpegts_getname,
  1119. .create = ffmpeg_mpegts_create,
  1120. .destroy = ffmpeg_mpegts_destroy,
  1121. .start = ffmpeg_mpegts_start,
  1122. .stop = ffmpeg_mpegts_stop,
  1123. .encoded_packet = ffmpeg_mpegts_data,
  1124. .get_total_bytes = ffmpeg_mpegts_total_bytes,
  1125. .get_properties = ffmpeg_mpegts_properties,
  1126. };