コード例 #1
0
        /**
         * Constructs the {@link MediaCodecWrapper} wrapper object around the video codec.
         * The codec is created using the encapsulated information in the
         * {@link MediaFormat} object.
         *
         * @param trackFormat The format of the media object to be decoded.
         * @param surface Surface to render the decoded frames.
         * @return
         */
        public static MediaCodecWrapper fromVideoFormat(MediaFormat trackFormat,
                                                        Surface surface)
        {
            MediaCodecWrapper result     = null;
            MediaCodec        videoCodec = null;

            // BEGIN_INCLUDE(create_codec)
            string mimeType = trackFormat.GetString(MediaFormat.KeyMime);

            // Check to see if this is actually a video mime type. If it is, then create
            // a codec that can decode this mime type.
            if (mimeType.Contains("video/"))
            {
                videoCodec = MediaCodec.CreateDecoderByType(mimeType);
                videoCodec.Configure(trackFormat, surface, null, 0);
            }

            // If codec creation was successful, then create a wrapper object around the
            // newly created codec.
            if (videoCodec != null)
            {
                result = new MediaCodecWrapper(videoCodec);
            }
            // END_INCLUDE(create_codec)

            return(result);
        }
コード例 #2
0
ファイル: Video.cs プロジェクト: marklauter/TelloLib
            private static void Init()
            {
                MediaFormat videoFormat = MediaFormat.CreateVideoFormat("video/avc", width, height);

                videoFormat.SetByteBuffer("csd-0", ByteBuffer.Wrap(sps));
                videoFormat.SetByteBuffer("csd-1", ByteBuffer.Wrap(pps));

                string str = videoFormat.GetString("mime");

                try
                {
                    var cdx = MediaCodec.CreateDecoderByType(str);
                    cdx.Configure(videoFormat, picSurface, (MediaCrypto)null, 0);
                    cdx.SetVideoScalingMode(VideoScalingMode.ScaleToFit);
                    cdx.Start();

                    picCodec = cdx;
                    //codec = picCodec;
                }
                catch (Exception ex)
                {
                }


                videoFormat = MediaFormat.CreateVideoFormat("video/avc", 1280, 720);
                videoFormat.SetByteBuffer("csd-0", ByteBuffer.Wrap(vidSps));
                videoFormat.SetByteBuffer("csd-1", ByteBuffer.Wrap(pps));

                try
                {
                    var cdx = MediaCodec.CreateDecoderByType(videoFormat.GetString("mime"));
                    cdx.Configure(videoFormat, vidSurface, (MediaCrypto)null, 0);
                    cdx.SetVideoScalingMode(VideoScalingMode.ScaleToFit);
                    cdx.Start();

                    vidCodec = cdx;
                }
                catch (Exception ex)
                {
                }

                bConfigured = true;
            }
コード例 #3
0
        private void Init()
        {
            if (sps.Length == 14)
                decoderWidth = 1280;
            else
                decoderWidth = 960;

            MediaFormat videoFormat = MediaFormat.CreateVideoFormat("video/avc", decoderWidth, decoderHeight);
            videoFormat.SetByteBuffer("csd-0", ByteBuffer.Wrap(sps));
            videoFormat.SetByteBuffer("csd-1", ByteBuffer.Wrap(pps));

            string str = videoFormat.GetString("mime");
            try
            {
                var cdx = MediaCodec.CreateDecoderByType(str);
                cdx.Configure(videoFormat, Holder.Surface, (MediaCrypto)null, 0);
                cdx.SetVideoScalingMode(VideoScalingMode.ScaleToFit);
                cdx.Start();

                codec = cdx;
            }
            catch (Exception ex)
            {
//handle
            }

            bConfigured = true;

            //set surface aspect ratio
            MainActivity.getActivity().RunOnUiThread(() =>
            {
                float videoProportion = (float)decoderWidth / (float)decoderHeight;

                var size = new Android.Graphics.Point();
                MainActivity.getActivity().WindowManager.DefaultDisplay.GetSize(size);
                int screenWidth = size.X;
                int screenHeight = size.Y;
                float screenProportion = (float)screenWidth / (float)screenHeight;

                var lp = this.LayoutParameters;
                if (videoProportion > screenProportion)
                {
                    lp.Width = screenWidth;
                    lp.Height = (int)((float)screenWidth / videoProportion);
                }
                else
                {
                    lp.Width = (int)(videoProportion * (float)screenHeight);
                    lp.Height = screenHeight;
                }

                this.LayoutParameters = lp;
            });

        }
