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.

90 lines
2.3KB

  1. #include "mpeg-ps.h"
  2. #include "hls-m3u8.h"
  3. #include "hls-media.h"
  4. #include "hls-param.h"
  5. #include "flv-proto.h"
  6. #include "flv-reader.h"
  7. #include "flv-demuxer.h"
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <assert.h>
  12. static int hls_handler(void* m3u8, const void* data, size_t bytes, int64_t pts, int64_t dts, int64_t duration)
  13. {
  14. static int64_t s_dts = -1;
  15. int discontinue = -1 != s_dts ? 0 : (dts > s_dts + HLS_DURATION / 2 ? 1 : 0);
  16. s_dts = dts;
  17. static int i = 0;
  18. char name[128] = {0};
  19. snprintf(name, sizeof(name) - 1, "%d.ts", i++);
  20. hls_m3u8_add((hls_m3u8_t*)m3u8, name, pts, duration, discontinue);
  21. FILE* fp = fopen(name, "wb");
  22. if(fp)
  23. {
  24. fwrite(data, 1, bytes, fp);
  25. fclose(fp);
  26. }
  27. return 0;
  28. }
  29. static int flv_handler(void* param, int codec, const void* data, size_t bytes, uint32_t pts, uint32_t dts, int flags)
  30. {
  31. hls_media_t* hls = (hls_media_t*)param;
  32. switch (codec)
  33. {
  34. case FLV_AUDIO_AAC:
  35. return hls_media_input(hls, PSI_STREAM_AAC, data, bytes, pts, dts, 0);
  36. case FLV_AUDIO_MP3:
  37. return hls_media_input(hls, PSI_STREAM_MP3, data, bytes, pts, dts, 0);
  38. case FLV_VIDEO_H264:
  39. return hls_media_input(hls, PSI_STREAM_H264, data, bytes, pts, dts, flags ? HLS_FLAGS_KEYFRAME : 0);
  40. case FLV_VIDEO_H265:
  41. return hls_media_input(hls, PSI_STREAM_H265, data, bytes, pts, dts, flags ? HLS_FLAGS_KEYFRAME : 0);
  42. default:
  43. // nothing to do
  44. return 0;
  45. }
  46. }
  47. void hls_segmenter_flv(const char* file)
  48. {
  49. hls_m3u8_t* m3u = hls_m3u8_create(0, 3);
  50. hls_media_t* hls = hls_media_create(HLS_DURATION * 1000, hls_handler, m3u);
  51. void* flv = flv_reader_create(file);
  52. flv_demuxer_t* demuxer = flv_demuxer_create(flv_handler, hls);
  53. int r, type;
  54. size_t taglen;
  55. uint32_t timestamp;
  56. static char data[2 * 1024 * 1024];
  57. while (1 == flv_reader_read(flv, &type, &timestamp, &taglen, data, sizeof(data)))
  58. {
  59. r = flv_demuxer_input(demuxer, type, data, taglen, timestamp);
  60. assert(0 == r);
  61. }
  62. // write m3u8 file
  63. hls_media_input(hls, PSI_STREAM_H264, NULL, 0, 0, 0, 0);
  64. hls_m3u8_playlist(m3u, 1, data, sizeof(data));
  65. FILE* fp = fopen("playlist.m3u8", "wb");
  66. if(fp)
  67. {
  68. fwrite(data, 1, strlen(data), fp);
  69. fclose(fp);
  70. }
  71. flv_demuxer_destroy(demuxer);
  72. flv_reader_destroy(flv);
  73. hls_media_destroy(hls);
  74. hls_m3u8_destroy(m3u);
  75. }