1-
2-
31#import " TIoTAVCaptionFLV.h"
42#import " TIoTAACEncoder.h"
53#import " TIoTH264Encoder.h"
64
75#include < string>
6+ #include < memory> // 添加memory头文件以支持std::unique_ptr
87// #include <flv-writer.h>
98// #include <flv-muxer.h>
109#import " flv-writer.h"
@@ -498,18 +497,21 @@ static int flv_onwrite(void *param, const struct flv_vec_t* vec, int n) {
498497 }
499498
500499// NSLog(@"========= flv_onmuxer total size: %d", total_size);
501- char * bytes = new char [total_size];
500+
501+ // 使用unique_ptr自动管理内存,确保异常安全
502+ std::unique_ptr<char []> bytes (new char [total_size]);
502503 for (int i = 0 , offset = 0 ; i < n; i++) {
503- memcpy (bytes + offset, vec[i].ptr , vec[i].len );
504+ memcpy (bytes. get () + offset, vec[i].ptr , vec[i].len );
504505 offset += vec[i].len ;
505506 }
506507
507508// NSData *ByteHeader = [NSData dataWithBytes:bytes length:total_size];
508509// [_fileHandle writeData:ByteHeader];
509510
510- [tAVCaptionFLV.delegate capture: (uint8_t *)bytes len: total_size];
511+ // 传递数据给delegate,确保在函数返回前数据有效
512+ [tAVCaptionFLV.delegate capture: (uint8_t *)bytes.get () len: total_size];
511513
512- delete[] bytes;
514+ // unique_ptr会自动释放内存,无需手动delete[]
513515 return 0 ;
514516}
515517
@@ -521,14 +523,15 @@ int encodeFlvData(int type, NSData *packetData) {
521523 NSLog (@" Please init flv muxer first." );
522524 return -1 ;
523525 }
524- __block NSData *blockData = packetData;
526+ // 使用强引用确保数据在异步执行期间不被释放
527+ NSData *strongData = [packetData copy ];
525528 dispatch_async (muxerQueue, ^{
526529
527530 CFTimeInterval timestamp = CACurrentMediaTime ();
528531 uint32_t pts = timestamp*1000 ;
529532
530- const void *c_data = blockData .bytes ;
531- NSUInteger len = blockData .length ;
533+ const void *c_data = strongData .bytes ;
534+ NSUInteger len = strongData .length ;
532535 // NSLog(@"===========================------------ %ld, pts: %u", len, pts);
533536
534537
@@ -564,7 +567,7 @@ -(BOOL) startCapture {
564567// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
565568// NSString *documentsDirectory = [paths firstObject];
566569//
567- // NSString *h264File = [documentsDirectory stringByAppendingPathComponent:@"test.aac "];
570+ // NSString *h264File = [documentsDirectory stringByAppendingPathComponent:@"test.h264 "];
568571// [fileManager removeItemAtPath:h264File error:nil];
569572// [fileManager createFileAtPath:h264File contents:nil attributes:nil];
570573// _fileHandle = [NSFileHandle fileHandleForWritingAtPath:h264File];
0 commit comments