コード例 #4
0
        public static Java.Lang.String printTransformationStats(Context context, IList <TrackTransformationInfo> stats)
        {
            if (stats == null || stats.Any() == false)
            {
                return(new Java.Lang.String(context.GetString(Resource.String.no_transformation_stats)));
            }

            StringBuilder statsStringBuilder = new StringBuilder();

            for (int track = 0; track < stats.Count; track++)
            {
                statsStringBuilder.AppendLine(context.GetString(Resource.String.stats_track, track));

                TrackTransformationInfo trackTransformationInfo = stats[track];
                MediaFormat             sourceFormat            = trackTransformationInfo.SourceFormat;
                String mimeType = null;
                if (sourceFormat.ContainsKey(MediaFormat.KeyMime))
                {
                    mimeType = sourceFormat.GetString(MediaFormat.KeyMime);
                }
                if (mimeType != null && mimeType.StartsWith("video"))
                {
                    statsStringBuilder.AppendLine(context.GetString(Resource.String.stats_source_format))
                    .AppendLine(printVideoMetadata(context, sourceFormat))
                    .AppendLine(context.GetString(Resource.String.stats_target_format))
                    .AppendLine(printVideoMetadata(context, trackTransformationInfo.TargetFormat));
                }
                else if (mimeType != null && mimeType.StartsWith("audio"))
                {
                    statsStringBuilder.AppendLine(context.GetString(Resource.String.stats_source_format))
                    .AppendLine(printAudioMetadata(context, sourceFormat))
                    .AppendLine(context.GetString(Resource.String.stats_target_format))
                    .AppendLine(printAudioMetadata(context, trackTransformationInfo.TargetFormat));
                }
                else if (mimeType != null && mimeType.StartsWith("image"))
                {
                    statsStringBuilder.AppendLine(context.GetString(Resource.String.stats_source_format))
                    .AppendLine(printImageMetadata(context, sourceFormat))
                    .AppendLine(context.GetString(Resource.String.stats_target_format))
                    .AppendLine(printImageMetadata(context, trackTransformationInfo.TargetFormat));
                }
                else
                {
                    statsStringBuilder.AppendLine(context.GetString(Resource.String.stats_source_format))
                    .AppendLine(printGenericMetadata(context, sourceFormat))
                    .AppendLine(context.GetString(Resource.String.stats_target_format))
                    .AppendLine(printGenericMetadata(context, trackTransformationInfo.TargetFormat));
                }
                statsStringBuilder.AppendLine(context.GetString(Resource.String.stats_decoder, trackTransformationInfo.DecoderCodec))
                .AppendLine(context.GetString(Resource.String.stats_encoder, trackTransformationInfo.EncoderCodec))
                .AppendLine(context.GetString(Resource.String.stats_transformation_duration, trackTransformationInfo.Duration))
                .AppendLine("\n");
            }
            return(new Java.Lang.String(statsStringBuilder.ToString()));
        }
コード例 #5
0
        protected void updateSourceMedia(SourceMedia sourceMedia, Android.Net.Uri uri)
        {
            sourceMedia.uri = uri;
            sourceMedia.size = TranscoderUtils.GetSize(this, uri);
            sourceMedia.duration = getMediaDuration(uri) / 1000f;

            try
            {
                MediaExtractor mediaExtractor = new MediaExtractor();
                mediaExtractor.SetDataSource(this, uri, null);
                sourceMedia.tracks = new List<MediaTrackFormat>(mediaExtractor.TrackCount);

                for (int track = 0; track < mediaExtractor.TrackCount; track++)
                {
                    MediaFormat mediaFormat = mediaExtractor.GetTrackFormat(track);
                    var mimeType = mediaFormat.GetString(MediaFormat.KeyMime);
                    if (mimeType == null)
                    {
                        continue;
                    }

                    if (mimeType.StartsWith("video"))
                    {
                        VideoTrackFormat videoTrack = new VideoTrackFormat(track, mimeType);
                        videoTrack.width = getInt(mediaFormat, MediaFormat.KeyWidth);
                        videoTrack.height = getInt(mediaFormat, MediaFormat.KeyHeight);
                        videoTrack.duration = getLong(mediaFormat, MediaFormat.KeyDuration);
                        videoTrack.frameRate = MediaFormatUtils.GetFrameRate(mediaFormat, new Java.Lang.Integer(-1)).IntValue();
                        videoTrack.keyFrameInterval = MediaFormatUtils.GetIFrameInterval(mediaFormat, new Java.Lang.Integer(-1)).IntValue();
                        videoTrack.rotation = getInt(mediaFormat, TrackMetadataUtil.KEY_ROTATION, 0);
                        videoTrack.bitrate = getInt(mediaFormat, MediaFormat.KeyBitRate);
                        sourceMedia.tracks.Add(videoTrack);
                    }
                    else if (mimeType.StartsWith("audio"))
                    {
                        AudioTrackFormat audioTrack = new AudioTrackFormat(track, mimeType);
                        audioTrack.channelCount = getInt(mediaFormat, MediaFormat.KeyChannelCount);
                        audioTrack.samplingRate = getInt(mediaFormat, MediaFormat.KeySampleRate);
                        audioTrack.duration = getLong(mediaFormat, MediaFormat.KeyDuration);
                        audioTrack.bitrate = getInt(mediaFormat, MediaFormat.KeyBitRate);
                        sourceMedia.tracks.Add(audioTrack);
                    }
                    else
                    {
                        sourceMedia.tracks.Add(new GenericTrackFormat(track, mimeType));
                    }
                }
            }
            catch (IOException ex)
            {
                System.Diagnostics.Debug.WriteLine($"Failed to extract sourceMedia: {ex.Message}");
            }

            sourceMedia.NotifyChange();
        }
コード例 #6
0
 private static String printGenericMetadata(Context context, MediaFormat mediaFormat)
 {
     if (mediaFormat == null)
     {
         return("\n");
     }
     if (mediaFormat.ContainsKey(MediaFormat.KeyMime))
     {
         return(context.GetString(Resource.String.stats_mime_type, mediaFormat.GetString(MediaFormat.KeyMime)));
     }
     return("\n");
 }
コード例 #7
0
        public static MediaFormat GetTrackFormat(MediaExtractor extractor, string mimeType)
        {
            for (int i = 0; i < extractor.TrackCount; i++)
            {
                MediaFormat format        = extractor.GetTrackFormat(i);
                string      trackMimeType = format.GetString(MediaFormat.KeyMime);
                if (mimeType.Equals(trackMimeType))
                {
                    return(format);
                }
            }

            return(null);
        }
