Debian Codegraph @

Xpjproject/pjmedia/src/pjmedia-codec/vid_toolbox.m

raw
1 /*
2 * Copyright (C)2017 Teluu Inc. (http://www.teluu.com)
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18 #include <pjmedia-codec/vid_toolbox.h>
19 #include <pjmedia-codec/h264_packetizer.h>
20 #include <pjmedia/vid_codec_util.h>
21 #include <pjmedia/errno.h>
22 #include <pj/log.h>
23 #include <pj/math.h>
24
25 #if defined(PJMEDIA_HAS_VID_TOOLBOX_CODEC) && \
26 PJMEDIA_HAS_VID_TOOLBOX_CODEC != 0 && \
27 defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0)
28
29 #import <Foundation/Foundation.h>
30 #import <VideoToolbox/VideoToolbox.h>
31
32 #include "TargetConditionals.h"
33
34 #define THIS_FILE "vid_toolbox.m"
35
36 #if (defined(PJ_DARWINOS) && PJ_DARWINOS != 0 && TARGET_OS_IPHONE)
37 #import <UIKit/UIKit.h>
38 #endif
39
40 #define DEFAULT_WIDTH 720
41 #define DEFAULT_HEIGHT 480
42 #define DEFAULT_FPS 15
43 #define DEFAULT_AVG_BITRATE 384000
44 #define DEFAULT_MAX_BITRATE 512000
45
46 #define MAX_RX_WIDTH 1280
47 #define MAX_RX_HEIGHT 800
48
49 #define SPS_PPS_BUF_SIZE 32
50
51 /* For better compatibility with other codecs (OpenH264 and x264),
52 * we decode the whole packets at once.
53 */
54 #define DECODE_WHOLE PJ_TRUE
55
56 /* Maximum duration from one key frame to the next (in seconds). */
57 #define KEYFRAME_INTERVAL PJMEDIA_CODEC_VID_TOOLBOX_MAX_KEYFRAME_INTERVAL
58
59 /* vidtoolbox H264 default PT */
60 #define VT_H264_PT PJMEDIA_RTP_PT_H264_RSV1
61 /*
62 * Factory operations.
63 */
64 static pj_status_t vtool_test_alloc(pjmedia_vid_codec_factory *factory,
65 const pjmedia_vid_codec_info *info );
66 static pj_status_t vtool_default_attr(pjmedia_vid_codec_factory *factory,
67 const pjmedia_vid_codec_info *info,
68 pjmedia_vid_codec_param *attr );
69 static pj_status_t vtool_enum_info(pjmedia_vid_codec_factory *factory,
70 unsigned *count,
71 pjmedia_vid_codec_info codecs[]);
72 static pj_status_t vtool_alloc_codec(pjmedia_vid_codec_factory *factory,
73 const pjmedia_vid_codec_info *info,
74 pjmedia_vid_codec **p_codec);
75 static pj_status_t vtool_dealloc_codec(pjmedia_vid_codec_factory *factory,
76 pjmedia_vid_codec *codec );
77
78
79 /*
80 * Codec operations
81 */
82 static pj_status_t vtool_codec_init(pjmedia_vid_codec *codec,
83 pj_pool_t *pool );
84 static pj_status_t vtool_codec_open(pjmedia_vid_codec *codec,
85 pjmedia_vid_codec_param *param );
86 static pj_status_t vtool_codec_close(pjmedia_vid_codec *codec);
87 static pj_status_t vtool_codec_modify(pjmedia_vid_codec *codec,
88 const pjmedia_vid_codec_param *param);
89 static pj_status_t vtool_codec_get_param(pjmedia_vid_codec *codec,
90 pjmedia_vid_codec_param *param);
91 static pj_status_t vtool_codec_encode_begin(pjmedia_vid_codec *codec,
92 const pjmedia_vid_encode_opt *opt,
93 const pjmedia_frame *input,
94 unsigned out_size,
95 pjmedia_frame *output,
96 pj_bool_t *has_more);
97 static pj_status_t vtool_codec_encode_more(pjmedia_vid_codec *codec,
98 unsigned out_size,
99 pjmedia_frame *output,
100 pj_bool_t *has_more);
101 static pj_status_t vtool_codec_decode(pjmedia_vid_codec *codec,
102 pj_size_t count,
103 pjmedia_frame packets[],
104 unsigned out_size,
105 pjmedia_frame *output);
106
107 /* Definition for Video Toolbox codecs operations. */
108 static pjmedia_vid_codec_op vtool_codec_op =
109 {
110 &vtool_codec_init,
111 &vtool_codec_open,
112 &vtool_codec_close,
113 &vtool_codec_modify,
114 &vtool_codec_get_param,
115 &vtool_codec_encode_begin,
116 &vtool_codec_encode_more,
117 &vtool_codec_decode,
118 NULL
119 };
120
121 /* Definition for Video Toolbox codecs factory operations. */
122 static pjmedia_vid_codec_factory_op vtool_factory_op =
123 {
124 &vtool_test_alloc,
125 &vtool_default_attr,
126 &vtool_enum_info,
127 &vtool_alloc_codec,
128 &vtool_dealloc_codec
129 };
130
131
132 static struct vtool_factory
133 {
134 pjmedia_vid_codec_factory base;
135 pjmedia_vid_codec_mgr *mgr;
136 pj_pool_factory *pf;
137 pj_pool_t *pool;
138 } vtool_factory;
139
140
141 typedef struct vtool_codec_data
142 {
143 pjmedia_vid_codec *codec;
144 pj_pool_t *pool;
145 pjmedia_vid_codec_param *prm;
146 pj_bool_t whole;
147 pjmedia_h264_packetizer *pktz;
148
149 /* Encoder */
150 VTCompressionSessionRef enc;
151 void *enc_buf;
152 unsigned enc_buf_size;
153
154 unsigned enc_input_size;
155 unsigned enc_wxh;
156 unsigned enc_fps;
157 unsigned enc_frm_cnt;
158 unsigned enc_frame_size;
159 unsigned enc_processed;
160 pj_bool_t enc_is_keyframe;
161
162 /* Decoder */
163 VTDecompressionSessionRef dec;
164 pj_uint8_t *dec_buf;
165 unsigned dec_buf_size;
166 CMFormatDescriptionRef dec_format;
167 OSStatus dec_status;
168
169 unsigned dec_sps_size;
170 unsigned dec_pps_size;
171 unsigned char dec_sps[SPS_PPS_BUF_SIZE];
172 unsigned char dec_pps[SPS_PPS_BUF_SIZE];
173
174 pjmedia_frame *dec_frame;
175 pj_bool_t dec_fmt_change;
176 } vtool_codec_data;
177
178 /* Prototypes */
179 static OSStatus create_decoder(struct vtool_codec_data *vtool_data);
180
181 #if TARGET_OS_IPHONE
182 static void dispatch_sync_on_main_queue(void (^block)(void))
183 {
184 if ([NSThread isMainThread]) {
185 block();
186 } else {
187 dispatch_sync(dispatch_get_main_queue(), block);
188 }
189 }
190 #endif
191
192 PJ_DEF(pj_status_t) pjmedia_codec_vid_toolbox_init(pjmedia_vid_codec_mgr *mgr,
193 pj_pool_factory *pf)
194 {
195 const pj_str_t h264_name = { (char*)"H264", 4};
196 pj_status_t status;
197
198 if (vtool_factory.pool != NULL) {
199 /* Already initialized. */
200 return PJ_SUCCESS;
201 }
202
203 if (!mgr) mgr = pjmedia_vid_codec_mgr_instance();
204 PJ_ASSERT_RETURN(mgr, PJ_EINVAL);
205
206 /* Create Video Toolbox codec factory. */
207 vtool_factory.base.op = &vtool_factory_op;
208 vtool_factory.base.factory_data = NULL;
209 vtool_factory.mgr = mgr;
210 vtool_factory.pf = pf;
211 vtool_factory.pool = pj_pool_create(pf, "vtoolfactory", 256, 256, NULL);
212 if (!vtool_factory.pool)
213 return PJ_ENOMEM;
214
215 /* Registering format match for SDP negotiation */
216 status = pjmedia_sdp_neg_register_fmt_match_cb(
217 &h264_name,
218 &pjmedia_vid_codec_h264_match_sdp);
219 if (status != PJ_SUCCESS)
220 goto on_error;
221
222 /* Register codec factory to codec manager. */
223 status = pjmedia_vid_codec_mgr_register_factory(mgr,
224 &vtool_factory.base);
225 if (status != PJ_SUCCESS)
226 goto on_error;
227
228 PJ_LOG(4,(THIS_FILE, "Video Toolbox codec initialized"));
229
230 /* Done. */
231 return PJ_SUCCESS;
232
233 on_error:
234 pj_pool_release(vtool_factory.pool);
235 vtool_factory.pool = NULL;
236 return status;
237 }
238
239 /*
240 * Unregister Video Toolbox codecs factory from pjmedia endpoint.
241 */
242 PJ_DEF(pj_status_t) pjmedia_codec_vid_toolbox_deinit(void)
243 {
244 pj_status_t status = PJ_SUCCESS;
245
246 if (vtool_factory.pool == NULL) {
247 /* Already deinitialized */
248 return PJ_SUCCESS;
249 }
250
251 /* Unregister Video Toolbox codecs factory. */
252 status = pjmedia_vid_codec_mgr_unregister_factory(vtool_factory.mgr,
253 &vtool_factory.base);
254
255 /* Destroy pool. */
256 pj_pool_release(vtool_factory.pool);
257 vtool_factory.pool = NULL;
258
259 return status;
260 }
261
262 static pj_status_t vtool_test_alloc(pjmedia_vid_codec_factory *factory,
263 const pjmedia_vid_codec_info *info )
264 {
265 PJ_ASSERT_RETURN(factory == &vtool_factory.base, PJ_EINVAL);
266
267 if (info->fmt_id == PJMEDIA_FORMAT_H264 &&
268 info->pt == VT_H264_PT)
269 {
270 return PJ_SUCCESS;
271 }
272
273 return PJMEDIA_CODEC_EUNSUP;
274 }
275
276 static pj_status_t vtool_default_attr(pjmedia_vid_codec_factory *factory,
277 const pjmedia_vid_codec_info *info,
278 pjmedia_vid_codec_param *attr )
279 {
280 PJ_ASSERT_RETURN(factory == &vtool_factory.base, PJ_EINVAL);
281 PJ_ASSERT_RETURN(info && attr, PJ_EINVAL);
282
283 pj_bzero(attr, sizeof(pjmedia_vid_codec_param));
284
285 attr->dir = PJMEDIA_DIR_ENCODING_DECODING;
286 attr->packing = PJMEDIA_VID_PACKING_PACKETS;
287
288 /* Encoded format */
289 pjmedia_format_init_video(&attr->enc_fmt, PJMEDIA_FORMAT_H264,
290 DEFAULT_WIDTH, DEFAULT_HEIGHT,
291 DEFAULT_FPS, 1);
292
293 /* Decoded format */
294 pjmedia_format_init_video(&attr->dec_fmt, PJMEDIA_FORMAT_I420,
295 DEFAULT_WIDTH, DEFAULT_HEIGHT,
296 DEFAULT_FPS, 1);
297
298 /* Decoding fmtp */
299 attr->dec_fmtp.cnt = 2;
300 attr->dec_fmtp.param[0].name = pj_str((char*)"profile-level-id");
301 attr->dec_fmtp.param[0].val = pj_str((char*)"42e01e");
302 attr->dec_fmtp.param[1].name = pj_str((char*)" packetization-mode");
303 attr->dec_fmtp.param[1].val = pj_str((char*)"1");
304
305 /* Bitrate */
306 attr->enc_fmt.det.vid.avg_bps = DEFAULT_AVG_BITRATE;
307 attr->enc_fmt.det.vid.max_bps = DEFAULT_MAX_BITRATE;
308
309 /* Encoding MTU */
310 attr->enc_mtu = PJMEDIA_MAX_VID_PAYLOAD_SIZE;
311
312 return PJ_SUCCESS;
313 }
314
315 static pj_status_t vtool_enum_info(pjmedia_vid_codec_factory *factory,
316 unsigned *count,
317 pjmedia_vid_codec_info info[])
318 {
319 PJ_ASSERT_RETURN(info && *count > 0, PJ_EINVAL);
320 PJ_ASSERT_RETURN(factory == &vtool_factory.base, PJ_EINVAL);
321
322 *count = 1;
323 info->fmt_id = PJMEDIA_FORMAT_H264;
324 info->pt = VT_H264_PT;
325 info->encoding_name = pj_str((char*)"H264");
326 info->encoding_desc = pj_str((char*)"Video Toolbox codec");
327 info->clock_rate = 90000;
328 info->dir = PJMEDIA_DIR_ENCODING_DECODING;
329 info->dec_fmt_id_cnt = 1;
330 info->dec_fmt_id[0] = PJMEDIA_FORMAT_I420;
331 info->packings = PJMEDIA_VID_PACKING_PACKETS |
332 PJMEDIA_VID_PACKING_WHOLE;
333 info->fps_cnt = 3;
334 info->fps[0].num = 15;
335 info->fps[0].denum = 1;
336 info->fps[1].num = 25;
337 info->fps[1].denum = 1;
338 info->fps[2].num = 30;
339 info->fps[2].denum = 1;
340
341 return PJ_SUCCESS;
342 }
343
344 static pj_status_t vtool_alloc_codec(pjmedia_vid_codec_factory *factory,
345 const pjmedia_vid_codec_info *info,
346 pjmedia_vid_codec **p_codec)
347 {
348 pj_pool_t *pool;
349 pjmedia_vid_codec *codec;
350 vtool_codec_data *vtool_data;
351
352 PJ_ASSERT_RETURN(factory == &vtool_factory.base && info && p_codec,
353 PJ_EINVAL);
354
355 *p_codec = NULL;
356
357 pool = pj_pool_create(vtool_factory.pf, "vtool%p", 16000, 4000, NULL);
358 if (!pool)
359 return PJ_ENOMEM;
360
361 /* codec instance */
362 codec = PJ_POOL_ZALLOC_T(pool, pjmedia_vid_codec);
363 codec->factory = factory;
364 codec->op = &vtool_codec_op;
365
366 /* codec data */
367 vtool_data = PJ_POOL_ZALLOC_T(pool, vtool_codec_data);
368 vtool_data->pool = pool;
369 vtool_data->codec = codec;
370 codec->codec_data = vtool_data;
371
372 *p_codec = codec;
373 return PJ_SUCCESS;
374 }
375
376 static pj_status_t vtool_dealloc_codec(pjmedia_vid_codec_factory *factory,
377 pjmedia_vid_codec *codec )
378 {
379 vtool_codec_data *vtool_data;
380
381 PJ_ASSERT_RETURN(codec, PJ_EINVAL);
382
383 PJ_UNUSED_ARG(factory);
384
385 vtool_data = (vtool_codec_data*) codec->codec_data;
386 pj_pool_release(vtool_data->pool);
387 return PJ_SUCCESS;
388 }
389
390 static pj_status_t vtool_codec_init(pjmedia_vid_codec *codec,
391 pj_pool_t *pool )
392 {
393 PJ_ASSERT_RETURN(codec && pool, PJ_EINVAL);
394 PJ_UNUSED_ARG(codec);
395 PJ_UNUSED_ARG(pool);
396 return PJ_SUCCESS;
397 }
398
399 static void encode_cb(void *outputCallbackRefCon,
400 void *sourceFrameRefCon,
401 OSStatus status,
402 VTEncodeInfoFlags infoFlags,
403 CMSampleBufferRef sampleBuffer)
404 {
405 struct vtool_codec_data *vtool_data;
406 const pj_uint8_t start_code[] = { 0, 0, 0, 1 };
407 const int code_size = PJ_ARRAY_SIZE(start_code);
408 const int avcc_size = sizeof(uint32_t);
409 CFArrayRef array;
410 CFDictionaryRef dict = NULL;
411 CMBlockBufferRef block_buf;
412 size_t offset = 0, length = 0;
413 size_t buf_pos;
414 char *data, *buf;
415
416 /* This callback can be called from another, unregistered thread.
417 * So do not call pjlib functions here.
418 */
419
420 if (status != noErr || !CMSampleBufferDataIsReady(sampleBuffer)) return;
421
422 vtool_data = (struct vtool_codec_data *)outputCallbackRefCon;
423 vtool_data->enc_is_keyframe = PJ_FALSE;
424 buf = vtool_data->enc_buf;
425
426 /* Check if the encoded frame is keyframe */
427 array = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, true);
428 if (array) dict = (CFDictionaryRef)CFArrayGetValueAtIndex(array, 0);
429 if (dict && !CFDictionaryContainsKey(dict,kCMSampleAttachmentKey_NotSync))
430 vtool_data->enc_is_keyframe = PJ_TRUE;
431
432 if (vtool_data->enc_is_keyframe) {
433 CMFormatDescriptionRef format;
434 size_t enc_sps_size, enc_sps_cnt;
435 size_t enc_pps_size, enc_pps_cnt;
436 const uint8_t *enc_sps, *enc_pps;
437 OSStatus status;
438
439 format = CMSampleBufferGetFormatDescription(sampleBuffer);
440
441 /* Get SPS */
442 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
443 format, 0, &enc_sps, &enc_sps_size, &enc_sps_cnt, 0 );
444 if (status != noErr) return;
445
446 /* Get PPS */
447 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
448 format, 1, &enc_pps, &enc_pps_size, &enc_pps_cnt, 0 );
449 if (status != noErr) return;
450
451 /* Append SPS and PPS to output frame */
452 pj_assert (enc_sps_size + enc_pps_size + 2 * code_size <=
453 vtool_data->enc_buf_size);
454 pj_memcpy(buf + offset, start_code, code_size);
455 offset += code_size;
456 pj_memcpy(buf + offset, enc_sps, enc_sps_size);
457 offset += enc_sps_size;
458 pj_memcpy(buf + offset, start_code, code_size);
459 offset += code_size;
460 pj_memcpy(buf + offset, enc_pps, enc_pps_size);
461 offset += enc_pps_size;
462 }
463
464 pj_assert(CMSampleBufferGetNumSamples(sampleBuffer) == 1);
465
466 /* Get data pointer of the encoded frame */
467 block_buf = CMSampleBufferGetDataBuffer(sampleBuffer);
468 status = CMBlockBufferGetDataPointer(block_buf, 0, &length, NULL, &data);
469 if (status != noErr || (offset + length) > vtool_data->enc_buf_size)
470 return;
471
472 pj_assert(CMBlockBufferIsRangeContiguous(block_buf, 0, length));
473 pj_assert(length == CMBlockBufferGetDataLength(block_buf));
474
475 buf_pos = 0;
476 while (buf_pos < length - avcc_size) {
477 uint32_t data_length;
478
479 /* Get data length and copy the data to the output buffer */
480 pj_memcpy(&data_length, data + buf_pos, avcc_size);
481 data_length = pj_ntohl(data_length);
482 pj_assert(buf_pos + data_length + avcc_size <= length);
483 pj_memcpy(buf + offset, data + buf_pos, data_length + avcc_size);
484
485 /* Replace data length with NAL start code */
486 pj_memcpy(buf + offset, start_code, code_size);
487
488 buf_pos += avcc_size + data_length;
489 offset += avcc_size + data_length;
490 }
491 vtool_data->enc_frame_size = offset;
492 }
493
494
495 static OSStatus create_encoder(vtool_codec_data *vtool_data)
496 {
497 pjmedia_vid_codec_param *param = vtool_data->prm;
498 CFDictionaryRef supported_prop;
499 OSStatus ret;
500
501 /* Destroy if initialized before */
502 if (vtool_data->enc) {
503 VTCompressionSessionInvalidate(vtool_data->enc);
504 CFRelease(vtool_data->enc);
505 vtool_data->enc = NULL;
506 }
507
508 /* Create encoder session */
509 ret = VTCompressionSessionCreate(NULL, (int)param->enc_fmt.det.vid.size.w,
510 (int)param->enc_fmt.det.vid.size.h,
511 kCMVideoCodecType_H264, NULL, NULL,
512 NULL, encode_cb, vtool_data,
513 &vtool_data->enc);
514 if (ret != noErr) {
515 PJ_LOG(4,(THIS_FILE, "VTCompressionCreate failed, ret=%d", ret));
516 return ret;
517 }
518
519 #define SET_PROPERTY(sess, prop, val) \
520 { \
521 ret = VTSessionSetProperty(sess, prop, val); \
522 if (ret != noErr) \
523 PJ_LOG(5,(THIS_FILE, "Failed to set session property %s", #prop)); \
524 }
525
526 SET_PROPERTY(vtool_data->enc,
527 kVTCompressionPropertyKey_ProfileLevel,
528 kVTProfileLevel_H264_Baseline_AutoLevel);
529 SET_PROPERTY(vtool_data->enc, kVTCompressionPropertyKey_RealTime,
530 kCFBooleanTrue);
531 SET_PROPERTY(vtool_data->enc,
532 kVTCompressionPropertyKey_AllowFrameReordering,
533 kCFBooleanFalse);
534 SET_PROPERTY(vtool_data->enc,
535 kVTCompressionPropertyKey_AverageBitRate,
536 (__bridge CFTypeRef)@(param->enc_fmt.det.vid.avg_bps));
537 vtool_data->enc_fps = param->enc_fmt.det.vid.fps.num /
538 param->enc_fmt.det.vid.fps.denum;
539 SET_PROPERTY(vtool_data->enc,
540 kVTCompressionPropertyKey_ExpectedFrameRate,
541 (__bridge CFTypeRef)@(vtool_data->enc_fps));
542 SET_PROPERTY(vtool_data->enc,
543 kVTCompressionPropertyKey_DataRateLimits,
544 ((__bridge CFArrayRef) // [Bytes, second]
545 @[@(param->enc_fmt.det.vid.max_bps >> 3), @(1)]));
546 SET_PROPERTY(vtool_data->enc,
547 kVTCompressionPropertyKey_MaxKeyFrameInterval,
548 (__bridge CFTypeRef)@(KEYFRAME_INTERVAL *
549 param->enc_fmt.det.vid.fps.num /
550 param->enc_fmt.det.vid.fps.denum));
551 SET_PROPERTY(vtool_data->enc,
552 kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration,
553 (__bridge CFTypeRef)@(KEYFRAME_INTERVAL));
554
555 ret = VTSessionCopySupportedPropertyDictionary(vtool_data->enc,
556 &supported_prop);
557 if (ret == noErr) {
558 if (CFDictionaryContainsKey(supported_prop,
559 kVTCompressionPropertyKey_MaxH264SliceBytes))
560 {
561 /* kVTCompressionPropertyKey_MaxH264SliceBytes is not yet supported
562 * by Apple. We leave it here for possible future enhancements.
563 SET_PROPERTY(vtool_data->enc,
564 kVTCompressionPropertyKey_MaxH264SliceBytes,
565 // param->enc_mtu - NAL_HEADER_ADD_0X30BYTES
566 (__bridge CFTypeRef)@(param->enc_mtu - 50));
567 */
568 }
569
570 CFRelease(supported_prop);
571 }
572
573 VTCompressionSessionPrepareToEncodeFrames(vtool_data->enc);
574
575 PJ_LOG(4, (THIS_FILE, "Video Toolbox encoder bitrate initialized to "
576 "%d avg bps and %d max bps",
577 param->enc_fmt.det.vid.avg_bps,
578 param->enc_fmt.det.vid.max_bps));
579
580 return ret;
581 }
582
583
584 static pj_status_t vtool_codec_open(pjmedia_vid_codec *codec,
585 pjmedia_vid_codec_param *codec_param )
586 {
587 vtool_codec_data *vtool_data;
588 pjmedia_vid_codec_param *param;
589 pjmedia_h264_packetizer_cfg pktz_cfg;
590 pjmedia_vid_codec_h264_fmtp h264_fmtp;
591 pj_status_t status;
592 OSStatus ret;
593
594 PJ_ASSERT_RETURN(codec && codec_param, PJ_EINVAL);
595
596 PJ_LOG(5,(THIS_FILE, "Opening codec.."));
597
598 vtool_data = (vtool_codec_data*) codec->codec_data;
599 vtool_data->prm = pjmedia_vid_codec_param_clone( vtool_data->pool,
600 codec_param);
601 param = vtool_data->prm;
602
603 /* Parse remote fmtp */
604 pj_bzero(&h264_fmtp, sizeof(h264_fmtp));
605 status = pjmedia_vid_codec_h264_parse_fmtp(&param->enc_fmtp, &h264_fmtp);
606 if (status != PJ_SUCCESS)
607 return status;
608
609 /* Apply SDP fmtp to format in codec param */
610 if (!param->ignore_fmtp) {
611 status = pjmedia_vid_codec_h264_apply_fmtp(param);
612 if (status != PJ_SUCCESS)
613 return status;
614 }
615
616 pj_bzero(&pktz_cfg, sizeof(pktz_cfg));
617 pktz_cfg.mtu = param->enc_mtu;
618 pktz_cfg.unpack_nal_start = 4;
619 /* Packetization mode */
620 if (h264_fmtp.packetization_mode == 0)
621 pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL;
622 else if (h264_fmtp.packetization_mode == 1)
623 pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED;
624 else
625 return PJ_ENOTSUP;
626 /* Video Toolbox encoder doesn't support setting maximum slice size,
627 * so we cannot use single NAL mode since the NAL size likely
628 * exceeds the MTU.
629 */
630 pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED;
631
632 status = pjmedia_h264_packetizer_create(vtool_data->pool, &pktz_cfg,
633 &vtool_data->pktz);
634 if (status != PJ_SUCCESS)
635 return status;
636
637 vtool_data->whole = (param->packing == PJMEDIA_VID_PACKING_WHOLE);
638 if (1) {
639 /* Init format info and apply-param of encoder */
640 const pjmedia_video_format_info *enc_vfi;
641 pjmedia_video_apply_fmt_param enc_vafp;
642
643 enc_vfi = pjmedia_get_video_format_info(NULL,codec_param->dec_fmt.id);
644 if (!enc_vfi)
645 return PJ_EINVAL;
646
647 pj_bzero(&enc_vafp, sizeof(enc_vafp));
648 enc_vafp.size = codec_param->enc_fmt.det.vid.size;
649 enc_vafp.buffer = NULL;
650 status = (*enc_vfi->apply_fmt)(enc_vfi, &enc_vafp);
651 if (status != PJ_SUCCESS)
652 return status;
653
654 vtool_data->enc_wxh = codec_param->enc_fmt.det.vid.size.w *
655 codec_param->enc_fmt.det.vid.size.h;
656 vtool_data->enc_input_size = enc_vafp.framebytes;
657 if (!vtool_data->whole) {
658 vtool_data->enc_buf_size = (unsigned)enc_vafp.framebytes;
659 vtool_data->enc_buf = pj_pool_alloc(vtool_data->pool,
660 vtool_data->enc_buf_size);
661 }
662 }
663
664 /* Create encoder */
665 ret = create_encoder(vtool_data);
666 if (ret != noErr)
667 return PJMEDIA_CODEC_EFAILED;
668
669 /* If available, use the "sprop-parameter-sets" fmtp from remote SDP
670 * to create the decoder.
671 */
672 if (h264_fmtp.sprop_param_sets_len) {
673 const pj_uint8_t start_code[3] = {0, 0, 1};
674 const int code_size = PJ_ARRAY_SIZE(start_code);
675 unsigned i, j;
676
677 for (i = h264_fmtp.sprop_param_sets_len-code_size; i >= code_size;
678 i--)
679 {
680 for (j = 0; j < code_size; j++) {
681 if (h264_fmtp.sprop_param_sets[i+j] != start_code[j]) {
682 break;
683 }
684 }
685 }
686
687 if (i >= code_size) {
688 vtool_data->dec_sps_size = i - code_size;
689 pj_memcpy(vtool_data->dec_sps,
690 &h264_fmtp.sprop_param_sets[code_size],
691 vtool_data->dec_sps_size);
692
693 vtool_data->dec_pps_size = h264_fmtp.sprop_param_sets_len -
694 code_size-i;
695 pj_memcpy(vtool_data->dec_pps,
696 &h264_fmtp.sprop_param_sets[i + code_size],
697 vtool_data->dec_pps_size);
698
699 create_decoder(vtool_data);
700 }
701 }
702
703 /* Create decoder buffer */
704 vtool_data->dec_buf_size = (MAX_RX_WIDTH * MAX_RX_HEIGHT * 3 >> 1) +
705 (MAX_RX_WIDTH);
706 vtool_data->dec_buf = (pj_uint8_t*)pj_pool_alloc(vtool_data->pool,
707 vtool_data->dec_buf_size);
708
709 /* Need to update param back after values are negotiated */
710 pj_memcpy(codec_param, param, sizeof(*codec_param));
711
712 return PJ_SUCCESS;
713 }
714
715 static pj_status_t vtool_codec_close(pjmedia_vid_codec *codec)
716 {
717 struct vtool_codec_data *vtool_data;
718
719 PJ_ASSERT_RETURN(codec, PJ_EINVAL);
720
721 vtool_data = (vtool_codec_data*) codec->codec_data;
722
723 if (vtool_data->enc) {
724 VTCompressionSessionInvalidate(vtool_data->enc);
725 CFRelease(vtool_data->enc);
726 vtool_data->enc = NULL;
727 }
728
729 if (vtool_data->dec) {
730 VTDecompressionSessionInvalidate(vtool_data->dec);
731 CFRelease(vtool_data->dec);
732 vtool_data->dec = NULL;
733 }
734
735 if (vtool_data->dec_format)
736 CFRelease(vtool_data->dec_format);
737
738 return PJ_SUCCESS;
739 }
740
741 static pj_status_t vtool_codec_modify(pjmedia_vid_codec *codec,
742 const pjmedia_vid_codec_param *param)
743 {
744 struct vtool_codec_data *vtool_data;
745 OSStatus ret;
746
747 PJ_ASSERT_RETURN(codec && param, PJ_EINVAL);
748
749 vtool_data = (vtool_codec_data*) codec->codec_data;
750
751 SET_PROPERTY(vtool_data->enc,
752 kVTCompressionPropertyKey_AverageBitRate,
753 (__bridge CFTypeRef)@(param->enc_fmt.det.vid.avg_bps));
754 if (ret != noErr)
755 return PJMEDIA_CODEC_EUNSUP;
756
757 vtool_data->prm->enc_fmt.det.vid.avg_bps = param->enc_fmt.det.vid.avg_bps;
758
759 SET_PROPERTY(vtool_data->enc,
760 kVTCompressionPropertyKey_DataRateLimits,
761 ((__bridge CFArrayRef) // [Bytes, second]
762 @[@(param->enc_fmt.det.vid.max_bps >> 3), @(1)]));
763 if (ret == noErr) {
764 vtool_data->prm->enc_fmt.det.vid.max_bps =
765 param->enc_fmt.det.vid.max_bps;
766
767 PJ_LOG(4, (THIS_FILE, "Video Toolbox encoder bitrate is modified to "
768 "%d avg bps and %d max bps",
769 param->enc_fmt.det.vid.avg_bps,
770 param->enc_fmt.det.vid.max_bps));
771 }
772
773 return PJ_SUCCESS;
774 }
775
776 static pj_status_t vtool_codec_get_param(pjmedia_vid_codec *codec,
777 pjmedia_vid_codec_param *param)
778 {
779 struct vtool_codec_data *vtool_data;
780
781 PJ_ASSERT_RETURN(codec && param, PJ_EINVAL);
782
783 vtool_data = (vtool_codec_data*) codec->codec_data;
784 pj_memcpy(param, vtool_data->prm, sizeof(*param));
785
786 return PJ_SUCCESS;
787 }
788
789 static pj_status_t vtool_codec_encode_begin(pjmedia_vid_codec *codec,
790 const pjmedia_vid_encode_opt *opt,
791 const pjmedia_frame *input,
792 unsigned out_size,
793 pjmedia_frame *output,
794 pj_bool_t *has_more)
795 {
796 struct vtool_codec_data *vtool_data;
797 CMTime ts, dur;
798 CVImageBufferRef image_buf;
799 void *base_addr[3];
800 size_t plane_w[3], plane_h[3], plane_bpr[3];
801 NSDictionary *frm_prop = NULL;
802 OSStatus ret;
803
804 PJ_ASSERT_RETURN(codec && input && out_size && output && has_more,
805 PJ_EINVAL);
806
807 vtool_data = (vtool_codec_data*) codec->codec_data;
808
809 base_addr[0] = input->buf;
810 base_addr[1] = input->buf + vtool_data->enc_wxh;
811 base_addr[2] = base_addr[1] + (vtool_data->enc_wxh >> 2);
812 plane_w[0] = vtool_data->prm->enc_fmt.det.vid.size.w;
813 plane_h[0] = vtool_data->prm->enc_fmt.det.vid.size.h;
814 plane_w[1] = plane_w[2] = vtool_data->prm->enc_fmt.det.vid.size.w >> 1;
815 plane_h[1] = plane_h[2] = vtool_data->prm->enc_fmt.det.vid.size.h >> 1;
816 plane_bpr[0] = vtool_data->prm->enc_fmt.det.vid.size.w;
817 plane_bpr[1] = plane_bpr[2] = vtool_data->prm->enc_fmt.det.vid.size.w >> 1;
818
819 #if TARGET_OS_IPHONE
820 ret = CVPixelBufferCreate(NULL,
821 vtool_data->prm->enc_fmt.det.vid.size.w,
822 vtool_data->prm->enc_fmt.det.vid.size.h,
823 kCVPixelFormatType_420YpCbCr8Planar, /* I420 */
824 NULL, &image_buf);
825 if (ret == noErr) {
826 size_t i, count;
827
828 CVPixelBufferLockBaseAddress(image_buf, 0);
829
830 count = CVPixelBufferGetPlaneCount(image_buf);
831 for (i = 0; i < count; i++) {
832 char *ptr = (char*)CVPixelBufferGetBaseAddressOfPlane(image_buf, i);
833 char *src = (char*)base_addr[i];
834 size_t bpr = CVPixelBufferGetBytesPerRowOfPlane(image_buf, i);
835 int j;
836
837 pj_assert(bpr >= plane_bpr[i]);
838 for (j = 0; j < plane_h[i]; ++j) {
839 pj_memcpy(ptr, src, plane_bpr[i]);
840 src += plane_bpr[i];
841 ptr += bpr;
842 }
843 }
844
845 CVPixelBufferUnlockBaseAddress(image_buf, 0);
846 }
847 #else
848 ret = CVPixelBufferCreateWithPlanarBytes(NULL,
849 vtool_data->prm->enc_fmt.det.vid.size.w,
850 vtool_data->prm->enc_fmt.det.vid.size.h,
851 kCVPixelFormatType_420YpCbCr8Planar, /* I420 */
852 NULL, vtool_data->enc_input_size,
853 3, /* number of planes of I420 */
854 base_addr,
855 (size_t *)plane_w, (size_t *)plane_h, (size_t *)plane_bpr,
856 NULL, NULL, NULL, &image_buf);
857 #endif
858
859 if (ret != noErr) {
860 PJ_LOG(4,(THIS_FILE, "Failed to create pixel buffer"));
861 return PJMEDIA_CODEC_EFAILED;
862 }
863
864 ts = CMTimeMake(++vtool_data->enc_frm_cnt, vtool_data->enc_fps);
865 dur = CMTimeMake(1, vtool_data->enc_fps);
866 vtool_data->enc_frame_size = vtool_data->enc_processed = 0;
867
868 if (vtool_data->whole) {
869 vtool_data->enc_buf = output->buf;
870 vtool_data->enc_buf_size = out_size;
871 }
872
873 if (opt && opt->force_keyframe) {
874 frm_prop = @{ (__bridge NSString *)
875 kVTEncodeFrameOptionKey_ForceKeyFrame: @YES };
876 }
877
878 ret = VTCompressionSessionEncodeFrame(vtool_data->enc, image_buf,
879 ts, dur,
880 (__bridge CFDictionaryRef)frm_prop,
881 NULL, NULL);
882 if (ret == kVTInvalidSessionErr) {
883 #if TARGET_OS_IPHONE
884 /* Just return if app is not active, i.e. in the bg. */
885 __block UIApplicationState state;
886
887 dispatch_sync_on_main_queue(^{
888 state = [UIApplication sharedApplication].applicationState;
889 });
890 if (state != UIApplicationStateActive) {
891 *has_more = PJ_FALSE;
892 output->size = 0;
893 output->type = PJMEDIA_FRAME_TYPE_NONE;
894
895 CVPixelBufferRelease(image_buf);
896 return PJ_SUCCESS;
897 }
898 #endif
899
900 /* Reset compression session */
901 ret = create_encoder(vtool_data);
902 PJ_LOG(3,(THIS_FILE, "Encoder needs to be reset [1]: %s (%d)",
903 (ret == noErr? "success": "fail"), ret));
904 if (ret == noErr) {
905 /* Retry encoding the frame after successful encoder reset. */
906 ret = VTCompressionSessionEncodeFrame(vtool_data->enc, image_buf,
907 ts, dur,
908 (__bridge CFDictionaryRef)
909 frm_prop,
910 NULL, NULL);
911 }
912 }
913
914 if (ret != noErr) {
915 PJ_LOG(4,(THIS_FILE, "Failed to encode frame %d", ret));
916 CVPixelBufferRelease(image_buf);
917 return PJMEDIA_CODEC_EFAILED;
918 }
919
920 /* EncodeFrame is async, so tell it to finish the encoding. */
921 ts.flags = kCMTimeFlags_Indefinite;
922 ret = VTCompressionSessionCompleteFrames(vtool_data->enc, ts);
923 if (ret == kVTInvalidSessionErr) {
924 /* Reset compression session */
925 ret = create_encoder(vtool_data);
926 PJ_LOG(3,(THIS_FILE, "Encoder needs to be reset [2]: %s (%d)",
927 (ret == noErr? "success": "fail"), ret));
928 if (ret == PJ_SUCCESS) {
929 /* Retry finishing the encoding after successful encoder reset. */
930 ret = VTCompressionSessionCompleteFrames(vtool_data->enc, ts);
931 }
932 }
933
934 if (ret != noErr) {
935 PJ_LOG(4,(THIS_FILE, "Failed to complete encoding %d", ret));
936 CVPixelBufferRelease(image_buf);
937 return PJMEDIA_CODEC_EFAILED;
938 }
939
940 CVPixelBufferRelease(image_buf);
941
942 if (vtool_data->whole) {
943 *has_more = PJ_FALSE;
944 output->size = vtool_data->enc_frame_size;
945 return PJ_SUCCESS;
946 }
947
948 return vtool_codec_encode_more(codec, out_size, output, has_more);
949 }
950
951
952 static pj_status_t vtool_codec_encode_more(pjmedia_vid_codec *codec,
953 unsigned out_size,
954 pjmedia_frame *output,
955 pj_bool_t *has_more)
956 {
957 struct vtool_codec_data *vtool_data;
958 const pj_uint8_t *payload;
959 pj_size_t payload_len;
960 pj_status_t status;
961
962 PJ_ASSERT_RETURN(codec && out_size && output && has_more,
963 PJ_EINVAL);
964
965 vtool_data = (vtool_codec_data*) codec->codec_data;
966
967 if (vtool_data->enc_processed >= vtool_data->enc_frame_size) {
968 /* No more frame */
969 *has_more = PJ_FALSE;
970 output->size = 0;
971 output->type = PJMEDIA_FRAME_TYPE_NONE;
972
973 return PJ_SUCCESS;
974 }
975
976 /* We have outstanding frame in packetizer */
977 status = pjmedia_h264_packetize(vtool_data->pktz,
978 (pj_uint8_t*)vtool_data->enc_buf,
979 vtool_data->enc_frame_size,
980 &vtool_data->enc_processed,
981 &payload, &payload_len);
982 if (status != PJ_SUCCESS) {
983 /* Reset */
984 vtool_data->enc_frame_size = vtool_data->enc_processed = 0;
985 *has_more = (vtool_data->enc_processed < vtool_data->enc_frame_size);
986
987 PJ_PERROR(4,(THIS_FILE, status, "pjmedia_h264_packetize() error"));
988 return status;
989 }
990
991 PJ_ASSERT_RETURN(payload_len <= out_size, PJMEDIA_CODEC_EFRMTOOSHORT);
992
993 output->type = PJMEDIA_FRAME_TYPE_VIDEO;
994 pj_memcpy(output->buf, payload, payload_len);
995 output->size = payload_len;
996 if (vtool_data->enc_is_keyframe)
997 output->bit_info |= PJMEDIA_VID_FRM_KEYFRAME;
998
999 *has_more = (vtool_data->enc_processed < vtool_data->enc_frame_size);
1000 return PJ_SUCCESS;
1001 }
1002
1003
1004 /* Copy I420 frame from source to destination and clip if necessary */
1005 static int process_i420(CVImageBufferRef src_buf, pj_uint8_t *dst)
1006 {
1007 pj_uint8_t *pdst = dst;
1008 pj_size_t i, count;
1009
1010 count = CVPixelBufferGetPlaneCount(src_buf);
1011 for (i = 0; i < count; i++) {
1012 pj_uint8_t *psrc;
1013 pj_size_t src_w, dst_w, h;
1014
1015 psrc = CVPixelBufferGetBaseAddressOfPlane(src_buf, i);
1016 src_w = CVPixelBufferGetBytesPerRowOfPlane(src_buf, i);
1017 dst_w = CVPixelBufferGetWidthOfPlane(src_buf, i);
1018 h = CVPixelBufferGetHeightOfPlane(src_buf, i);
1019
1020 /* Check if clipping is required */
1021 if (src_w == dst_w) {
1022 pj_size_t plane_size = dst_w * h;
1023 pj_memcpy(pdst, psrc, plane_size);
1024 pdst += plane_size;
1025 } else {
1026 pj_size_t j = 0;
1027 for (; j < h; ++j) {
1028 pj_memcpy(pdst, psrc, dst_w);
1029 pdst += dst_w;
1030 psrc += src_w;
1031 }
1032 }
1033 }
1034
1035 return (pdst - dst);
1036 }
1037
1038
1039 static void decode_cb(void *decompressionOutputRefCon,
1040 void *sourceFrameRefCon,
1041 OSStatus status,
1042 VTDecodeInfoFlags infoFlags,
1043 CVImageBufferRef imageBuffer,
1044 CMTime presentationTimeStamp,
1045 CMTime presentationDuration)
1046 {
1047 struct vtool_codec_data *vtool_data;
1048 pj_size_t width, height, len = 0;
1049
1050 /* This callback can be called from another, unregistered thread.
1051 * So do not call pjlib functions here.
1052 */
1053 vtool_data = (struct vtool_codec_data *)decompressionOutputRefCon;
1054 vtool_data->dec_status = status;
1055 if (vtool_data->dec_status != noErr)
1056 return;
1057
1058 CVPixelBufferLockBaseAddress(imageBuffer,0);
1059
1060 width = CVPixelBufferGetWidth(imageBuffer);
1061 height = CVPixelBufferGetHeight(imageBuffer);
1062
1063 /* Detect format change */
1064 if (width != vtool_data->prm->dec_fmt.det.vid.size.w ||
1065 height != vtool_data->prm->dec_fmt.det.vid.size.h)
1066 {
1067 vtool_data->dec_fmt_change = PJ_TRUE;
1068 vtool_data->prm->dec_fmt.det.vid.size.w = width;
1069 vtool_data->prm->dec_fmt.det.vid.size.h = height;
1070 } else {
1071 vtool_data->dec_fmt_change = PJ_FALSE;
1072 }
1073
1074 if (vtool_data->dec_frame->size >= width * height * 3 / 2) {
1075 len = process_i420(imageBuffer,
1076 (pj_uint8_t *)vtool_data->dec_frame->buf);
1077 } else {
1078 vtool_data->dec_status = (OSStatus)PJMEDIA_CODEC_EFRMTOOSHORT;
1079 }
1080 vtool_data->dec_frame->size = len;
1081
1082 CVPixelBufferUnlockBaseAddress(imageBuffer,0);
1083 }
1084
1085 static OSStatus create_decoder(struct vtool_codec_data *vtool_data)
1086 {
1087 uint8_t *param_ptrs[2] = {vtool_data->dec_sps,
1088 vtool_data->dec_pps};
1089 const size_t param_sizes[2] = {vtool_data->dec_sps_size,
1090 vtool_data->dec_pps_size};
1091 const int code_size = 4; // PJ_ARRAY_SIZE(start_code);
1092 CMFormatDescriptionRef dec_format;
1093 VTDecompressionOutputCallbackRecord cbr;
1094 NSDictionary *dst_attr;
1095 OSStatus ret;
1096
1097 /* Create video format description based on H264 SPS and PPS
1098 * parameters.
1099 */
1100 ret = CMVideoFormatDescriptionCreateFromH264ParameterSets(
1101 kCFAllocatorDefault, 2,
1102 (const uint8_t * const *)param_ptrs,
1103 param_sizes, code_size, &dec_format);
1104 if (ret != noErr) {
1105 PJ_LOG(4,(THIS_FILE, "Failed to create video format "
1106 "description %d", ret));
1107 return ret;
1108 }
1109
1110 if (!vtool_data->dec || !vtool_data->dec_format ||
1111 !CMFormatDescriptionEqual(dec_format, vtool_data->dec_format))
1112 {
1113 if (vtool_data->dec_format)
1114 CFRelease(vtool_data->dec_format);
1115 vtool_data->dec_format = dec_format;
1116 } else {
1117 CFRelease(dec_format);
1118 return noErr;
1119 }
1120
1121 cbr.decompressionOutputCallback = decode_cb;
1122 cbr.decompressionOutputRefCon = vtool_data;
1123
1124 if (vtool_data->dec) {
1125 VTDecompressionSessionInvalidate(vtool_data->dec);
1126 CFRelease(vtool_data->dec);
1127 vtool_data->dec = NULL;
1128 }
1129
1130 dst_attr = [NSDictionary dictionaryWithObjectsAndKeys:
1131 [NSNumber numberWithInt: /* I420 */
1132 kCVPixelFormatType_420YpCbCr8Planar],
1133 kCVPixelBufferPixelFormatTypeKey,
1134 nil];
1135 ret = VTDecompressionSessionCreate(NULL, vtool_data->dec_format, NULL,
1136 (__bridge CFDictionaryRef)dst_attr,
1137 &cbr, &vtool_data->dec);
1138 if (ret != noErr) {
1139 PJ_LOG(3,(THIS_FILE, "Failed to create decompression session %d",
1140 ret));
1141 }
1142
1143 SET_PROPERTY(vtool_data->dec, kVTCompressionPropertyKey_RealTime,
1144 kCFBooleanTrue);
1145 #if !TARGET_OS_IPHONE
1146 SET_PROPERTY(vtool_data->dec,
1147 kVTVideoDecoderSpecification_EnableHardwareAcceleratedVideoDecoder,
1148 kCFBooleanTrue);
1149 #endif
1150
1151 return ret;
1152 }
1153
1154 static pj_status_t vtool_codec_decode(pjmedia_vid_codec *codec,
1155 pj_size_t count,
1156 pjmedia_frame packets[],
1157 unsigned out_size,
1158 pjmedia_frame *output)
1159 {
1160 struct vtool_codec_data *vtool_data;
1161 const pj_uint8_t start_code[] = { 0, 0, 0, 1 };
1162 const int code_size = PJ_ARRAY_SIZE(start_code);
1163 pj_bool_t has_frame = PJ_FALSE;
1164 unsigned buf_pos, whole_len = 0;
1165 unsigned i;
1166 pj_status_t status = PJ_SUCCESS;
1167 pj_bool_t decode_whole = DECODE_WHOLE;
1168 OSStatus ret;
1169
1170 PJ_ASSERT_RETURN(codec && count && packets && out_size && output,
1171 PJ_EINVAL);
1172 PJ_ASSERT_RETURN(output->buf, PJ_EINVAL);
1173
1174 vtool_data = (vtool_codec_data*) codec->codec_data;
1175
1176 /*
1177 * Step 1: unpacketize the packets/frames
1178 */
1179 whole_len = 0;
1180 if (vtool_data->whole) {
1181 for (i=0; i<count; ++i) {
1182 if (whole_len + packets[i].size > vtool_data->dec_buf_size) {
1183 PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow"));
1184 status = PJMEDIA_CODEC_EFRMTOOSHORT;
1185 break;
1186 }
1187
1188 pj_memcpy( vtool_data->dec_buf + whole_len,
1189 (pj_uint8_t*)packets[i].buf,
1190 packets[i].size);
1191 whole_len += packets[i].size;
1192 }
1193
1194 } else {
1195 for (i=0; i<count; ++i) {
1196 if (whole_len + packets[i].size + code_size >
1197 vtool_data->dec_buf_size)
1198 {
1199 PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow [1]"));
1200 status = PJMEDIA_CODEC_EFRMTOOSHORT;
1201 break;
1202 }
1203
1204 status = pjmedia_h264_unpacketize( vtool_data->pktz,
1205 (pj_uint8_t*)packets[i].buf,
1206 packets[i].size,
1207 vtool_data->dec_buf,
1208 vtool_data->dec_buf_size,
1209 &whole_len);
1210 if (status != PJ_SUCCESS) {
1211 PJ_PERROR(4,(THIS_FILE, status, "Unpacketize error"));
1212 continue;
1213 }
1214 }
1215 }
1216
1217 if (whole_len + code_size > vtool_data->dec_buf_size ||
1218 whole_len <= code_size + 1)
1219 {
1220 PJ_LOG(4,(THIS_FILE, "Decoding buffer overflow or unpacketize error "
1221 "size: %d, buffer: %d", whole_len,
1222 vtool_data->dec_buf_size));
1223 status = PJMEDIA_CODEC_EFRMTOOSHORT;
1224 }
1225
1226 if (status != PJ_SUCCESS)
1227 goto on_return;
1228
1229 /* Dummy NAL sentinel */
1230 pj_memcpy(vtool_data->dec_buf + whole_len, start_code, code_size);
1231
1232 /*
1233 * Step 2: parse the individual NAL and give to decoder
1234 */
1235 buf_pos = 0;
1236 while (1) {
1237 uint32_t frm_size, nalu_type, data_length;
1238 unsigned char *start;
1239
1240 for (i = code_size - 1; buf_pos + i < whole_len; i++) {
1241 if (vtool_data->dec_buf[buf_pos + i] == 0 &&
1242 vtool_data->dec_buf[buf_pos + i + 1] == 0 &&
1243 vtool_data->dec_buf[buf_pos + i + 2] == 0 &&
1244 vtool_data->dec_buf[buf_pos + i + 3] == 1)
1245 {
1246 break;
1247 }
1248 }
1249
1250 frm_size = i;
1251 start = vtool_data->dec_buf + buf_pos;
1252 nalu_type = (start[code_size] & 0x1F);
1253
1254 #if TARGET_OS_IPHONE
1255 /* On iOS, packets preceded by SEI frame (type 6), such as the ones
1256 * sent by Mac VideoToolbox encoder will cause DecodeFrame to fail
1257 * with -12911 (kVTVideoDecoderMalfunctionErr). The workaround
1258 * is to decode the whole packets at once.
1259 */
1260 if (nalu_type == 6)
1261 decode_whole = PJ_TRUE;
1262 #endif
1263
1264 /* AVCC format requires us to replace the start code header
1265 * on this NAL with its frame size.
1266 */
1267 data_length = pj_htonl(frm_size - code_size);
1268 pj_memcpy(start, &data_length, sizeof (data_length));
1269
1270 if (nalu_type == 7) {
1271 /* NALU type 7 is the SPS parameter NALU */
1272 vtool_data->dec_sps_size = PJ_MIN(frm_size - code_size,
1273 sizeof(vtool_data->dec_sps));
1274 pj_memcpy(vtool_data->dec_sps, &start[code_size],
1275 vtool_data->dec_sps_size);
1276 } else if (nalu_type == 8) {
1277 /* NALU type 8 is the PPS parameter NALU */
1278 vtool_data->dec_pps_size = PJ_MIN(frm_size - code_size,
1279 sizeof(vtool_data->dec_pps));
1280 pj_memcpy(vtool_data->dec_pps, &start[code_size],
1281 vtool_data->dec_pps_size);
1282
1283 ret = create_decoder(vtool_data);
1284 } else if (vtool_data->dec &&
1285 (!decode_whole || (buf_pos + frm_size >= whole_len)))
1286 {
1287 CMBlockBufferRef block_buf = NULL;
1288 CMSampleBufferRef sample_buf = NULL;
1289
1290 if (decode_whole) {
1291 /* We decode all the packets at once. */
1292 frm_size = whole_len;
1293 start = vtool_data->dec_buf;
1294 }
1295
1296 /* Create a block buffer from the NALU */
1297 ret = CMBlockBufferCreateWithMemoryBlock(NULL,
1298 start, frm_size,
1299 kCFAllocatorNull, NULL,
1300 0, frm_size,
1301 0, &block_buf);
1302 if (ret == noErr) {
1303 const size_t sample_size = frm_size;
1304 ret = CMSampleBufferCreate(kCFAllocatorDefault,
1305 block_buf, true, NULL, NULL,
1306 vtool_data->dec_format,
1307 1, 0, NULL, 1,
1308 &sample_size, &sample_buf);
1309 if (ret != noErr) {
1310 PJ_LOG(4,(THIS_FILE, "Failed to create sample buffer"));
1311 CFRelease(block_buf);
1312 }
1313 } else {
1314 PJ_LOG(4,(THIS_FILE, "Failed to create block buffer"));
1315 }
1316
1317 if (ret == noErr) {
1318 vtool_data->dec_frame = output;
1319 vtool_data->dec_frame->size = out_size;
1320 ret = VTDecompressionSessionDecodeFrame(
1321 vtool_data->dec, sample_buf, 0,
1322 NULL, NULL);
1323 if (ret == kVTInvalidSessionErr) {
1324 #if TARGET_OS_IPHONE
1325 /* Just return if app is not active, i.e. in the bg. */
1326 __block UIApplicationState state;
1327
1328 dispatch_sync_on_main_queue(^{
1329 state = [UIApplication sharedApplication].applicationState;
1330 });
1331 if (state != UIApplicationStateActive) {
1332 output->type = PJMEDIA_FRAME_TYPE_NONE;
1333 output->size = 0;
1334 output->timestamp = packets[0].timestamp;
1335
1336 CFRelease(block_buf);
1337 CFRelease(sample_buf);
1338 return PJ_SUCCESS;
1339 }
1340 #endif
1341 if (vtool_data->dec_format)
1342 CFRelease(vtool_data->dec_format);
1343 vtool_data->dec_format = NULL;
1344 ret = create_decoder(vtool_data);
1345 PJ_LOG(3,(THIS_FILE, "Decoder needs to be reset: %s (%d)",
1346 (ret == noErr? "success": "fail"), ret));
1347
1348 if (ret == noErr) {
1349 /* Retry decoding the frame after successful reset */
1350 ret = VTDecompressionSessionDecodeFrame(
1351 vtool_data->dec, sample_buf, 0,
1352 NULL, NULL);
1353 }
1354 }
1355
1356 if ((ret != noErr) || (vtool_data->dec_status != noErr)) {
1357 char *ret_err = (ret != noErr)?"decode err":"cb err";
1358 OSStatus err_code = (ret != noErr)? ret:
1359 vtool_data->dec_status;
1360
1361 PJ_LOG(5,(THIS_FILE, "Failed to decode frame %d of size "
1362 "%d %s:%d", nalu_type, frm_size, ret_err,
1363 err_code));
1364 } else {
1365 has_frame = PJ_TRUE;
1366 output->type = PJMEDIA_FRAME_TYPE_VIDEO;
1367 output->timestamp = packets[0].timestamp;
1368
1369 /* Broadcast format changed event */
1370 if (vtool_data->dec_fmt_change) {
1371 pjmedia_event event;
1372
1373 PJ_LOG(4,(THIS_FILE, "Frame size changed to %dx%d",
1374 vtool_data->prm->dec_fmt.det.vid.size.w,
1375 vtool_data->prm->dec_fmt.det.vid.size.h));
1376
1377 /* Broadcast format changed event */
1378 pjmedia_event_init(&event, PJMEDIA_EVENT_FMT_CHANGED,
1379 &output->timestamp, codec);
1380 event.data.fmt_changed.dir = PJMEDIA_DIR_DECODING;
1381 pjmedia_format_copy(&event.data.fmt_changed.new_fmt,
1382 &vtool_data->prm->dec_fmt);
1383 pjmedia_event_publish(NULL, codec, &event,
1384 PJMEDIA_EVENT_PUBLISH_DEFAULT);
1385 }
1386 }
1387
1388 CFRelease(block_buf);
1389 CFRelease(sample_buf);
1390 }
1391 }
1392
1393 if (buf_pos + frm_size >= whole_len)
1394 break;
1395
1396 buf_pos += frm_size;
1397 }
1398
1399 on_return:
1400 if (!has_frame) {
1401 pjmedia_event event;
1402
1403 /* Broadcast missing keyframe event */
1404 pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_MISSING,
1405 &packets[0].timestamp, codec);
1406 pjmedia_event_publish(NULL, codec, &event,
1407 PJMEDIA_EVENT_PUBLISH_DEFAULT);
1408
1409 PJ_LOG(5,(THIS_FILE, "Decode couldn't produce picture, "
1410 "input nframes=%lu, concatenated size=%d bytes",
1411 (unsigned long)count, whole_len));
1412
1413 output->type = PJMEDIA_FRAME_TYPE_NONE;
1414 output->size = 0;
1415 output->timestamp = packets[0].timestamp;
1416 }
1417
1418 return PJ_SUCCESS;
1419 }
1420
1421 #endif /* PJMEDIA_HAS_VID_TOOLBOX_CODEC */