encoder_aac.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #ifndef ENCODER_AAC
  2. #define ENCODER_AAC
  3. #include <atomic>
  4. #include <condition_variable>
  5. #include <functional>
  6. #include <mutex>
  7. #include <thread>
  8. #include "headers_ffmpeg.h"
  9. #include "ring_buffer.h"
  10. //#define SAVE_AAC
  11. namespace am {
  12. typedef std::function<void(AVPacket *packet)> cb_aac_data;
  13. typedef std::function<void(int)> cb_aac_error;
  14. class encoder_aac
  15. {
  16. public:
  17. encoder_aac();
  18. ~encoder_aac();
  19. int init(int nb_channels, int sample_rate, AVSampleFormat fmt, int bit_rate);
  20. int get_extradata_size();
  21. const uint8_t *get_extradata();
  22. int get_nb_samples();
  23. int start();
  24. void stop();
  25. int put(const uint8_t *data, int data_len, AVFrame *frame);
  26. inline void registe_cb(cb_aac_data on_data, cb_aac_error on_error)
  27. {
  28. _on_data = on_data;
  29. _on_error = on_error;
  30. }
  31. const AVRational &get_time_base();
  32. AVCodecID get_codec_id();
  33. // Ring buffer stats helpers
  34. inline size_t rb_dropped_frames() const { return _ring_buffer ? _ring_buffer->dropped_frames() : 0; }
  35. inline size_t rb_pending_frames() const { return _ring_buffer ? _ring_buffer->get_pending_frames() : 0; }
  36. inline size_t rb_max_frames() const { return _ring_buffer ? _ring_buffer->max_frames() : 0; }
  37. inline void rb_set_max_frames(size_t max_frames) { if (_ring_buffer) _ring_buffer->set_max_frames(max_frames); }
  38. inline void rb_reset_dropped() { if (_ring_buffer) _ring_buffer->reset_dropped_frames(); }
  39. private:
  40. int encode(AVFrame *frame, AVPacket *packet);
  41. void encode_loop();
  42. void cleanup();
  43. // 为raw AAC数据添加ADTS头部
  44. int add_adts_header(AVPacket *packet);
  45. private:
  46. cb_aac_data _on_data;
  47. cb_aac_error _on_error;
  48. ring_buffer<AVFrame> *_ring_buffer;
  49. std::atomic_bool _inited;
  50. std::atomic_bool _running;
  51. std::thread _thread;
  52. AVCodec *_encoder;
  53. AVCodecContext *_encoder_ctx;
  54. AVFrame *_frame;
  55. uint8_t *_buff;
  56. int _buff_size;
  57. // BSF for converting raw AAC to ADTS format
  58. AVBSFContext *_bsf_ctx;
  59. std::mutex _mutex;
  60. std::condition_variable _cond_var;
  61. bool _cond_notify;
  62. #ifdef SAVE_AAC
  63. AVIOContext *_aac_io_ctx;
  64. AVStream *_aac_stream;
  65. AVFormatContext *_aac_fmt_ctx;
  66. #endif
  67. };
  68. } // namespace am
  69. #endif