コード例 #8
0
        /**
         * 
         * @param filePath
         */
        public void startPlay(string path)
        {
            eosReceived = false;
            mExtractor = new MediaExtractor();
            try
            {
                mExtractor.SetDataSource(path);
            }
            catch (IOException e)
            {
                e.PrintStackTrace();
            }

            int channel = 0;
            for (int i = 0; i < mExtractor.TrackCount; i++)
            {
                MediaFormat format = mExtractor.GetTrackFormat(i);
                string mime = format.GetString(MediaFormat.KeyMime);
                if (mime.StartsWith("audio/"))
                {
                    mExtractor.SelectTrack(i);
                    Log.Debug("TAG", "format : " + format);
                    ByteBuffer csd = format.GetByteBuffer("csd-0");

                    for (int k = 0; k < csd.Capacity(); ++k)
                    {
                        Log.Error("TAG", "csd : " + csd.ToArray<Byte>()[k]);
                    }
                    mSampleRate = format.GetInteger(MediaFormat.KeySampleRate);
                    channel = format.GetInteger(MediaFormat.KeyChannelCount);
                    break;
                }
            }
            MediaFormat format2 = makeAACCodecSpecificData(MediaCodecInfo.CodecProfileLevel.AACObjectLC, mSampleRate, channel);
            if (format2 == null)
                return;

            mDecoder = MediaCodec.createDecoderByType("audio/mp4a-latm");
            mDecoder.configure(format, null, null, 0);

            if (mDecoder == null)
            {
                Log.e("DecodeActivity", "Can't find video info!");
                return;
            }

            mDecoder.start();

            new Thread(AACDecoderAndPlayRunnable).start();
        }
コード例 #9
0
        /**
         * Selects the video track, if any.
         *
         * @return the track index, or -1 if no video track is found.
         */
        private int selectTrack(MediaExtractor extractor)
        {
            // Select the first video track we find, ignore the rest.
            int numTracks = extractor.TrackCount;

            for (int i = 0; i < numTracks; i++)
            {
                MediaFormat format = extractor.GetTrackFormat(i);
                String      mime   = format.GetString(MediaFormat.KeyMime);
                if (mime.StartsWith("video/"))
                {
                    return(i);
                }
            }
            return(-1);
        }
コード例 #10
0
        private int GetVideoTrackIndex(MediaExtractor extractor)
        {
            for (int trackIndex = 0; trackIndex < extractor.TrackCount; trackIndex++)
            {
                MediaFormat format = extractor.GetTrackFormat(trackIndex);

                string mime = format.GetString(MediaFormat.KeyMime);
                if (mime != null)
                {
                    if (mime.Equals("video/avc"))
                    {
                        return(trackIndex);
                    }
                }
            }

            return(-1);
        }
コード例 #11
0
            static public void config(Surface surface, int width, int height, byte[] sps, byte[] pps)
            {
                if (sps == null || pps == null)//not ready.
                {
                    return;
                }

                if (bConfigured)
                {
                    return;
                }

                if (codec != null)
                {
                    stop();
                }

                Decoder.width  = width;
                Decoder.height = height;
                Decoder.sps    = sps;
                Decoder.pps    = pps;
                MediaFormat videoFormat = MediaFormat.CreateVideoFormat("video/avc", width, height);

                videoFormat.SetByteBuffer("csd-0", ByteBuffer.Wrap(sps));
                videoFormat.SetByteBuffer("csd-1", ByteBuffer.Wrap(pps));
                videoFormat.SetInteger("color-format", 19);

                string str = videoFormat.GetString("mime");

                try
                {
                    codec = MediaCodec.CreateDecoderByType(str);
                    codec.Configure(videoFormat, surface, (MediaCrypto)null, 0);
                    codec.SetVideoScalingMode(VideoScalingMode.ScaleToFit);
                    codec.Start();
                    bConfigured = true;
                }
                catch (Exception ex)
                {
                    var errstr = ex.Message.ToString();
                }
            }
コード例 #12
0
        // Selects the video track, if any.
        internal static int FindAudioTrack(MediaExtractor extractor)
        {
            string prefix = "audio/";

            // Select the first video track we find, ignore the rest.
            int numTracks = extractor.TrackCount;

            for (int i = 0; i < numTracks; i++)
            {
                MediaFormat format = extractor.GetTrackFormat(i);
                String      mime   = format.GetString(MediaFormat.KeyMime);
                if (mime.StartsWith(prefix))
                {
                    Logger.Verbose(string.Format("Extractor selected track {0} ({1}): {2}", i, mime, format));
                    return(i);
                }
            }

            return(-1);
        }
コード例 #13
0
        public static MediaFormat GetAudioTrackFormat(string filepath, Android.Net.Uri inputUri = null)
        {
            MediaExtractor extractor = new MediaExtractor();

            if (inputUri != null)
            {
                extractor.SetDataSource(Android.App.Application.Context, inputUri, null);
            }
            else if (filepath != null)
            {
                extractor.SetDataSource(filepath);
            }
            int trackCount = extractor.TrackCount;
            int bufferSize = -1;

            for (int i = 0; i < trackCount; i++)
            {
                MediaFormat format             = extractor.GetTrackFormat(i);
                string      mime               = format.GetString(MediaFormat.KeyMime);
                bool        selectCurrentTrack = false;
                if (mime.StartsWith("audio/"))
                {
                    selectCurrentTrack = true;
                }
                else if (mime.StartsWith("video/"))
                {
                    selectCurrentTrack = false;
                }
                if (selectCurrentTrack)
                {
                    extractor.SelectTrack(i);
                    if (format.ContainsKey(MediaFormat.KeyMaxInputSize))
                    {
                        int newSize = format.GetInteger(MediaFormat.KeyMaxInputSize);
                        bufferSize = newSize > bufferSize ? newSize : bufferSize;
                    }
                    return(format);
                }
            }
            return(null);
        }
コード例 #14
0
        // Selects the video track, if any.
        private static int FindTrack(MediaExtractor extractor, MediaType trackType)
        {
            string prefix = null;

            switch (trackType)
            {
            case MediaType.Video:
                prefix = "video/";
                break;

            case MediaType.Audio:
                prefix = "audio/";
                break;

            default:
                return(-1);
            }

            // Select the first video track we find, ignore the rest.
            int numTracks = extractor.TrackCount;

            for (int i = 0; i < numTracks; i++)
            {
                MediaFormat format = extractor.GetTrackFormat(i);
                String      mime   = format.GetString(MediaFormat.KeyMime);
                if (mime.StartsWith(prefix))
                {
                    if (ListSupportedMediaCodecs.FindDecoderForFormat(format) != null)
                    {
                        Logger.Verbose(string.Format("Extractor selected track {0} ({1}): {2}", i, mime, format));
                        return(i);
                    }
                }
            }

            return(-1);
        }
