ftl-stream.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  1. /******************************************************************************
  2. Copyright (C) 2017 by Quinn Damerell <[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 <obs-avc.h>
  16. #include <util/platform.h>
  17. #include <util/deque.h>
  18. #include <util/dstr.h>
  19. #include <util/threading.h>
  20. #include <inttypes.h>
  21. #include "ftl.h"
  22. #include "flv-mux.h"
  23. #include "net-if.h"
  24. #ifdef _WIN32
  25. #include <Iphlpapi.h>
  26. #else
  27. #include <sys/ioctl.h>
  28. #define INFINITE 0xFFFFFFFF
  29. #endif
  30. #define do_log(level, format, ...) \
  31. blog(level, "[ftl stream: '%s'] " format, \
  32. obs_output_get_name(stream->output), ##__VA_ARGS__)
  33. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  34. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  35. #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
  36. #define OPT_DROP_THRESHOLD "drop_threshold_ms"
  37. #define OPT_MAX_SHUTDOWN_TIME_SEC "max_shutdown_time_sec"
  38. #define OPT_BIND_IP "bind_ip"
  39. #define FTL_URL_PROTOCOL "ftl://"
  40. typedef struct _nalu_t {
  41. int len;
  42. int dts_usec;
  43. int send_marker_bit;
  44. uint8_t *data;
  45. } nalu_t;
  46. typedef struct _frame_of_nalus_t {
  47. nalu_t nalus[100];
  48. int total;
  49. int complete_frame;
  50. } frame_of_nalus_t;
  51. struct ftl_stream {
  52. obs_output_t *output;
  53. pthread_mutex_t packets_mutex;
  54. struct deque packets;
  55. bool sent_headers;
  56. int64_t frames_sent;
  57. volatile bool connecting;
  58. pthread_t connect_thread;
  59. pthread_t status_thread;
  60. volatile bool active;
  61. volatile bool disconnected;
  62. volatile bool encode_error;
  63. pthread_t send_thread;
  64. int max_shutdown_time_sec;
  65. os_sem_t *send_sem;
  66. os_event_t *stop_event;
  67. uint64_t stop_ts;
  68. uint64_t shutdown_timeout_ts;
  69. struct dstr path;
  70. uint32_t channel_id;
  71. struct dstr username, password;
  72. struct dstr encoder_name;
  73. struct dstr bind_ip;
  74. /* frame drop variables */
  75. int64_t drop_threshold_usec;
  76. int64_t pframe_drop_threshold_usec;
  77. int min_priority;
  78. float congestion;
  79. int64_t last_dts_usec;
  80. uint64_t total_bytes_sent;
  81. uint64_t dropped_frames;
  82. uint64_t last_nack_count;
  83. ftl_handle_t ftl_handle;
  84. ftl_ingest_params_t params;
  85. int peak_kbps;
  86. uint32_t scale_width, scale_height, width, height;
  87. frame_of_nalus_t coded_pic_buffer;
  88. };
  89. static int init_connect(struct ftl_stream *stream);
  90. static void *connect_thread(void *data);
  91. static void *status_thread(void *data);
  92. static int _ftl_error_to_obs_error(int status);
  93. static const char *ftl_stream_getname(void *unused)
  94. {
  95. UNUSED_PARAMETER(unused);
  96. return obs_module_text("FTLStream");
  97. }
  98. static inline size_t num_buffered_packets(struct ftl_stream *stream);
  99. static inline void free_packets(struct ftl_stream *stream)
  100. {
  101. size_t num_packets;
  102. pthread_mutex_lock(&stream->packets_mutex);
  103. num_packets = num_buffered_packets(stream);
  104. if (num_packets)
  105. info("Freeing %d remaining packets", (int)num_packets);
  106. while (stream->packets.size) {
  107. struct encoder_packet packet;
  108. deque_pop_front(&stream->packets, &packet, sizeof(packet));
  109. obs_encoder_packet_release(&packet);
  110. }
  111. pthread_mutex_unlock(&stream->packets_mutex);
  112. }
  113. static inline bool stopping(struct ftl_stream *stream)
  114. {
  115. return os_event_try(stream->stop_event) != EAGAIN;
  116. }
  117. static inline bool connecting(struct ftl_stream *stream)
  118. {
  119. return os_atomic_load_bool(&stream->connecting);
  120. }
  121. static inline bool active(struct ftl_stream *stream)
  122. {
  123. return os_atomic_load_bool(&stream->active);
  124. }
  125. static inline bool disconnected(struct ftl_stream *stream)
  126. {
  127. return os_atomic_load_bool(&stream->disconnected);
  128. }
  129. static void ftl_stream_destroy(void *data)
  130. {
  131. struct ftl_stream *stream = data;
  132. ftl_status_t status_code;
  133. info("ftl_stream_destroy");
  134. if (stopping(stream) && !connecting(stream)) {
  135. pthread_join(stream->send_thread, NULL);
  136. } else if (connecting(stream) || active(stream)) {
  137. if (stream->connecting) {
  138. info("wait for connect_thread to terminate");
  139. pthread_join(stream->status_thread, NULL);
  140. pthread_join(stream->connect_thread, NULL);
  141. info("wait for connect_thread to terminate: done");
  142. }
  143. stream->stop_ts = 0;
  144. os_event_signal(stream->stop_event);
  145. if (active(stream)) {
  146. os_sem_post(stream->send_sem);
  147. obs_output_end_data_capture(stream->output);
  148. pthread_join(stream->send_thread, NULL);
  149. }
  150. }
  151. info("ingest destroy");
  152. status_code = ftl_ingest_destroy(&stream->ftl_handle);
  153. if (status_code != FTL_SUCCESS) {
  154. info("Failed to destroy from ingest %d", status_code);
  155. }
  156. if (stream) {
  157. free_packets(stream);
  158. dstr_free(&stream->path);
  159. dstr_free(&stream->username);
  160. dstr_free(&stream->password);
  161. dstr_free(&stream->encoder_name);
  162. dstr_free(&stream->bind_ip);
  163. os_event_destroy(stream->stop_event);
  164. os_sem_destroy(stream->send_sem);
  165. pthread_mutex_destroy(&stream->packets_mutex);
  166. deque_free(&stream->packets);
  167. bfree(stream);
  168. }
  169. }
  170. static void *ftl_stream_create(obs_data_t *settings, obs_output_t *output)
  171. {
  172. struct ftl_stream *stream = bzalloc(sizeof(struct ftl_stream));
  173. info("ftl_stream_create");
  174. stream->output = output;
  175. pthread_mutex_init_value(&stream->packets_mutex);
  176. stream->peak_kbps = -1;
  177. ftl_init();
  178. if (pthread_mutex_init(&stream->packets_mutex, NULL) != 0) {
  179. goto fail;
  180. }
  181. if (os_event_init(&stream->stop_event, OS_EVENT_TYPE_MANUAL) != 0) {
  182. goto fail;
  183. }
  184. stream->coded_pic_buffer.total = 0;
  185. stream->coded_pic_buffer.complete_frame = 0;
  186. UNUSED_PARAMETER(settings);
  187. return stream;
  188. fail:
  189. return NULL;
  190. }
  191. static void ftl_stream_stop(void *data, uint64_t ts)
  192. {
  193. struct ftl_stream *stream = data;
  194. info("ftl_stream_stop");
  195. if (stopping(stream) && ts != 0) {
  196. return;
  197. }
  198. if (connecting(stream)) {
  199. pthread_join(stream->status_thread, NULL);
  200. pthread_join(stream->connect_thread, NULL);
  201. }
  202. stream->stop_ts = ts / 1000ULL;
  203. if (ts) {
  204. stream->shutdown_timeout_ts =
  205. ts +
  206. (uint64_t)stream->max_shutdown_time_sec * 1000000000ULL;
  207. }
  208. if (active(stream)) {
  209. os_event_signal(stream->stop_event);
  210. if (stream->stop_ts == 0)
  211. os_sem_post(stream->send_sem);
  212. } else {
  213. obs_output_signal_stop(stream->output, OBS_OUTPUT_SUCCESS);
  214. }
  215. }
  216. static inline bool get_next_packet(struct ftl_stream *stream,
  217. struct encoder_packet *packet)
  218. {
  219. bool new_packet = false;
  220. pthread_mutex_lock(&stream->packets_mutex);
  221. if (stream->packets.size) {
  222. deque_pop_front(&stream->packets, packet,
  223. sizeof(struct encoder_packet));
  224. new_packet = true;
  225. }
  226. pthread_mutex_unlock(&stream->packets_mutex);
  227. return new_packet;
  228. }
  229. static int avc_get_video_frame(struct ftl_stream *stream,
  230. struct encoder_packet *packet, bool is_header)
  231. {
  232. int consumed = 0;
  233. int len = (int)packet->size;
  234. nalu_t *nalu;
  235. unsigned char *video_stream = packet->data;
  236. while ((size_t)consumed < packet->size) {
  237. size_t total_max = sizeof(stream->coded_pic_buffer.nalus) /
  238. sizeof(stream->coded_pic_buffer.nalus[0]);
  239. if ((size_t)stream->coded_pic_buffer.total >= total_max) {
  240. warn("ERROR: cannot continue, nalu buffers are full");
  241. return -1;
  242. }
  243. nalu = &stream->coded_pic_buffer
  244. .nalus[stream->coded_pic_buffer.total];
  245. if (is_header) {
  246. if (consumed == 0) {
  247. //first 6 bytes are some obs header with part
  248. //of the sps
  249. video_stream += 6;
  250. consumed += 6;
  251. } else {
  252. //another spacer byte of 0x1
  253. video_stream += 1;
  254. consumed += 1;
  255. }
  256. len = video_stream[0] << 8 | video_stream[1];
  257. video_stream += 2;
  258. consumed += 2;
  259. } else {
  260. len = video_stream[0] << 24 | video_stream[1] << 16 |
  261. video_stream[2] << 8 | video_stream[3];
  262. if ((size_t)len > (packet->size - (size_t)consumed)) {
  263. warn("ERROR: got len of %d but packet only "
  264. "has %d left",
  265. len, (int)(packet->size - consumed));
  266. }
  267. consumed += 4;
  268. video_stream += 4;
  269. }
  270. consumed += len;
  271. uint8_t nalu_type = video_stream[0] & 0x1F;
  272. uint8_t nri = (video_stream[0] >> 5) & 0x3;
  273. if ((nalu_type != 12 && nalu_type != 6 && nalu_type != 9) ||
  274. nri) {
  275. nalu->data = video_stream;
  276. nalu->len = len;
  277. nalu->send_marker_bit = 0;
  278. stream->coded_pic_buffer.total++;
  279. }
  280. video_stream += len;
  281. }
  282. if (!is_header) {
  283. size_t idx = stream->coded_pic_buffer.total - 1;
  284. stream->coded_pic_buffer.nalus[idx].send_marker_bit = 1;
  285. }
  286. return 0;
  287. }
  288. static int send_packet(struct ftl_stream *stream, struct encoder_packet *packet,
  289. bool is_header)
  290. {
  291. int bytes_sent = 0;
  292. int ret = 0;
  293. if (packet->type == OBS_ENCODER_VIDEO) {
  294. stream->coded_pic_buffer.total = 0;
  295. avc_get_video_frame(stream, packet, is_header);
  296. int i;
  297. for (i = 0; i < stream->coded_pic_buffer.total; i++) {
  298. nalu_t *nalu = &stream->coded_pic_buffer.nalus[i];
  299. bytes_sent += ftl_ingest_send_media_dts(
  300. &stream->ftl_handle, FTL_VIDEO_DATA,
  301. packet->dts_usec, nalu->data, nalu->len,
  302. nalu->send_marker_bit);
  303. if (nalu->send_marker_bit) {
  304. stream->frames_sent++;
  305. }
  306. }
  307. } else if (packet->type == OBS_ENCODER_AUDIO) {
  308. bytes_sent += ftl_ingest_send_media_dts(
  309. &stream->ftl_handle, FTL_AUDIO_DATA, packet->dts_usec,
  310. packet->data, (int)packet->size, 0);
  311. } else {
  312. warn("Got packet type %d", packet->type);
  313. }
  314. if (is_header) {
  315. bfree(packet->data);
  316. } else {
  317. obs_encoder_packet_release(packet);
  318. }
  319. stream->total_bytes_sent += bytes_sent;
  320. return ret;
  321. }
  322. static void set_peak_bitrate(struct ftl_stream *stream)
  323. {
  324. int speedtest_kbps = 15000;
  325. int speedtest_duration = 1000;
  326. speed_test_t results;
  327. ftl_status_t status_code;
  328. status_code = ftl_ingest_speed_test_ex(&stream->ftl_handle,
  329. speedtest_kbps,
  330. speedtest_duration, &results);
  331. float percent_lost = 0;
  332. if (status_code == FTL_SUCCESS) {
  333. percent_lost = (float)results.lost_pkts * 100.f /
  334. (float)results.pkts_sent;
  335. } else {
  336. warn("Speed test failed with: %s",
  337. ftl_status_code_to_string(status_code));
  338. }
  339. // Get what the user set the encoding bitrate to.
  340. obs_encoder_t *video_encoder =
  341. obs_output_get_video_encoder(stream->output);
  342. obs_data_t *video_settings = obs_encoder_get_settings(video_encoder);
  343. int user_desired_bitrate =
  344. (int)obs_data_get_int(video_settings, "bitrate");
  345. obs_data_release(video_settings);
  346. // Report the results.
  347. info("Speed test completed: User desired bitrate %d, Peak kbps %d, "
  348. "initial rtt %d, "
  349. "final rtt %d, %3.2f lost packets",
  350. user_desired_bitrate, results.peak_kbps, results.starting_rtt,
  351. results.ending_rtt, percent_lost);
  352. // We still want to set the peak to about 1.2x what the target bitrate is,
  353. // even if the speed test reported it should be lower. If we don't, FTL
  354. // will queue data on the client and start adding latency. If the internet
  355. // connection really can't handle the bitrate the user will see either lost frame
  356. // and recovered frame counts go up, which is reflect in the dropped_frames count.
  357. stream->peak_kbps = stream->params.peak_kbps =
  358. user_desired_bitrate * 12 / 10;
  359. ftl_ingest_update_params(&stream->ftl_handle, &stream->params);
  360. }
  361. static inline bool send_headers(struct ftl_stream *stream, int64_t dts_usec);
  362. static inline bool can_shutdown_stream(struct ftl_stream *stream,
  363. struct encoder_packet *packet)
  364. {
  365. uint64_t cur_time = os_gettime_ns();
  366. bool timeout = cur_time >= stream->shutdown_timeout_ts;
  367. if (timeout)
  368. info("Stream shutdown timeout reached (%d second(s))",
  369. stream->max_shutdown_time_sec);
  370. return timeout || packet->sys_dts_usec >= (int64_t)stream->stop_ts;
  371. }
  372. static void *send_thread(void *data)
  373. {
  374. struct ftl_stream *stream = data;
  375. ftl_status_t status_code;
  376. os_set_thread_name("ftl-stream: send_thread");
  377. while (os_sem_wait(stream->send_sem) == 0) {
  378. struct encoder_packet packet;
  379. if (stopping(stream) && stream->stop_ts == 0) {
  380. break;
  381. }
  382. if (!get_next_packet(stream, &packet))
  383. continue;
  384. if (stopping(stream)) {
  385. if (can_shutdown_stream(stream, &packet)) {
  386. obs_encoder_packet_release(&packet);
  387. break;
  388. }
  389. }
  390. /* sends sps/pps on every key frame as this is typically
  391. * required for webrtc */
  392. if (packet.keyframe) {
  393. if (!send_headers(stream, packet.dts_usec)) {
  394. os_atomic_set_bool(&stream->disconnected, true);
  395. break;
  396. }
  397. }
  398. if (send_packet(stream, &packet, false) < 0) {
  399. os_atomic_set_bool(&stream->disconnected, true);
  400. break;
  401. }
  402. }
  403. bool encode_error = os_atomic_load_bool(&stream->encode_error);
  404. if (disconnected(stream)) {
  405. info("Disconnected from %s", stream->path.array);
  406. } else if (encode_error) {
  407. info("Encoder error, disconnecting");
  408. } else {
  409. info("User stopped the stream");
  410. }
  411. if (!stopping(stream)) {
  412. pthread_detach(stream->send_thread);
  413. obs_output_signal_stop(stream->output, OBS_OUTPUT_DISCONNECTED);
  414. } else if (encode_error) {
  415. obs_output_signal_stop(stream->output, OBS_OUTPUT_ENCODE_ERROR);
  416. } else {
  417. obs_output_end_data_capture(stream->output);
  418. }
  419. info("ingest disconnect");
  420. status_code = ftl_ingest_disconnect(&stream->ftl_handle);
  421. if (status_code != FTL_SUCCESS) {
  422. printf("Failed to disconnect from ingest %d", status_code);
  423. }
  424. free_packets(stream);
  425. os_event_reset(stream->stop_event);
  426. os_atomic_set_bool(&stream->active, false);
  427. stream->sent_headers = false;
  428. return NULL;
  429. }
  430. static bool send_video_header(struct ftl_stream *stream, int64_t dts_usec)
  431. {
  432. obs_output_t *context = stream->output;
  433. obs_encoder_t *vencoder = obs_output_get_video_encoder(context);
  434. uint8_t *header;
  435. size_t size;
  436. struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO,
  437. .timebase_den = 1,
  438. .keyframe = true,
  439. .dts_usec = dts_usec};
  440. if (!obs_encoder_get_extra_data(vencoder, &header, &size))
  441. return false;
  442. packet.size = obs_parse_avc_header(&packet.data, header, size);
  443. return send_packet(stream, &packet, true) >= 0;
  444. }
  445. static inline bool send_headers(struct ftl_stream *stream, int64_t dts_usec)
  446. {
  447. stream->sent_headers = true;
  448. if (!send_video_header(stream, dts_usec))
  449. return false;
  450. return true;
  451. }
  452. static inline bool reset_semaphore(struct ftl_stream *stream)
  453. {
  454. os_sem_destroy(stream->send_sem);
  455. return os_sem_init(&stream->send_sem, 0) == 0;
  456. }
  457. #ifdef _WIN32
  458. #define socklen_t int
  459. #endif
  460. static int init_send(struct ftl_stream *stream)
  461. {
  462. int ret;
  463. reset_semaphore(stream);
  464. ret = pthread_create(&stream->send_thread, NULL, send_thread, stream);
  465. if (ret != 0) {
  466. warn("Failed to create send thread");
  467. return OBS_OUTPUT_ERROR;
  468. }
  469. os_atomic_set_bool(&stream->active, true);
  470. obs_output_begin_data_capture(stream->output, 0);
  471. return OBS_OUTPUT_SUCCESS;
  472. }
  473. static int try_connect(struct ftl_stream *stream)
  474. {
  475. ftl_status_t status_code;
  476. if (dstr_is_empty(&stream->path)) {
  477. warn("URL is empty");
  478. return OBS_OUTPUT_BAD_PATH;
  479. }
  480. info("Connecting to FTL Ingest URL %s...", stream->path.array);
  481. stream->width = (int)obs_output_get_width(stream->output);
  482. stream->height = (int)obs_output_get_height(stream->output);
  483. status_code = ftl_ingest_connect(&stream->ftl_handle);
  484. if (status_code != FTL_SUCCESS) {
  485. if (status_code == FTL_BAD_OR_INVALID_STREAM_KEY) {
  486. blog(LOG_ERROR, "Invalid Key (%s)",
  487. ftl_status_code_to_string(status_code));
  488. return OBS_OUTPUT_INVALID_STREAM;
  489. } else {
  490. warn("Ingest connect failed with: %s (%d)",
  491. ftl_status_code_to_string(status_code),
  492. status_code);
  493. return _ftl_error_to_obs_error(status_code);
  494. }
  495. }
  496. info("Connection to %s successful", stream->path.array);
  497. // Always get the peak bitrate when we are starting.
  498. set_peak_bitrate(stream);
  499. pthread_create(&stream->status_thread, NULL, status_thread, stream);
  500. return init_send(stream);
  501. }
  502. static bool ftl_stream_start(void *data)
  503. {
  504. struct ftl_stream *stream = data;
  505. info("ftl_stream_start");
  506. // Mixer doesn't support bframes. So force them off.
  507. obs_encoder_t *video_encoder =
  508. obs_output_get_video_encoder(stream->output);
  509. obs_data_t *video_settings = obs_encoder_get_settings(video_encoder);
  510. obs_data_set_int(video_settings, "bf", 0);
  511. obs_data_release(video_settings);
  512. if (!obs_output_can_begin_data_capture(stream->output, 0)) {
  513. return false;
  514. }
  515. if (!obs_output_initialize_encoders(stream->output, 0)) {
  516. return false;
  517. }
  518. stream->frames_sent = 0;
  519. os_atomic_set_bool(&stream->connecting, true);
  520. return pthread_create(&stream->connect_thread, NULL, connect_thread,
  521. stream) == 0;
  522. }
  523. static inline bool add_packet(struct ftl_stream *stream,
  524. struct encoder_packet *packet)
  525. {
  526. deque_push_back(&stream->packets, packet,
  527. sizeof(struct encoder_packet));
  528. return true;
  529. }
  530. static inline size_t num_buffered_packets(struct ftl_stream *stream)
  531. {
  532. return stream->packets.size / sizeof(struct encoder_packet);
  533. }
  534. static void drop_frames(struct ftl_stream *stream, const char *name,
  535. int highest_priority, bool pframes)
  536. {
  537. UNUSED_PARAMETER(pframes);
  538. struct deque new_buf = {0};
  539. int num_frames_dropped = 0;
  540. #ifdef _DEBUG
  541. int start_packets = (int)num_buffered_packets(stream);
  542. #else
  543. UNUSED_PARAMETER(name);
  544. #endif
  545. deque_reserve(&new_buf, sizeof(struct encoder_packet) * 8);
  546. while (stream->packets.size) {
  547. struct encoder_packet packet;
  548. deque_pop_front(&stream->packets, &packet, sizeof(packet));
  549. /* do not drop audio data or video keyframes */
  550. if (packet.type == OBS_ENCODER_AUDIO ||
  551. packet.drop_priority >= highest_priority) {
  552. deque_push_back(&new_buf, &packet, sizeof(packet));
  553. } else {
  554. num_frames_dropped++;
  555. obs_encoder_packet_release(&packet);
  556. }
  557. }
  558. deque_free(&stream->packets);
  559. stream->packets = new_buf;
  560. if (stream->min_priority < highest_priority)
  561. stream->min_priority = highest_priority;
  562. if (!num_frames_dropped)
  563. return;
  564. stream->dropped_frames += num_frames_dropped;
  565. #ifdef _DEBUG
  566. debug("Dropped %s, prev packet count: %d, new packet count: %d", name,
  567. start_packets, (int)num_buffered_packets(stream));
  568. #endif
  569. }
  570. static bool find_first_video_packet(struct ftl_stream *stream,
  571. struct encoder_packet *first)
  572. {
  573. size_t count = stream->packets.size / sizeof(*first);
  574. for (size_t i = 0; i < count; i++) {
  575. struct encoder_packet *cur =
  576. deque_data(&stream->packets, i * sizeof(*first));
  577. if (cur->type == OBS_ENCODER_VIDEO && !cur->keyframe) {
  578. *first = *cur;
  579. return true;
  580. }
  581. }
  582. return false;
  583. }
  584. static void check_to_drop_frames(struct ftl_stream *stream, bool pframes)
  585. {
  586. struct encoder_packet first;
  587. int64_t buffer_duration_usec;
  588. size_t num_packets = num_buffered_packets(stream);
  589. const char *name = pframes ? "p-frames" : "b-frames";
  590. int priority = pframes ? OBS_NAL_PRIORITY_HIGHEST
  591. : OBS_NAL_PRIORITY_HIGH;
  592. int64_t drop_threshold = pframes ? stream->pframe_drop_threshold_usec
  593. : stream->drop_threshold_usec;
  594. if (num_packets < 5) {
  595. if (!pframes)
  596. stream->congestion = 0.0f;
  597. return;
  598. }
  599. if (!find_first_video_packet(stream, &first))
  600. return;
  601. /* if the amount of time stored in the buffered packets waiting to be
  602. * sent is higher than threshold, drop frames */
  603. buffer_duration_usec = stream->last_dts_usec - first.dts_usec;
  604. if (!pframes) {
  605. stream->congestion =
  606. (float)buffer_duration_usec / (float)drop_threshold;
  607. }
  608. if (buffer_duration_usec > drop_threshold) {
  609. debug("buffer_duration_usec: %" PRId64, buffer_duration_usec);
  610. drop_frames(stream, name, priority, pframes);
  611. }
  612. }
  613. static bool add_video_packet(struct ftl_stream *stream,
  614. struct encoder_packet *packet)
  615. {
  616. check_to_drop_frames(stream, false);
  617. check_to_drop_frames(stream, true);
  618. /* if currently dropping frames, drop packets until it reaches the
  619. * desired priority */
  620. if (packet->priority < stream->min_priority) {
  621. stream->dropped_frames++;
  622. return false;
  623. } else {
  624. stream->min_priority = 0;
  625. }
  626. stream->last_dts_usec = packet->dts_usec;
  627. return add_packet(stream, packet);
  628. }
  629. static void ftl_stream_data(void *data, struct encoder_packet *packet)
  630. {
  631. struct ftl_stream *stream = data;
  632. struct encoder_packet new_packet;
  633. bool added_packet = false;
  634. if (disconnected(stream) || !active(stream))
  635. return;
  636. /* encoder failure */
  637. if (!packet) {
  638. os_atomic_set_bool(&stream->encode_error, true);
  639. os_sem_post(stream->send_sem);
  640. return;
  641. }
  642. if (packet->type == OBS_ENCODER_VIDEO)
  643. obs_parse_avc_packet(&new_packet, packet);
  644. else
  645. obs_encoder_packet_ref(&new_packet, packet);
  646. pthread_mutex_lock(&stream->packets_mutex);
  647. if (!disconnected(stream)) {
  648. added_packet = (packet->type == OBS_ENCODER_VIDEO)
  649. ? add_video_packet(stream, &new_packet)
  650. : add_packet(stream, &new_packet);
  651. }
  652. pthread_mutex_unlock(&stream->packets_mutex);
  653. if (added_packet)
  654. os_sem_post(stream->send_sem);
  655. else
  656. obs_encoder_packet_release(&new_packet);
  657. }
  658. static void ftl_stream_defaults(obs_data_t *defaults)
  659. {
  660. UNUSED_PARAMETER(defaults);
  661. }
  662. static obs_properties_t *ftl_stream_properties(void *unused)
  663. {
  664. UNUSED_PARAMETER(unused);
  665. obs_properties_t *props = obs_properties_create();
  666. obs_properties_add_int(props, "peak_bitrate_kbps",
  667. obs_module_text("FTLStream.PeakBitrate"), 1000,
  668. 10000, 500);
  669. return props;
  670. }
  671. static uint64_t ftl_stream_total_bytes_sent(void *data)
  672. {
  673. struct ftl_stream *stream = data;
  674. return stream->total_bytes_sent;
  675. }
  676. static int ftl_stream_dropped_frames(void *data)
  677. {
  678. struct ftl_stream *stream = data;
  679. return (int)stream->dropped_frames;
  680. }
  681. static float ftl_stream_congestion(void *data)
  682. {
  683. struct ftl_stream *stream = data;
  684. return stream->min_priority > 0 ? 1.0f : stream->congestion;
  685. }
  686. enum ret_type {
  687. RET_CONTINUE,
  688. RET_BREAK,
  689. RET_EXIT,
  690. };
  691. static enum ret_type ftl_event(struct ftl_stream *stream,
  692. ftl_status_msg_t status)
  693. {
  694. if (status.msg.event.type != FTL_STATUS_EVENT_TYPE_DISCONNECTED)
  695. return RET_CONTINUE;
  696. info("Disconnected from ingest with reason: %s",
  697. ftl_status_code_to_string(status.msg.event.error_code));
  698. if (status.msg.event.reason == FTL_STATUS_EVENT_REASON_API_REQUEST) {
  699. return RET_BREAK;
  700. }
  701. //tell OBS and it will trigger a reconnection
  702. blog(LOG_WARNING, "Reconnecting to Ingest");
  703. obs_output_signal_stop(stream->output, OBS_OUTPUT_DISCONNECTED);
  704. reset_semaphore(stream);
  705. return RET_EXIT;
  706. }
  707. static void *status_thread(void *data)
  708. {
  709. struct ftl_stream *stream = data;
  710. ftl_status_msg_t status;
  711. ftl_status_t status_code;
  712. while (!disconnected(stream)) {
  713. status_code = ftl_ingest_get_status(&stream->ftl_handle,
  714. &status, 1000);
  715. if (status_code == FTL_STATUS_TIMEOUT ||
  716. status_code == FTL_QUEUE_EMPTY) {
  717. continue;
  718. } else if (status_code == FTL_NOT_INITIALIZED) {
  719. break;
  720. }
  721. if (status.type == FTL_STATUS_EVENT) {
  722. enum ret_type ret_type = ftl_event(stream, status);
  723. if (ret_type == RET_EXIT)
  724. return NULL;
  725. else if (ret_type == RET_BREAK)
  726. break;
  727. } else if (status.type == FTL_STATUS_LOG) {
  728. blog(LOG_INFO, "[%d] %s", status.msg.log.log_level,
  729. status.msg.log.string);
  730. } else if (status.type == FTL_STATUS_VIDEO_PACKETS) {
  731. ftl_packet_stats_msg_t *p = &status.msg.pkt_stats;
  732. // Report nack requests as dropped frames
  733. stream->dropped_frames +=
  734. p->nack_reqs - stream->last_nack_count;
  735. stream->last_nack_count = p->nack_reqs;
  736. int log_level = p->nack_reqs > 0 ? LOG_INFO : LOG_DEBUG;
  737. blog(log_level,
  738. "Avg packet send per second %3.1f, "
  739. "total nack requests %d",
  740. (float)p->sent * 1000.f / p->period,
  741. (int)p->nack_reqs);
  742. } else if (status.type == FTL_STATUS_VIDEO_PACKETS_INSTANT) {
  743. ftl_packet_stats_instant_msg_t *p =
  744. &status.msg.ipkt_stats;
  745. int log_level = p->avg_rtt > 20 ? LOG_INFO : LOG_DEBUG;
  746. blog(log_level,
  747. "avg transmit delay %dms "
  748. "(min: %d, max: %d), "
  749. "avg rtt %dms (min: %d, max: %d)",
  750. p->avg_xmit_delay, p->min_xmit_delay,
  751. p->max_xmit_delay, p->avg_rtt, p->min_rtt,
  752. p->max_rtt);
  753. } else if (status.type == FTL_STATUS_VIDEO) {
  754. ftl_video_frame_stats_msg_t *v =
  755. &status.msg.video_stats;
  756. int log_level = v->queue_fullness > 0 ? LOG_INFO
  757. : LOG_DEBUG;
  758. blog(log_level,
  759. "Queue an average of %3.2f fps "
  760. "(%3.1f kbps), "
  761. "sent an average of %3.2f fps "
  762. "(%3.1f kbps), "
  763. "queue fullness %d, "
  764. "max frame size %d",
  765. (float)v->frames_queued * 1000.f / v->period,
  766. (float)v->bytes_queued / v->period * 8,
  767. (float)v->frames_sent * 1000.f / v->period,
  768. (float)v->bytes_sent / v->period * 8,
  769. v->queue_fullness, v->max_frame_size);
  770. } else {
  771. blog(LOG_DEBUG,
  772. "Status: Got Status message of type "
  773. "%d",
  774. status.type);
  775. }
  776. }
  777. blog(LOG_DEBUG, "status_thread: Exited");
  778. pthread_detach(stream->status_thread);
  779. return NULL;
  780. }
  781. static void *connect_thread(void *data)
  782. {
  783. struct ftl_stream *stream = data;
  784. int ret;
  785. os_set_thread_name("ftl-stream: connect_thread");
  786. blog(LOG_WARNING, "ftl-stream: connect thread");
  787. ret = init_connect(stream);
  788. if (ret != OBS_OUTPUT_SUCCESS) {
  789. obs_output_signal_stop(stream->output, ret);
  790. return NULL;
  791. }
  792. ret = try_connect(stream);
  793. if (ret != OBS_OUTPUT_SUCCESS) {
  794. obs_output_signal_stop(stream->output, ret);
  795. info("Connection to %s failed: %d", stream->path.array, ret);
  796. }
  797. if (!stopping(stream))
  798. pthread_detach(stream->connect_thread);
  799. os_atomic_set_bool(&stream->connecting, false);
  800. return NULL;
  801. }
  802. static int init_connect(struct ftl_stream *stream)
  803. {
  804. obs_service_t *service;
  805. obs_data_t *settings;
  806. const char *bind_ip, *key, *ingest_url;
  807. ftl_status_t status_code;
  808. info("init_connect");
  809. if (stopping(stream))
  810. pthread_join(stream->send_thread, NULL);
  811. free_packets(stream);
  812. service = obs_output_get_service(stream->output);
  813. if (!service) {
  814. return OBS_OUTPUT_ERROR;
  815. }
  816. os_atomic_set_bool(&stream->disconnected, false);
  817. os_atomic_set_bool(&stream->encode_error, false);
  818. stream->total_bytes_sent = 0;
  819. stream->dropped_frames = 0;
  820. stream->min_priority = 0;
  821. settings = obs_output_get_settings(stream->output);
  822. obs_encoder_t *video_encoder =
  823. obs_output_get_video_encoder(stream->output);
  824. obs_data_t *video_settings = obs_encoder_get_settings(video_encoder);
  825. ingest_url = obs_service_get_connect_info(
  826. service, OBS_SERVICE_CONNECT_INFO_SERVER_URL);
  827. if (strncmp(ingest_url, FTL_URL_PROTOCOL, strlen(FTL_URL_PROTOCOL)) ==
  828. 0) {
  829. dstr_copy(&stream->path, ingest_url + strlen(FTL_URL_PROTOCOL));
  830. } else {
  831. dstr_copy(&stream->path, ingest_url);
  832. }
  833. key = obs_service_get_connect_info(service,
  834. OBS_SERVICE_CONNECT_INFO_STREAM_KEY);
  835. int target_bitrate = (int)obs_data_get_int(video_settings, "bitrate");
  836. int peak_bitrate = (int)((float)target_bitrate * 1.1f);
  837. //minimum overshoot tolerance of 10%
  838. if (peak_bitrate < target_bitrate) {
  839. peak_bitrate = target_bitrate;
  840. }
  841. stream->params.stream_key = (char *)key;
  842. stream->params.video_codec = FTL_VIDEO_H264;
  843. stream->params.audio_codec = FTL_AUDIO_OPUS;
  844. stream->params.ingest_hostname = stream->path.array;
  845. stream->params.vendor_name = "OBS Studio";
  846. stream->params.vendor_version = obs_get_version_string();
  847. stream->params.peak_kbps = stream->peak_kbps < 0 ? 0
  848. : stream->peak_kbps;
  849. //not required when using ftl_ingest_send_media_dts
  850. stream->params.fps_num = 0;
  851. stream->params.fps_den = 0;
  852. status_code = ftl_ingest_create(&stream->ftl_handle, &stream->params);
  853. if (status_code != FTL_SUCCESS) {
  854. if (status_code == FTL_BAD_OR_INVALID_STREAM_KEY) {
  855. blog(LOG_ERROR, "Invalid Key (%s)",
  856. ftl_status_code_to_string(status_code));
  857. return OBS_OUTPUT_INVALID_STREAM;
  858. } else {
  859. blog(LOG_ERROR, "Failed to create ingest handle (%s)",
  860. ftl_status_code_to_string(status_code));
  861. return OBS_OUTPUT_ERROR;
  862. }
  863. }
  864. dstr_copy(&stream->username,
  865. obs_service_get_connect_info(
  866. service, OBS_SERVICE_CONNECT_INFO_USERNAME));
  867. dstr_copy(&stream->password,
  868. obs_service_get_connect_info(
  869. service, OBS_SERVICE_CONNECT_INFO_PASSWORD));
  870. dstr_depad(&stream->path);
  871. stream->drop_threshold_usec =
  872. (int64_t)obs_data_get_int(settings, OPT_DROP_THRESHOLD) * 1000;
  873. stream->max_shutdown_time_sec =
  874. (int)obs_data_get_int(settings, OPT_MAX_SHUTDOWN_TIME_SEC);
  875. bind_ip = obs_data_get_string(settings, OPT_BIND_IP);
  876. dstr_copy(&stream->bind_ip, bind_ip);
  877. obs_data_release(settings);
  878. obs_data_release(video_settings);
  879. return OBS_OUTPUT_SUCCESS;
  880. }
  881. // Returns 0 on success
  882. static int _ftl_error_to_obs_error(int status)
  883. {
  884. /* Map FTL errors to OBS errors */
  885. switch (status) {
  886. case FTL_SUCCESS:
  887. return OBS_OUTPUT_SUCCESS;
  888. case FTL_SOCKET_NOT_CONNECTED:
  889. case FTL_MALLOC_FAILURE:
  890. case FTL_INTERNAL_ERROR:
  891. case FTL_CONFIG_ERROR:
  892. case FTL_NOT_ACTIVE_STREAM:
  893. case FTL_NOT_CONNECTED:
  894. case FTL_ALREADY_CONNECTED:
  895. case FTL_STATUS_TIMEOUT:
  896. case FTL_QUEUE_FULL:
  897. case FTL_STATUS_WAITING_FOR_KEY_FRAME:
  898. case FTL_QUEUE_EMPTY:
  899. case FTL_NOT_INITIALIZED:
  900. return OBS_OUTPUT_ERROR;
  901. case FTL_BAD_REQUEST:
  902. case FTL_DNS_FAILURE:
  903. case FTL_CONNECT_ERROR:
  904. case FTL_UNSUPPORTED_MEDIA_TYPE:
  905. case FTL_OLD_VERSION:
  906. case FTL_UNAUTHORIZED:
  907. case FTL_AUDIO_SSRC_COLLISION:
  908. case FTL_VIDEO_SSRC_COLLISION:
  909. case FTL_STREAM_REJECTED:
  910. case FTL_BAD_OR_INVALID_STREAM_KEY:
  911. case FTL_CHANNEL_IN_USE:
  912. case FTL_REGION_UNSUPPORTED:
  913. case FTL_GAME_BLOCKED:
  914. return OBS_OUTPUT_CONNECT_FAILED;
  915. case FTL_NO_MEDIA_TIMEOUT:
  916. return OBS_OUTPUT_DISCONNECTED;
  917. case FTL_USER_DISCONNECT:
  918. return OBS_OUTPUT_SUCCESS;
  919. case FTL_UNKNOWN_ERROR_CODE:
  920. default:
  921. /* Unknown FTL error */
  922. return OBS_OUTPUT_ERROR;
  923. }
  924. }
  925. struct obs_output_info ftl_output_info = {
  926. .id = "ftl_output",
  927. .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_SERVICE,
  928. .protocols = "FTL",
  929. .encoded_video_codecs = "h264",
  930. .encoded_audio_codecs = "opus",
  931. .get_name = ftl_stream_getname,
  932. .create = ftl_stream_create,
  933. .destroy = ftl_stream_destroy,
  934. .start = ftl_stream_start,
  935. .stop = ftl_stream_stop,
  936. .encoded_packet = ftl_stream_data,
  937. .get_defaults = ftl_stream_defaults,
  938. .get_properties = ftl_stream_properties,
  939. .get_total_bytes = ftl_stream_total_bytes_sent,
  940. .get_congestion = ftl_stream_congestion,
  941. .get_dropped_frames = ftl_stream_dropped_frames,
  942. };