ffmpeg_linux.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include <assert.h>
  2. #include <stdio.h>
  3. #include <stdint.h>
  4. #include <string.h>
  5. #include <errno.h>
  6. #include <sys/types.h>
  7. #include <sys/wait.h>
  8. #include <unistd.h>
  9. #define READ_END 0
  10. #define WRITE_END 1
  11. int ffmpeg_start_rendering(size_t width, size_t height, size_t fps)
  12. {
  13. int pipefd[2];
  14. if (pipe(pipefd) < 0) {
  15. fprintf(stderr, "ERROR: could not create a pipe: %s\n", strerror(errno));
  16. return -1;
  17. }
  18. pid_t child = fork();
  19. if (child < 0) {
  20. fprintf(stderr, "ERROR: could not fork a child: %s\n", strerror(errno));
  21. return -1;
  22. }
  23. if (child == 0) {
  24. if (dup2(pipefd[READ_END], STDIN_FILENO) < 0) {
  25. fprintf(stderr, "ERROR: could not reopen read end of pipe as stdin: %s\n", strerror(errno));
  26. return -1;
  27. }
  28. close(pipefd[WRITE_END]);
  29. char resolution[64];
  30. snprintf(resolution, sizeof(resolution), "%zux%zu", width, height);
  31. char framerate[64];
  32. snprintf(framerate, sizeof(framerate), "%zu", fps);
  33. int ret = execlp("ffmpeg",
  34. "ffmpeg",
  35. "-loglevel", "verbose",
  36. "-y",
  37. "-f", "rawvideo",
  38. "-pix_fmt", "rgba",
  39. "-s", resolution,
  40. "-r", framerate,
  41. "-i", "-",
  42. "-c:v", "libx264",
  43. "-vb", "2500k",
  44. "-c:a", "aac",
  45. "-ab", "200k",
  46. "-pix_fmt", "yuv420p",
  47. "output.mp4",
  48. NULL
  49. );
  50. if (ret < 0) {
  51. fprintf(stderr, "ERROR: could not run ffmpeg as a child process: %s\n", strerror(errno));
  52. return -1;
  53. }
  54. assert(0 && "unreachable");
  55. }
  56. close(pipefd[READ_END]);
  57. return pipefd[WRITE_END];
  58. }
  59. void ffmpeg_end_rendering(int pipe)
  60. {
  61. close(pipe);
  62. wait(NULL);
  63. }
  64. void ffmpeg_send_frame(int pipe, void *data, size_t width, size_t height)
  65. {
  66. write(pipe, data, sizeof(uint32_t)*width*height);
  67. }
  68. void ffmpeg_send_frame_flipped(int pipe, void *data, size_t width, size_t height)
  69. {
  70. for (size_t y = height; y > 0; --y) {
  71. write(pipe, (uint32_t*)data + (y - 1)*width, sizeof(uint32_t)*width);
  72. }
  73. }