コード例 #15
0
        private static String printAudioMetadata(Context context, MediaFormat mediaFormat)
        {
            if (mediaFormat == null)
            {
                return("\n");
            }
            StringBuilder stringBuilder = new StringBuilder();

            if (mediaFormat.ContainsKey(MediaFormat.KeyMime))
            {
                stringBuilder.AppendLine(context.GetString(Resource.String.stats_mime_type, mediaFormat.GetString(MediaFormat.KeyMime)));
            }
            if (mediaFormat.ContainsKey(MediaFormat.KeyChannelCount))
            {
                stringBuilder.AppendLine(context.GetString(Resource.String.stats_channel_count, mediaFormat.GetInteger(MediaFormat.KeyChannelCount)));
            }
            if (mediaFormat.ContainsKey(MediaFormat.KeyBitRate))
            {
                stringBuilder.AppendLine(context.GetString(Resource.String.stats_bitrate, mediaFormat.GetInteger(MediaFormat.KeyBitRate)));
            }
            if (mediaFormat.ContainsKey(MediaFormat.KeyDuration))
            {
                stringBuilder.AppendLine(context.GetString(Resource.String.stats_duration, mediaFormat.GetLong(MediaFormat.KeyDuration)));
            }
            if (mediaFormat.ContainsKey(MediaFormat.KeySampleRate))
            {
                stringBuilder.AppendLine(context.GetString(Resource.String.stats_sampling_rate, mediaFormat.GetInteger(MediaFormat.KeySampleRate)));
            }
            return(stringBuilder.ToString());
        }
コード例 #16
0
ファイル: FramesExtract.cs プロジェクト: borisblanc/GrowPea
        public void PrepareEncoder(string path, File _downloaddir)
        {
            MediaCodec     _Decoder  = null;
            MediaExtractor extractor = null;

            _downloadsfilesdir = _downloaddir;


            try {
                //for (int i = 0; i < extractor.TrackCount; i++)
                //{
                //    MediaFormat Format = extractor.GetTrackFormat(i);
                //    //MediaFormat format = MediaFormat.CreateVideoFormat(MIME_TYPE, 640, 360);
                //    String mime = Format.GetString(MediaFormat.KeyMime);
                //    if (mime.StartsWith("video/"))
                //    {

                //            extractor.SelectTrack(i);
                //            _Decoder = MediaCodec.CreateEncoderByType(mime);

                //            _Decoder.Configure(Format, null, null, 0);
                //            break;

                //    }
                //}

                extractor = new MediaExtractor();
                extractor.SetDataSource(path);
                int trackIndex = selectTrack(extractor);
                //if (trackIndex < 0)
                //{
                //    throw new RuntimeException("No video track found in " + inputFile);
                //}
                extractor.SelectTrack(trackIndex);

                MediaFormat format = extractor.GetTrackFormat(trackIndex);

                _Width  = format.GetInteger(MediaFormat.KeyWidth);
                _Height = format.GetInteger(MediaFormat.KeyHeight);


                // Could use width/height from the MediaFormat to get full-size frames.

                //outputSurface = new CodecOutputSurface(saveWidth, saveHeight);

                // Create a MediaCodec decoder, and configure it with the MediaFormat from the
                // extractor.  It's very important to use the format from the extractor because
                // it contains a copy of the CSD-0/CSD-1 codec-specific data chunks.
                String mime = format.GetString(MediaFormat.KeyMime);
                _Decoder = MediaCodec.CreateDecoderByType(mime);
                _Decoder.Configure(format, null, null, 0);
                _Decoder.Start();



                Decode(_Decoder, extractor);
            }
            catch (Exception e)
            {
                Log.Error(TAG, e.Message, e);
                throw;
            }
            finally
            {
                // release everything we grabbed
                //if (outputSurface != null)
                //{
                //    outputSurface.release();
                //    outputSurface = null;
                //}
                if (_Decoder != null)
                {
                    _Decoder.Stop();
                    _Decoder.Release();
                    _Decoder = null;
                }
                if (extractor != null)
                {
                    extractor.Release();
                    extractor = null;
                }
            }

            _TrackIndex = -1;
            //_MuxerStarted = false;
        }
コード例 #17
0
        /**
         * Tests extraction from an MP4 to a series of PNG files.
         * <p>
         * We scale the video to 640x480 for the PNG just to demonstrate that we can scale the
         * video with the GPU.  If the input video has a different aspect ratio, we could preserve
         * it by adjusting the GL viewport to get letterboxing or pillarboxing, but generally if
         * you're extracting frames you don't want black bars.
         */
        public void extractMpegFrames(int saveWidth, int saveHeight)
        {
            MediaCodec         decoder       = null;
            CodecOutputSurface outputSurface = null;
            MediaExtractor     extractor     = null;

            try
            {
                // must be an absolute path The MediaExtractor error messages aren't very useful.  Check to see if the input file exists so we can throw a better one if it's not there.
                File inputFile = new File(_filesdir, INPUT_FILE);
                if (!inputFile.CanRead())
                {
                    throw new FileNotFoundException("Unable to read " + inputFile);
                }

                extractor = new MediaExtractor();
                extractor.SetDataSource(inputFile.ToString());
                int trackIndex = selectTrack(extractor);
                if (trackIndex < 0)
                {
                    throw new RuntimeException("No video track found in " + inputFile);
                }
                extractor.SelectTrack(trackIndex);

                MediaFormat format = extractor.GetTrackFormat(trackIndex);

                if (VERBOSE)
                {
                    Log.Info(TAG, "Video size is " + format.GetInteger(MediaFormat.KeyWidth) + "x" + format.GetInteger(MediaFormat.KeyHeight));
                }


                // Could use width/height from the MediaFormat to get full-size frames.

                outputSurface = new CodecOutputSurface(saveWidth, saveHeight);

                // Create a MediaCodec decoder, and configure it with the MediaFormat from the
                // extractor.  It's very important to use the format from the extractor because
                // it contains a copy of the CSD-0/CSD-1 codec-specific data chunks.
                String mime = format.GetString(MediaFormat.KeyMime);
                decoder = MediaCodec.CreateDecoderByType(mime);
                decoder.Configure(format, outputSurface.getSurface(), null, 0);
                decoder.Start();

                doExtract(extractor, trackIndex, decoder, outputSurface);
            }
            finally
            {
                // release everything we grabbed
                if (outputSurface != null)
                {
                    outputSurface.release();
                    outputSurface = null;
                }
                if (decoder != null)
                {
                    decoder.Stop();
                    decoder.Release();
                    decoder = null;
                }
                if (extractor != null)
                {
                    extractor.Release();
                    extractor = null;
                }
            }
        }
