MediaReader.cpp 12.1 KB
Newer Older
xiongziliang committed
1
/*
xiongziliang committed
2
 * MIT License
xzl committed
3
 *
xiongziliang committed
4
 * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com>
xiongziliang committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
xzl committed
25 26 27
 */

#include "MediaReader.h"
xiongziliang committed
28
#include "Common/config.h"
xiongzilaing committed
29
#include "Util/mini.h"
xzl committed
30
#include "Http/HttpSession.h"
xiongziliang committed
31 32 33
#include "Extension/AAC.h"
#include "Extension/H264.h"

xiongziliang committed
34
using namespace toolkit;
xzl committed
35

xiongziliang committed
36
namespace mediakit {
xzl committed
37

38
#ifdef ENABLE_MP4V2
xiongziliang committed
39
MediaReader::MediaReader(const string &strVhost,const string &strApp, const string &strId,const string &filePath ) {
40
	_poller = EventPollerPool::Instance().getPoller();
xiongziliang committed
41 42
    auto strFileName = filePath;
    if(strFileName.empty()){
43 44 45 46 47 48 49
		GET_CONFIG(string,recordPath,Record::kFilePath);
        GET_CONFIG(bool,enableVhost,General::kEnableVhost);
        if(enableVhost){
            strFileName = recordPath + "/" + strVhost + "/" + strApp + "/" + strId;
        }else{
            strFileName = recordPath + "/" + strApp + "/" + strId;
        }
xiongziliang committed
50
    }
xzl committed
51

52 53
	_hMP4File = MP4Read(strFileName.data());
	if(_hMP4File == MP4_INVALID_FILE_HANDLE){
54
		throw runtime_error(StrPrinter << "打开MP4文件失败:" << strFileName << endl);
xzl committed
55
	}
56 57 58 59 60 61 62 63 64 65 66
	_video_trId = MP4FindTrackId(_hMP4File, 0, MP4_VIDEO_TRACK_TYPE, 0);
	if(_video_trId != MP4_INVALID_TRACK_ID){
		 if(strcmp(MP4GetTrackMediaDataName(_hMP4File, _video_trId),"avc1") ==0){
			auto _video_timescale 		= MP4GetTrackTimeScale(_hMP4File, _video_trId);
			auto _video_duration 		= MP4GetTrackDuration(_hMP4File, _video_trId);
			_video_num_samples     = MP4GetTrackNumberOfSamples(_hMP4File, _video_trId);
			_video_sample_max_size = MP4GetTrackMaxSampleSize(_hMP4File, _video_trId);
			_video_width 			= MP4GetTrackVideoWidth(_hMP4File, _video_trId);
			_video_height 			= MP4GetTrackVideoHeight(_hMP4File, _video_trId);
			_video_framerate       = MP4GetTrackVideoFrameRate(_hMP4File, _video_trId);
			_pcVideoSample = std::shared_ptr<uint8_t> (new uint8_t[_video_sample_max_size],[](uint8_t *ptr){
xzl committed
67 68 69 70 71 72 73
				delete [] ptr;
			});
			uint8_t **seqheader;
			uint8_t **pictheader;
			uint32_t *pictheadersize;
			uint32_t *seqheadersize;
			uint32_t ix;
74
			if(MP4GetTrackH264SeqPictHeaders(_hMP4File, _video_trId, &seqheader, &seqheadersize, &pictheader, &pictheadersize)){
xzl committed
75
				for (ix = 0; seqheadersize[ix] != 0; ix++) {
76
					_strSps.assign((char *)(seqheader[ix]), seqheadersize[ix]);
xzl committed
77
					float framerate;
78 79 80
					getAVCInfo(_strSps, (int &)_video_width, (int &)_video_height, framerate);
					_video_framerate = framerate;
					_strSps = string("\x0\x0\x0\x1",4) + _strSps;
81
					MP4Free(seqheader[ix]);
xzl committed
82
				}
83 84
				MP4Free(seqheader);
				MP4Free(seqheadersize);
xzl committed
85
				for (ix = 0; pictheadersize[ix] != 0; ix++) {
86 87
					_strPps.assign("\x0\x0\x0\x1",4);
					_strPps.append((char *)(pictheader[ix]), pictheadersize[ix]);
88
					MP4Free(pictheader[ix]);
xzl committed
89
				}
90 91
				MP4Free(pictheader);
				MP4Free(pictheadersize);
xzl committed
92
			}
93
			_video_ms = 1000.0 * _video_duration / _video_timescale;
xzl committed
94
			/*InfoL 	<< "\r\n"
95 96 97 98 99
					<< _video_ms << "\r\n"
					<< _video_num_samples << "\r\n"
					<< _video_framerate << "\r\n"
					<< _video_width << "\r\n"
					<< _video_height << "\r\n";*/
xzl committed
100 101
		} else {
			//如果不是h264,则忽略
102
			_video_trId = MP4_INVALID_TRACK_ID;
xzl committed
103 104 105 106
		}
	}


107 108 109 110 111 112 113 114
	_audio_trId = MP4FindTrackId(_hMP4File, 0, MP4_AUDIO_TRACK_TYPE, 0);
	if (_audio_trId != MP4_INVALID_TRACK_ID) {
		if (strcmp(MP4GetTrackMediaDataName(_hMP4File, _audio_trId), "mp4a") == 0) {
			_audio_sample_rate = MP4GetTrackTimeScale(_hMP4File, _audio_trId);
			auto _audio_duration = MP4GetTrackDuration(_hMP4File, _audio_trId);
			_audio_num_samples = MP4GetTrackNumberOfSamples(_hMP4File,_audio_trId);
			_audio_num_channels = MP4GetTrackAudioChannels(_hMP4File, _audio_trId);
			_audio_sample_max_size = MP4GetTrackMaxSampleSize(_hMP4File,_audio_trId);
xzl committed
115 116
			uint8_t *ppConfig;
			uint32_t pConfigSize;
117 118 119 120 121
			if(MP4GetTrackESConfiguration(_hMP4File,_audio_trId,&ppConfig,&pConfigSize)){
				_strAacCfg.assign((char *)ppConfig, pConfigSize);
				makeAdtsHeader(_strAacCfg, _adts);
				writeAdtsHeader(_adts,_adts.buffer);
				getAACInfo(_adts, (int &)_audio_sample_rate, (int &)_audio_num_channels);
122
				MP4Free(ppConfig);
xzl committed
123
			}
124
			_audio_ms = 1000.0 * _audio_duration / _audio_sample_rate;
xzl committed
125
			/*InfoL 	<< "\r\n"
126 127 128 129
					<< _audio_ms << "\r\n"
					<< _audio_num_samples << "\r\n"
					<< _audio_num_channels << "\r\n"
					<< _audio_sample_rate << "\r\n";*/
xzl committed
130
		}else{
131
			_audio_trId = MP4_INVALID_TRACK_ID;
xzl committed
132 133
		}
	}
134 135 136
	if(_audio_trId == MP4_INVALID_TRACK_ID && _video_trId == MP4_INVALID_TRACK_ID){
		MP4Close(_hMP4File);
		_hMP4File = MP4_INVALID_FILE_HANDLE;
137
		throw runtime_error(StrPrinter << "该MP4文件音视频格式不支持:" << strFileName << endl);
xzl committed
138 139
	}

140
	_iDuration	= MAX(_video_ms,_audio_ms);
141
	_mediaMuxer.reset(new MultiMediaSourceMuxer(strVhost, strApp, strId, _iDuration / 1000.0, true, true, false, false));
142
	if (_audio_trId != MP4_INVALID_TRACK_ID) {
143
		AACTrack::Ptr track = std::make_shared<AACTrack>(_strAacCfg);
144
		_mediaMuxer->addTrack(track);
xzl committed
145 146
	}

147
	if (_video_trId != MP4_INVALID_TRACK_ID) {
148
		H264Track::Ptr track = std::make_shared<H264Track>(_strSps,_strPps);
149
		_mediaMuxer->addTrack(track);
xzl committed
150 151 152 153 154
	}
}


MediaReader::~MediaReader() {
155 156 157
	if (_hMP4File != MP4_INVALID_FILE_HANDLE) {
		MP4Close(_hMP4File);
		_hMP4File = MP4_INVALID_FILE_HANDLE;
xzl committed
158 159 160 161 162 163
	}
}


void MediaReader::startReadMP4() {
	auto strongSelf = shared_from_this();
164
    GET_CONFIG(uint32_t,sampleMS,Record::kSampleMS);
165

166
	_timer = std::make_shared<Timer>(sampleMS / 1000.0f,[strongSelf](){
167
		return strongSelf->readSample(0,false);
168
	}, _poller);
169

170 171
    //先读sampleMS毫秒的数据用于产生MediaSouce
	readSample(sampleMS, false);
172
	_mediaMuxer->setListener(strongSelf);
173
}
xiongziliang committed
174
 bool MediaReader::seekTo(MediaSource &sender,uint32_t ui32Stamp){
175 176 177
	 seek(ui32Stamp);
	 return true;
}
xiongziliang committed
178
bool MediaReader::close(MediaSource &sender,bool force){
179
    if(!_mediaMuxer || (!force && _mediaMuxer->readerCount() != 0)){
180 181
        return false;
    }
182
	_timer.reset();
xiongziliang committed
183
    WarnL << sender.getSchema() << "/" << sender.getVhost() << "/" << sender.getApp() << "/" << sender.getId() << " " << force;
184 185
    return true;
}
xzl committed
186

187
void MediaReader::onNoneReader(MediaSource &sender) {
188
    if(!_mediaMuxer || _mediaMuxer->readerCount() != 0){
189 190 191 192 193
        return;
    }
    MediaSourceEvent::onNoneReader(sender);
}

194
bool MediaReader::readSample(int iTimeInc,bool justSeekSyncFrame) {
xzl committed
195
	TimeTicker();
196
	lock_guard<recursive_mutex> lck(_mtx);
197 198
	auto bFlag0 = readVideoSample(iTimeInc,justSeekSyncFrame);//数据没读完
	auto bFlag1 = readAudioSample(iTimeInc,justSeekSyncFrame);//数据没读完
199
	auto bFlag2 = _mediaMuxer->readerCount() > 0;//读取者大于0
xzl committed
200
	if((bFlag0 || bFlag1) && bFlag2){
201
		_alive.resetTime();
xzl committed
202 203 204
	}
	//DebugL << "alive ...";
	//3秒延时关闭
205
	return  _alive.elapsedTime() <  3 * 1000;
xzl committed
206
}
207
inline bool MediaReader::readVideoSample(int iTimeInc,bool justSeekSyncFrame) {
208
	if (_video_trId != MP4_INVALID_TRACK_ID) {
xzl committed
209
		auto iNextSample = getVideoSampleId(iTimeInc);
210
		MP4SampleId iIdx = _video_current;
211
		for (; iIdx < iNextSample; iIdx++) {
212 213 214
			uint8_t *pBytes = _pcVideoSample.get();
			uint32_t numBytes = _video_sample_max_size;
			if(MP4ReadSample(_hMP4File, _video_trId, iIdx + 1, &pBytes, &numBytes,NULL,NULL,NULL,&_bSyncSample)){
215
				if (!justSeekSyncFrame) {
xzl committed
216 217 218 219 220 221 222 223 224
					uint32_t iOffset = 0;
					while (iOffset < numBytes) {
						uint32_t iFrameLen;
						memcpy(&iFrameLen,pBytes + iOffset,4);
						iFrameLen = ntohl(iFrameLen);
                        if(iFrameLen + iOffset + 4> numBytes){
                            break;
                        }
						memcpy(pBytes + iOffset, "\x0\x0\x0\x1", 4);
xiongziliang committed
225
						writeH264(pBytes + iOffset, iFrameLen + 4, (double) _video_ms * iIdx / _video_num_samples, 0);
xzl committed
226 227
						iOffset += (iFrameLen + 4);
					}
228
				}else if(_bSyncSample){
xzl committed
229 230 231
					break;
				}
			}else{
xiongziliang committed
232
				ErrorL << "读取视频失败:" << iIdx + 1;
xzl committed
233 234
			}
		}
235 236
		_video_current = iIdx;
		return _video_current < _video_num_samples;
xzl committed
237 238 239 240
	}
	return false;
}

241
inline bool MediaReader::readAudioSample(int iTimeInc,bool justSeekSyncFrame) {
242
	if (_audio_trId != MP4_INVALID_TRACK_ID) {
xzl committed
243
		auto iNextSample = getAudioSampleId(iTimeInc);
244 245 246 247
		for (auto i = _audio_current; i < iNextSample; i++) {
			uint32_t numBytes = _audio_sample_max_size;
			uint8_t *pBytes = _adts.buffer + 7;
			if(MP4ReadSample(_hMP4File, _audio_trId, i + 1, &pBytes, &numBytes)){
248
				if (!justSeekSyncFrame) {
249 250 251
					_adts.aac_frame_length = 7 + numBytes;
					writeAdtsHeader(_adts, _adts.buffer);
					writeAAC(_adts.buffer, _adts.aac_frame_length, (double) _audio_ms * i / _audio_num_samples);
xzl committed
252 253
				}
			}else{
xiongziliang committed
254
				ErrorL << "读取音频失败:" << i+ 1;
xzl committed
255 256
			}
		}
257 258
		_audio_current = iNextSample;
		return _audio_current < _audio_num_samples;
xzl committed
259 260 261 262
	}
	return false;
}

xiongziliang committed
263
inline void MediaReader::writeH264(uint8_t *pucData,int iLen,uint32_t dts,uint32_t pts) {
264
	_mediaMuxer->inputFrame(std::make_shared<H264FrameNoCacheAble>((char*)pucData,iLen,dts,pts));
xzl committed
265 266 267
}

inline void MediaReader::writeAAC(uint8_t *pucData,int iLen,uint32_t uiStamp) {
268
	_mediaMuxer->inputFrame(std::make_shared<AACFrameNoCacheAble>((char*)pucData,iLen,uiStamp));
xzl committed
269 270 271
}

inline MP4SampleId MediaReader::getVideoSampleId(int iTimeInc ) {
272 273
	MP4SampleId video_current = (double)_video_num_samples *  (_iSeekTime + _ticker.elapsedTime() + iTimeInc) / _video_ms;
	video_current = MAX(0,MIN(_video_num_samples, video_current));
xzl committed
274 275 276 277 278
	return video_current;

}

inline MP4SampleId MediaReader::getAudioSampleId(int iTimeInc) {
279 280
	MP4SampleId audio_current = (double)_audio_num_samples * (_iSeekTime + _ticker.elapsedTime() + iTimeInc)  / _audio_ms ;
	audio_current = MAX(0,MIN(_audio_num_samples,audio_current));
xzl committed
281 282
	return audio_current;
}
283
inline void MediaReader::setSeekTime(uint32_t iSeekTime){
284 285 286 287
	_iSeekTime = MAX(0, MIN(iSeekTime,_iDuration));
	_ticker.resetTime();
	if (_audio_trId != MP4_INVALID_TRACK_ID) {
		_audio_current = getAudioSampleId();
xzl committed
288
	}
289 290
	if (_video_trId != MP4_INVALID_TRACK_ID) {
		_video_current = getVideoSampleId();
xzl committed
291 292 293 294
	}
}

inline uint32_t MediaReader::getVideoCurrentTime(){
295
	return (double)_video_current * _video_ms /_video_num_samples;
xzl committed
296
}
297
void MediaReader::seek(uint32_t iSeekTime,bool bReStart){
298 299
	lock_guard<recursive_mutex> lck(_mtx);
	if(iSeekTime == 0 || _video_trId == MP4_INVALID_TRACK_ID){
xzl committed
300 301 302 303
		setSeekTime(iSeekTime);
	}else{
		setSeekTime(iSeekTime - 5000);
		//在之后的10秒查找关键帧
304
		readVideoSample(10000, true);
305
		if (_bSyncSample) {
xzl committed
306
			//找到关键帧
307
			auto iIdr =  _video_current;
xzl committed
308
			setSeekTime(getVideoCurrentTime());
309
			_video_current = iIdr;
xzl committed
310 311 312 313 314
		}else{
			//未找到关键帧
			setSeekTime(iSeekTime);
		}
	}
315
	_mediaMuxer->setTimeStamp(_iSeekTime);
xzl committed
316 317

	if(bReStart){
318
		_timer.reset();
xzl committed
319 320 321 322
		startReadMP4();
	}
}

323
#endif //ENABLE_MP4V2
xzl committed
324 325 326



xiongziliang committed
327 328 329 330 331 332
MediaSource::Ptr MediaReader::onMakeMediaSource(const string &strSchema,
												const string &strVhost,
												const string &strApp,
												const string &strId,
												const string &filePath,
												bool checkApp ){
333
#ifdef ENABLE_MP4V2
334
    GET_CONFIG(string,appName,Record::kAppName);
xiongziliang committed
335
    if (checkApp && strApp != appName) {
xzl committed
336 337 338
		return nullptr;
	}
	try {
xiongziliang committed
339
		MediaReader::Ptr pReader(new MediaReader(strVhost,strApp, strId,filePath));
xzl committed
340
		pReader->startReadMP4();
341
		return MediaSource::find(strSchema,strVhost,strApp, strId, false);
xzl committed
342 343 344 345 346 347
	} catch (std::exception &ex) {
		WarnL << ex.what();
		return nullptr;
	}
#else
	return nullptr;
348
#endif //ENABLE_MP4V2
xzl committed
349 350 351 352
}



xiongziliang committed
353
} /* namespace mediakit */