You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.1KB

  1. #include "mpeg-ps.h"
  2. #include "mpeg-ts.h"
  3. #include <assert.h>
  4. #include <string.h>
  5. #include <stdio.h>
  6. #include <map>
  7. static void* ts_alloc(void* /*param*/, size_t bytes)
  8. {
  9. static char s_buffer[188];
  10. assert(bytes <= sizeof(s_buffer));
  11. return s_buffer;
  12. }
  13. static void ts_free(void* /*param*/, void* /*packet*/)
  14. {
  15. return;
  16. }
  17. static int ts_write(void* param, const void* packet, size_t bytes)
  18. {
  19. return 1 == fwrite(packet, bytes, 1, (FILE*)param) ? 0 : ferror((FILE*)param);
  20. }
  21. inline const char* ts_type(int type)
  22. {
  23. switch (type)
  24. {
  25. case PSI_STREAM_MP3: return "MP3";
  26. case PSI_STREAM_AAC: return "AAC";
  27. case PSI_STREAM_H264: return "H264";
  28. case PSI_STREAM_H265: return "H265";
  29. default: return "*";
  30. }
  31. }
  32. static int ts_stream(void* ts, int codecid)
  33. {
  34. static std::map<int, int> streams;
  35. std::map<int, int>::const_iterator it = streams.find(codecid);
  36. if (streams.end() != it)
  37. return it->second;
  38. int i = mpeg_ts_add_stream(ts, codecid, NULL, 0);
  39. streams[codecid] = i;
  40. return i;
  41. }
  42. static int on_ts_packet(void* ts, int program, int stream, int avtype, int flags, int64_t pts, int64_t dts, const void* data, size_t bytes)
  43. {
  44. printf("[%s] pts: %08lu, dts: %08lu%s\n", ts_type(avtype), (unsigned long)pts, (unsigned long)dts, flags ? " [I]":"");
  45. return mpeg_ts_write(ts, ts_stream(ts, avtype), flags, pts, dts, data, bytes);
  46. }
  47. static void mpeg_ts_file(const char* file, void* muxer)
  48. {
  49. unsigned char ptr[188];
  50. struct ts_demuxer_t *ts;
  51. FILE* fp = fopen(file, "rb");
  52. ts = ts_demuxer_create(on_ts_packet, muxer);
  53. while (1 == fread(ptr, sizeof(ptr), 1, fp))
  54. {
  55. ts_demuxer_input(ts, ptr, sizeof(ptr));
  56. }
  57. ts_demuxer_flush(ts);
  58. ts_demuxer_destroy(ts);
  59. fclose(fp);
  60. }
  61. //mpeg_ts_test("test/fileSequence0.ts", "test/apple.ts")
  62. void mpeg_ts_test(const char* input)
  63. {
  64. char output[256] = { 0 };
  65. snprintf(output, sizeof(output) - 1, "%s.ts", input);
  66. struct mpeg_ts_func_t tshandler;
  67. tshandler.alloc = ts_alloc;
  68. tshandler.write = ts_write;
  69. tshandler.free = ts_free;
  70. FILE* fp = fopen(output, "wb");
  71. void* ts = mpeg_ts_create(&tshandler, fp);
  72. mpeg_ts_file(input, ts);
  73. mpeg_ts_destroy(ts);
  74. fclose(fp);
  75. }