コード例 #18
0
        private static String printImageMetadata(Context context, MediaFormat mediaFormat)
        {
            if (mediaFormat == null)
            {
                return("\n");
            }
            StringBuilder stringBuilder = new StringBuilder();

            if (mediaFormat.ContainsKey(MediaFormat.KeyMime))
            {
                stringBuilder.AppendLine(context.GetString(Resource.String.stats_mime_type, mediaFormat.GetString(MediaFormat.KeyMime)));
            }
            if (mediaFormat.ContainsKey(MediaFormat.KeyWidth))
            {
                stringBuilder.AppendLine(context.GetString(Resource.String.stats_width, mediaFormat.GetInteger(MediaFormat.KeyWidth)));
            }
            if (mediaFormat.ContainsKey(MediaFormat.KeyHeight))
            {
                stringBuilder.AppendLine(context.GetString(Resource.String.stats_height, mediaFormat.GetInteger(MediaFormat.KeyHeight)));
            }
            return(stringBuilder.ToString());
        }
コード例 #19
0
        private static bool genVideoUsingMuxer(String srcPath, String dstPath, long startMicroSeconds, long endMicroSeconds, bool useAudio, bool useVideo)
        {
            if (startMicroSeconds == endMicroSeconds)
            {
                throw new InvalidParameterException("You shit!! end has to be greater than start!!");
            }
            // Set up MediaExtractor to read from the source.
            MediaExtractor extractor = new MediaExtractor();

            extractor.SetDataSource(srcPath);
            int trackCount = extractor.TrackCount;
            // Set up MediaMuxer for the destination.
            var muxer = new MediaMuxer(dstPath, MediaMuxer.OutputFormat.MuxerOutputMpeg4);
            // Set up the tracks and retrieve the max buffer size for selected
            // tracks.
            Dictionary <int, int> indexMap = new Dictionary <int, int>(trackCount);
            int bufferSize = -1;

            for (int i = 0; i < trackCount; i++)
            {
                MediaFormat format             = extractor.GetTrackFormat(i);
                String      mime               = format.GetString(MediaFormat.KeyMime);
                bool        selectCurrentTrack = false;

                if (mime.StartsWith("audio/") && useAudio)
                {
                    selectCurrentTrack = true;
                }
                else if (mime.StartsWith("video/") && useVideo)
                {
                    selectCurrentTrack = true;
                }

                if (selectCurrentTrack)
                {
                    extractor.SelectTrack(i);
                    int dstIndex = muxer.AddTrack(format);
                    indexMap.Add(i, dstIndex);

                    if (format.ContainsKey(MediaFormat.KeyMaxInputSize))
                    {
                        int newSize = format.GetInteger(MediaFormat.KeyMaxInputSize);
                        bufferSize = newSize > bufferSize? newSize : bufferSize;
                    }
                }
            }

            if (bufferSize < 0)
            {
                bufferSize = DEFAULT_BUFFER_SIZE;
            }
            // Set up the orientation and starting time for extractor.
            MediaMetadataRetriever retrieverSrc = new MediaMetadataRetriever();

            retrieverSrc.SetDataSource(srcPath);
            String degreesString = retrieverSrc.ExtractMetadata(MediaMetadataRetriever.MetadataKeyVideoRotation);

            if (degreesString != null)
            {
                int degrees = Integer.ParseInt(degreesString);
                if (degrees >= 0)
                {
                    muxer.SetOrientationHint(degrees);
                }
            }

            if (startMicroSeconds > 0)
            {
                extractor.SeekTo(startMicroSeconds, MediaExtractor.SeekToClosestSync);
            }
            // Copy the samples from MediaExtractor to MediaMuxer. We will loop
            // for copying each sample and stop when we get to the end of the source
            // file or exceed the end time of the trimming.
            int        offset     = 0;
            int        trackIndex = -1;
            ByteBuffer dstBuf     = ByteBuffer.Allocate(bufferSize);

            MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();

            try
            {
                muxer.Start();
                while (true)
                {
                    bufferInfo.Offset = offset;
                    bufferInfo.Size   = extractor.ReadSampleData(dstBuf, offset);
                    if (bufferInfo.Size < 0)
                    {
                        Log.Info(LOGTAG, "Saw input EOS.");
                        bufferInfo.Size = 0;
                        break;
                    }
                    else
                    {
                        bufferInfo.PresentationTimeUs = extractor.SampleTime;
                        if (endMicroSeconds > 0 && bufferInfo.PresentationTimeUs > endMicroSeconds)
                        {
                            Log.Info(LOGTAG, "The current sample is over the trim end time.");
                            break;
                        }
                        else
                        {
                            bufferInfo.Flags = GetSyncsampleflags(extractor.SampleFlags); //had to map this shit not sure if its right
                            trackIndex       = extractor.SampleTrackIndex;
                            muxer.WriteSampleData(indexMap[trackIndex], dstBuf, bufferInfo);
                            extractor.Advance();
                        }
                    }
                }
                muxer.Stop();
            }
            catch (IllegalStateException e)
            {
                // Swallow the exception due to malformed source.
                Log.Info(LOGTAG, "The source video file is malformed");
                return(false);
            }
            finally
            {
                muxer.Release();
            }
            return(true);
        }
