fpvcopy.c 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. # include <stdio.h>
  2. # include <stdint.h>
  3. # include <stdlib.h>
  4. # include <unistd.h>
  5. # include <string.h>
  6. # include <errno.h>
  7. # include <sys/types.h>
  8. # include <sys/stat.h>
  9. # include <fcntl.h>
  10. # include <arpa/inet.h>
  11. # include <getopt.h>
  12. struct fpv
  13. {
  14. uint32_t len;
  15. uint8_t type;
  16. uint32_t ms;
  17. uint8_t pad[8];
  18. } __attribute__((packed));
  19. static const char short_options[] = "s:e:";
  20. static const struct option long_options[] =
  21. {
  22. { "start", required_argument, NULL, 's' },
  23. { "end", required_argument, NULL, 'e' },
  24. { 0, 0, NULL, 0 }
  25. };
  26. static int opt_s = 0;
  27. static int opt_e = -1;
  28. size_t in(int fd, uint8_t *data, size_t len)
  29. {
  30. int res = 0;
  31. while (len > 0) {
  32. size_t n = read(fd, data, len);
  33. if (n > 0) {
  34. len -= n;
  35. data += n;
  36. res += n;
  37. } else {
  38. if (n < 0) {
  39. if (errno != EAGAIN) {
  40. printf("read: %s\n", strerror(errno));
  41. } else {
  42. continue;
  43. }
  44. }
  45. break;
  46. }
  47. }
  48. return res;
  49. }
  50. int main(int argc, char *argv[])
  51. {
  52. struct fpv fpv;
  53. static uint8_t data[8 * 1024 * 1024];
  54. int i;
  55. for (;;) {
  56. int c;
  57. if ((c = getopt_long_only(argc, argv, short_options, long_options, &i)) == -1) {
  58. break;
  59. }
  60. switch (c) {
  61. case 's':
  62. opt_s = atoi(optarg);
  63. break;
  64. case 'e':
  65. opt_e = atoi(optarg);
  66. break;
  67. case 0:
  68. break;
  69. default:
  70. return 1;
  71. }
  72. }
  73. if ((argc - optind) < 1) {
  74. return 1;
  75. }
  76. for (i = 0; (optind + i) < argc; i++) {
  77. int fd = open(argv[optind + i], O_RDONLY);
  78. fprintf(stderr, "%s\n", argv[optind + i]);
  79. if (fd >= 0) {
  80. while (1) {
  81. if (in(fd, (uint8_t*)&fpv, sizeof(fpv)) < 0) {
  82. break;
  83. }
  84. if (in(fd, data, fpv.len) < 0) {
  85. break;
  86. }
  87. if (opt_e > 0 && fpv.ms >= opt_e) {
  88. break;
  89. }
  90. if (fpv.ms >= opt_s) {
  91. fpv.ms -= opt_s;
  92. write(fileno(stdout), &fpv, sizeof(fpv));
  93. write(fileno(stdout), data, fpv.len);
  94. }
  95. }
  96. close(fd);
  97. }
  98. }
  99. return 0;
  100. }