コード例 #20
0
        private static String printVideoMetadata(Context context, MediaFormat mediaFormat)
        {
            if (mediaFormat == null)
            {
                return("\n");
            }
            StringBuilder stringBuilder = new StringBuilder();

            if (mediaFormat.ContainsKey(MediaFormat.KeyMime))
            {
                stringBuilder.AppendLine(context.GetString(Resource.String.stats_mime_type, mediaFormat.GetString(MediaFormat.KeyMime)));
            }
            if (mediaFormat.ContainsKey(MediaFormat.KeyWidth))
            {
                stringBuilder.AppendLine(context.GetString(Resource.String.stats_width, mediaFormat.GetInteger(MediaFormat.KeyWidth)));
            }
            if (mediaFormat.ContainsKey(MediaFormat.KeyHeight))
            {
                stringBuilder.AppendLine(context.GetString(Resource.String.stats_height, mediaFormat.GetInteger(MediaFormat.KeyHeight)));
            }
            if (mediaFormat.ContainsKey(MediaFormat.KeyBitRate))
            {
                stringBuilder.AppendLine(context.GetString(Resource.String.stats_bitrate, mediaFormat.GetInteger(MediaFormat.KeyBitRate)));
            }
            if (mediaFormat.ContainsKey(MediaFormat.KeyDuration))
            {
                stringBuilder.AppendLine(context.GetString(Resource.String.stats_duration, mediaFormat.GetLong(MediaFormat.KeyDuration)));
            }
            if (mediaFormat.ContainsKey(MediaFormat.KeyFrameRate))
            {
                stringBuilder.AppendLine(context.GetString(Resource.String.stats_frame_rate, MediaFormatUtils.GetFrameRate(mediaFormat, new Java.Lang.Integer(0)).IntValue()));
            }
            if (mediaFormat.ContainsKey(MediaFormat.KeyIFrameInterval))
            {
                stringBuilder.AppendLine(context.GetString(Resource.String.stats_key_frame_interval, MediaFormatUtils.GetIFrameInterval(mediaFormat, new Java.Lang.Integer(0)).IntValue()));
            }
            if (mediaFormat.ContainsKey(KEY_ROTATION))
            {
                stringBuilder.AppendLine(context.GetString(Resource.String.stats_rotation, mediaFormat.GetInteger(KEY_ROTATION)));
            }
            return(stringBuilder.ToString());
        }
コード例 #21
0
 public Task <bool> TrimAsync(int startMS, int lengthMS, string inputPath, string outputPath)
 {
     return(Task.Run <bool>(() =>
     {
         try
         {
             bool didOperationSucceed = false;
             MediaExtractor extractor = new MediaExtractor();
             extractor.SetDataSource(inputPath);
             int trackCount = extractor.TrackCount;
             // Set up MediaMuxer for the destination.
             MediaMuxer muxer;
             muxer = new MediaMuxer(outputPath, MuxerOutputType.Mpeg4);
             // Set up the tracks and retrieve the max buffer size for selected
             // tracks.
             Dictionary <int, int> indexDict = new Dictionary <int, int>(trackCount);
             int bufferSize = -1;
             for (int i = 0; i < trackCount; i++)
             {
                 MediaFormat format = extractor.GetTrackFormat(i);
                 string mime = format.GetString(MediaFormat.KeyMime);
                 bool selectCurrentTrack = false;
                 if (mime.StartsWith("audio/"))
                 {
                     selectCurrentTrack = true;
                 }
                 else if (mime.StartsWith("video/"))
                 {
                     selectCurrentTrack = true;
                 }
                 if (selectCurrentTrack)
                 {
                     extractor.SelectTrack(i);
                     int dstIndex = muxer.AddTrack(format);
                     indexDict.Add(i, dstIndex);
                     if (format.ContainsKey(MediaFormat.KeyMaxInputSize))
                     {
                         int newSize = format.GetInteger(MediaFormat.KeyMaxInputSize);
                         bufferSize = newSize > bufferSize ? newSize : bufferSize;
                     }
                 }
             }
             if (bufferSize < 0)
             {
                 bufferSize = 1337; //TODO: I don't know what to put here tbh, it will most likely be above 0 at this point anyways :)
             }
             // Set up the orientation and starting time for extractor.
             MediaMetadataRetriever retrieverSrc = new MediaMetadataRetriever();
             retrieverSrc.SetDataSource(inputPath);
             string degreesString = retrieverSrc.ExtractMetadata(MetadataKey.VideoRotation);
             if (degreesString != null)
             {
                 int degrees = int.Parse(degreesString);
                 if (degrees >= 0)
                 {
                     muxer.SetOrientationHint(degrees);
                 }
             }
             if (startMS > 0)
             {
                 extractor.SeekTo(startMS * 1000, MediaExtractorSeekTo.ClosestSync);
             }
             // Copy the samples from MediaExtractor to MediaMuxer. We will loop
             // for copying each sample and stop when we get to the end of the source
             // file or exceed the end time of the trimming.
             int offset = 0;
             int trackIndex = -1;
             ByteBuffer dstBuf = ByteBuffer.Allocate(bufferSize);
             MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
             try
             {
                 muxer.Start();
                 while (true)
                 {
                     bufferInfo.Offset = offset;
                     bufferInfo.Size = extractor.ReadSampleData(dstBuf, offset);
                     if (bufferInfo.Size < 0)
                     {
                         bufferInfo.Size = 0;
                         break;
                     }
                     else
                     {
                         bufferInfo.PresentationTimeUs = extractor.SampleTime;
                         if (lengthMS > 0 && bufferInfo.PresentationTimeUs > ((startMS + lengthMS - 1) * 1000))
                         {
                             Console.WriteLine("The current sample is over the trim end time.");
                             break;
                         }
                         else
                         {
                             bufferInfo.Flags = ConvertMediaExtractorSampleFlagsToMediaCodecBufferFlags(extractor.SampleFlags);
                             trackIndex = extractor.SampleTrackIndex;
                             muxer.WriteSampleData(indexDict[trackIndex], dstBuf, bufferInfo);
                             extractor.Advance();
                         }
                     }
                 }
                 muxer.Stop();
                 didOperationSucceed = true;
                 //deleting the old file
                 //JFile file = new JFile(srcPath);
                 //file.Delete();
             }
             catch (IllegalStateException e)
             {
                 // Swallow the exception due to malformed source.
                 Console.WriteLine("The source video file is malformed");
             }
             finally
             {
                 muxer.Release();
             }
             return didOperationSucceed;
         }
         catch (System.Exception xx)
         {
             return false;
         }
     }));
     // Set up MediaExtractor to read from the source.
 }
コード例 #22
0
        public static Result DecodeAudio(FileDescriptor descriptor, long offset, long length)
        {
            using (var extractor = new MediaExtractor())
            {
                extractor.SetDataSource(descriptor, offset, length);

                MediaFormat format = null;
                string      mime   = null;
                for (int i = 0; i < extractor.TrackCount; i++)
                {
                    format = extractor.GetTrackFormat(i);
                    mime   = format.GetString(MediaFormat.KeyMime);

                    if (!mime.StartsWith("audio/"))
                    {
                        continue;
                    }
                    extractor.SelectTrack(i);
                }

                if (format == null || !mime.StartsWith("audio/"))
                {
                    throw new ContentLoadException("Could not find any audio track.");
                }

                int  sampleRate   = format.GetInteger(MediaFormat.KeySampleRate);
                long duration     = format.GetLong(MediaFormat.KeyDuration);
                int  channels     = format.GetInteger(MediaFormat.KeyChannelCount);
                int  samples      = (int)(sampleRate * duration / 1000000d);
                var  output       = new byte[samples * 2];
                int  timeoutsLeft = 1000;

                var decoder = MediaCodecPool.RentDecoder(mime);
                try
                {
                    decoder.Configure(format, null, null, MediaCodecConfigFlags.None);
                    decoder.Start();

                    ByteBuffer[] inputBuffers  = decoder.GetInputBuffers();
                    ByteBuffer[] outputBuffers = decoder.GetOutputBuffers();

                    var  bufferInfo  = new MediaCodec.BufferInfo();
                    int  totalOffset = 0;
                    bool endOfStream = false;
                    while (true)
                    {
                        // we dont need to have a endOfStream local,
                        // but it saves us a few calls to the decoder
                        if (!endOfStream)
                        {
                            int inputBufIndex = decoder.DequeueInputBuffer(5000);
                            if (inputBufIndex >= 0)
                            {
                                int size = extractor.ReadSampleData(inputBuffers[inputBufIndex], 0);
                                if (size > 0)
                                {
                                    decoder.QueueInputBuffer(
                                        inputBufIndex, 0, size, extractor.SampleTime, MediaCodecBufferFlags.None);
                                }

                                if (!extractor.Advance())
                                {
                                    endOfStream = true;
                                    decoder.QueueInputBuffer(
                                        inputBufIndex, 0, 0, 0, MediaCodecBufferFlags.EndOfStream);
                                }
                            }
                        }

                        int decoderStatus = decoder.DequeueOutputBuffer(bufferInfo, 5000);
                        if (decoderStatus >= 0)
                        {
                            IntPtr bufferPtr = outputBuffers[decoderStatus].GetDirectBufferAddress();
                            IntPtr offsetPtr = bufferPtr + bufferInfo.Offset;
                            int    size      = bufferInfo.Size;
                            Marshal.Copy(offsetPtr, output, totalOffset, size);

                            decoder.ReleaseOutputBuffer(decoderStatus, render: false);
                            totalOffset += size;

                            if (bufferInfo.Flags == MediaCodecBufferFlags.EndOfStream)
                            {
                                if (totalOffset != output.Length)
                                {
                                    throw new ContentLoadException(
                                              "Reached end of stream before reading expected amount of samples.");
                                }
                                break;
                            }
                        }
                        else if (decoderStatus == (int)MediaCodecInfoState.OutputBuffersChanged)
                        {
                            outputBuffers = decoder.GetOutputBuffers();
                        }
                        else if (decoderStatus == (int)MediaCodecInfoState.TryAgainLater)
                        {
                            if (timeoutsLeft-- <= 0)
                            {
                                break;
                            }
                        }
                    }
                }
                finally
                {
                    decoder.Stop();
                    MediaCodecPool.ReturnDecoder(mime, decoder);
                }

                if (timeoutsLeft <= 0)
                {
                    throw new ContentLoadException("Could not load sound effect in designated time frame.");
                }
                return(new Result(output, sampleRate, channels, mime));
            }
        }
コード例 #23
0
        /// <summary>
        /// if both inputPath string and inputUri are not null, this
        /// method will use the Uri.  Else, set one or the other
        ///
        /// They cannot both be null
        /// </summary>
        /// <param name="startMs">the start ms for trimming</param>
        /// <param name="endMs">the final ms for trimming</param>
        /// <param name="inputPath">optional input path string</param>
        /// <param name="muxer">the muxer to use for writing bytes</param>
        /// <param name="trackIndexOverride">the track index for muxer read/write to</param>
        /// <param name="bufferInfo">an input bufferinfo to get properties from</param>
        /// <param name="outputPath">the output path for method to check after finished encoding</param>
        /// <param name="ptOffset">the presentation time offset for audio, used in syncing audio and video</param>
        /// <param name="inputUri">optional inputUri to read from</param>
        /// <returns></returns>
        public async Task <string> HybridMuxingTrimmer(int startMs, int endMs, string inputPath, MediaMuxer muxer, int trackIndexOverride = -1, BufferInfo bufferInfo = null, string outputPath = null, long ptOffset = 0, Android.Net.Uri inputUri = null)
        {
            var tio = trackIndexOverride;
            await Task.Run(() =>
            {
                if (outputPath == null)
                {
                    outputPath = FileToMp4.LatestOutputPath;
                }
                MediaExtractor ext = new MediaExtractor();
                if (inputUri != null)
                {
                    ext.SetDataSource(Android.App.Application.Context, inputUri, null);
                }
                else
                {
                    ext.SetDataSource(inputPath);
                }
                int trackCount = ext.TrackCount;
                Dictionary <int, int> indexDict = new Dictionary <int, int>(trackCount);
                int bufferSize = -1;
                for (int i = 0; i < trackCount; i++)
                {
                    MediaFormat format      = ext.GetTrackFormat(i);
                    string mime             = format.GetString(MediaFormat.KeyMime);
                    bool selectCurrentTrack = false;
                    if (mime.StartsWith("audio/"))
                    {
                        selectCurrentTrack = true;
                    }
                    else if (mime.StartsWith("video/"))
                    {
                        selectCurrentTrack = false;
                    }                                                                   /*rerouted to gl video encoder*/
                    if (selectCurrentTrack)
                    {
                        ext.SelectTrack(i);
                        if (tio != -1)
                        {
                            indexDict.Add(i, i);
                        }
                        if (format.ContainsKey(MediaFormat.KeyMaxInputSize))
                        {
                            int newSize = format.GetInteger(MediaFormat.KeyMaxInputSize);
                            bufferSize  = newSize > bufferSize ? newSize : bufferSize;
                        }
                    }
                }
                MediaMetadataRetriever retrieverSrc = new MediaMetadataRetriever();
                if (!System.String.IsNullOrWhiteSpace(inputPath))
                {
                    retrieverSrc.SetDataSource(inputPath);
                }
                else
                {
                    retrieverSrc.SetDataSource(Android.App.Application.Context, inputUri);
                }
                string degreesString = retrieverSrc.ExtractMetadata(MetadataKey.VideoRotation);
                if (degreesString != null) // unused ATM but will be useful for stabilized videoview in streaming
                {
                    int degrees = int.Parse(degreesString);
                    if (degrees >= 0) /* muxer.SetOrientationHint(degrees); */ } {
                    //muxer won't accept this param once started
            }
                           if (startMs > 0)
                {
                    ext.SeekTo(startMs * 1000, MediaExtractorSeekTo.ClosestSync);
                }
                           int offset = 0;
                           if (bufferInfo == null)
                {
                    bufferInfo = new MediaCodec.BufferInfo();
                }
                           ByteBuffer dstBuf = ByteBuffer.Allocate(bufferSize);
                           long us           = endMs * 1000;
                           long uo           = us + ptOffset;
                           int cf            = 0;
                           try
                {
                    FileToMp4.AudioEncodingInProgress = true;
                    while (true)
                    {
                        bufferInfo.Offset = offset;
                        bufferInfo.Size   = ext.ReadSampleData(dstBuf, offset);
                        if (bufferInfo.Size < 0)
                        {
                            bufferInfo.Size = 0; break;
                        }
                        else
                        {
                            cf++;
                            bufferInfo.PresentationTimeUs = ext.SampleTime + ptOffset;
                            if (ext.SampleTime >= us)
                            {
                                break;
                            }                                    //out of while
                            else
                            {
                                bufferInfo.Flags = MFlags2MCodecBuff(ext.SampleFlags);
                                if (tio == -1)
                                {
                                    muxer.WriteSampleData(FileToMp4.LatestAudioTrackIndex, dstBuf, bufferInfo);
                                }
                                else
                                {
                                    muxer.WriteSampleData(tio, dstBuf, bufferInfo);
                                }
                                if (cf >= 240) //only send the muxer eventargs once every x frames to reduce CPU load
                                {
                                    Notify(ext.SampleTime, us);
                                    cf = 0;
                                }
                            }
                            ext.Advance();
                        }
                    }
                }
                           catch (Java.Lang.IllegalStateException e)
                {
                    this.Progress.Invoke(new MuxerEventArgs(ext.SampleTime, us, null, true, true));
                    Console.WriteLine("The source video file is malformed");
                }
                           catch (Java.Lang.Exception ex)
                {
                    this.Progress.Invoke(new MuxerEventArgs(ext.SampleTime, us, null, true, true));
                    Console.WriteLine(ex.Message);
                }
                           if (AppSettings.Logging.SendToConsole)
                {
                    System.Console.WriteLine($"DrainEncoder audio finished @ {bufferInfo.PresentationTimeUs}");
                }
});

            FileToMp4.AudioEncodingInProgress = false;
            try
            {
                if (!FileToMp4.VideoEncodingInProgress)
                {
                    muxer.Stop();
                    muxer.Release();
                    muxer = null;
                }
            }
            catch (Java.Lang.Exception ex) { Log.Debug("MuxingEncoder", ex.Message); }
            if (outputPath != null)
            {
                var success = System.IO.File.Exists(outputPath);
                if (success)
                {
                    this.Progress.Invoke(new MuxerEventArgs(endMs * 1000, endMs, outputPath, true));
                    return(outputPath);
                }
            }

            return(null); //nothing to look for
        }