private void initHwDecoder(string codec) { MediaFormat format = new MediaFormat(); string mime_type = null; switch (codec) { case "amrnb": mime_type = MediaFormat.MimetypeAudioAmrNb; format.SetInteger(MediaFormat.KeySampleRate, 8000); format.SetInteger(MediaFormat.KeyBitRate, 7950); break; case "amrwb": mime_type = MediaFormat.MimetypeAudioAmrWb; format.SetInteger(MediaFormat.KeySampleRate, 16000); format.SetInteger(MediaFormat.KeyBitRate, 18250); break; } if (mime_type != null) { format.SetString(MediaFormat.KeyMime, mime_type); format.SetInteger(MediaFormat.KeyChannelCount, 1); format.SetInteger(MediaFormat.KeyMaxInputSize, bufferSize); format.SetInteger(MediaFormat.KeyLatency, 1); format.SetInteger(MediaFormat.KeyPriority, 0); audioDecoder = new HwDecoder(mime_type, format, this); audioDecoder.start(); } }
private void initEncoder(string codec) { MediaFormat format = new MediaFormat(); switch (codec) { case "amrnb": audioEncoder = MediaCodec.CreateEncoderByType(MediaFormat.MimetypeAudioAmrNb); format.SetString(MediaFormat.KeyMime, MediaFormat.MimetypeAudioAmrNb); format.SetInteger(MediaFormat.KeySampleRate, 8000); format.SetInteger(MediaFormat.KeyBitRate, 7950); break; case "amrwb": audioEncoder = MediaCodec.CreateEncoderByType(MediaFormat.MimetypeAudioAmrWb); format.SetString(MediaFormat.KeyMime, MediaFormat.MimetypeAudioAmrWb); format.SetInteger(MediaFormat.KeySampleRate, 16000); format.SetInteger(MediaFormat.KeyBitRate, 18250); break; default: throw new Exception("Unknown recorder codec selected " + codec); } format.SetInteger(MediaFormat.KeyChannelCount, 1); format.SetInteger(MediaFormat.KeyMaxInputSize, bufferSize); audioEncoder.SetCallback(this); audioEncoder.Configure(format, null, null, MediaCodecConfigFlags.Encode); audioEncoder.Start(); }
public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append($"a={MediaAttributeFieldName}:{MediaFormat.ToString()} {MIMEType}/{SampleRate}").AppendLine(); return(sb.ToString()); }
private static void StartCallbackDelegate(IntPtr w, ulong frameInterval, MediaFormat mediaFormat, ulong userData) { if (_mIConstruct != null) { _mIConstruct.StartCallback(frameInterval, mediaFormat, userData); } }
public async Task <IActionResult> Edit(string id, [Bind("Id,Format")] MediaFormat mediaFormat) { if (id != mediaFormat.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(mediaFormat); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!MediaFormatExists(mediaFormat.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(mediaFormat)); }
/** * Checks the video file to see if the contents match our expectations. We decode the * video to a Surface and check the pixels with GL. */ private void checkVideoFile(VideoChunks inputData) { OutputSurface surface = null; MediaCodec decoder = null; mLargestColorDelta = -1; if (AppSettings.Logging.SendToConsole) { Log.Debug(TAG, "checkVideoFile"); } try { surface = new OutputSurface(mWidth, mHeight); MediaFormat format = inputData.getMediaFormat(); decoder = MediaCodec.CreateDecoderByType(MIME_TYPE); decoder.Configure(format, surface.Surface, null, 0); decoder.Start(); int badFrames = checkVideoData(inputData, decoder, surface); if (badFrames != 0) { fail("Found " + badFrames + " bad frames"); } } finally { if (surface != null) { surface.Release(); } if (decoder != null) { decoder.Stop(); decoder.Release(); } Log.Info(TAG, "Largest color delta: " + mLargestColorDelta); } }
public void SetupVideo(int width, int height, byte[] spsData, byte[] ppsData) { MediaFormat videoFormat = MediaFormat.CreateVideoFormat( mime: MediaFormat.MimetypeVideoAvc, width: width, height: height); /* * TODO: Use SPS / PPS * videoFormat.SetByteBuffer("csd-0", Java.Nio.ByteBuffer.Wrap(spsData)); * videoFormat.SetByteBuffer("csd-1", Java.Nio.ByteBuffer.Wrap(ppsData)); */ videoFormat.SetInteger(MediaFormat.KeyMaxInputSize, 100000); _videoCodec = MediaCodec.CreateDecoderByType( MediaFormat.MimetypeVideoAvc); _videoCodec.SetCallback(this); _videoCodec.Configure(format: videoFormat, surface: new Surface(_surface), crypto: null, flags: MediaCodecConfigFlags.None); _videoCodec.Start(); }
/// <summary> /// Initialize this instance. /// First, stop decoder and check if surface exists. /// Then configure MediaFormat and MediaCodec and start it. /// </summary> /// <returns>The initialize.</returns> public bool Initialize() { Initialized = false; if (!StopDecoder() || _surface == null) { return(Initialized); } _mediaFormat = GetMediaFormat(_mimeType, _videoWidth, _videoHeight); _mediaFormat.SetInteger(MediaFormat.KeyMaxWidth, _videoWidth); _mediaFormat.SetInteger(MediaFormat.KeyMaxHeight, _videoHeight); if (Build.VERSION.SdkInt >= BuildVersionCodes.M) { _mediaFormat.SetInteger(MediaFormat.KeyOperatingRate, Short.MaxValue); } _mediaCodec.Configure( format: _mediaFormat, surface: _surface, crypto: null, flags: MediaCodecConfigFlags.None); _mediaCodec.SetVideoScalingMode(VideoScalingMode.ScaleToFit); _mediaCodec.SetCallback(this); _mediaCodec.Start(); Initialized = true; return(Initialized); }
public static int GetMediaFormatPropertyInteger(Uri uri, string key, int defaultValue) { int value = defaultValue; MediaExtractor extractor = new MediaExtractor(); try { extractor.SetDataSource(uri.ToString()); } catch (System.Exception e) { return(value); } MediaFormat format = GetTrackFormat(extractor, MIME_TYPE_AVC); extractor.Release(); if (format.ContainsKey(key)) { value = format.GetInteger(key); } return(value); }
private static string BuildTrackName(MediaFormat format) { if (format.Adaptive) { return("auto"); } string trackName; if (MimeTypes.IsVideo(format.MimeType)) { trackName = JoinWithSeparator(JoinWithSeparator(BuildResolutionString(format), BuildBitrateString(format)), BuildTrackIdString(format)); } else if (MimeTypes.IsAudio(format.MimeType)) { trackName = JoinWithSeparator(JoinWithSeparator(JoinWithSeparator(BuildLanguageString(format), BuildAudioPropertyString(format)), BuildBitrateString(format)), BuildTrackIdString(format)); } else { trackName = JoinWithSeparator(JoinWithSeparator(BuildLanguageString(format), BuildBitrateString(format)), BuildTrackIdString(format)); } return(trackName.Length == 0 ? "unknown" : trackName); }
public async Task User_can_download_a_video_with_subtitles_into_a_single_webm_file() { // Arrange var youtube = new YoutubeClient(); var outputFilePath = _tempOutputFixture.GetTempFilePath(); var streamManifest = await youtube.Videos.Streams.GetManifestAsync("YltHGKX80Y8"); var trackManifest = await youtube.Videos.ClosedCaptions.GetManifestAsync("YltHGKX80Y8"); var streamInfos = new[] { streamManifest.GetVideoStreams().OrderBy(s => s.Size).First(s => s.Container == Container.WebM) }; var trackInfos = trackManifest.Tracks; // Act await youtube.Videos.DownloadAsync( streamInfos, trackInfos, new ConversionRequestBuilder(outputFilePath) .SetFFmpegPath(_ffmpegFixture.FilePath) .SetContainer("webm") .Build() ); // Assert MediaFormat.IsWebMFile(outputFilePath).Should().BeTrue(); foreach (var trackInfo in trackInfos) { FileEx.ContainsBytes(outputFilePath, Encoding.ASCII.GetBytes(trackInfo.Language.Name)).Should().BeTrue(); } }
public bool AddNewBook(IBook book) { using (SqlConnection connection = DBManager.GetSqlConnection()) { connection.Open(); // Add a new row to the Inventory_Books table // Update the number of copies in Inventory_Master using (SqlCommand command = new SqlCommand("AddNewBook", connection)) { command.CommandType = System.Data.CommandType.StoredProcedure; command.Parameters.AddWithValue("@libraryID", book.LibraryID); command.Parameters.AddWithValue("@title", book.Title); command.Parameters.AddWithValue("@author", book.Author); command.Parameters.AddWithValue("@format", MediaFormat.GetMediaKey(book.Format)); command.Parameters.AddWithValue("@isbn10", book.ISBN10); command.Parameters.AddWithValue("@isbn13", book.ISBN13); command.Parameters.AddWithValue("@length", book.Length); command.Parameters.AddWithValue("@genre", book.Genre); command.Parameters.AddWithValue("@publisher", book.Publisher); command.Parameters.AddWithValue("@publicationYear", book.PublicationYear); command.Parameters.AddWithValue("@description", book.Description); if (book.ImageBytes == null) { command.Parameters.AddWithValue("@image", DBNull.Value); } else { command.Parameters.AddWithValue("@image", book.ImageBytes); } command.ExecuteNonQuery(); } } return(true); }
/** * 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); }
public int Read(byte[] buffer, int offset, int length) { int min = 0; try { if (mBuffer == null) { while (!Thread.Interrupted() && !mClosed) { mIndex = mMediaCodec.DequeueOutputBuffer(mBufferInfo, 500000); if (mIndex >= 0) { //Log.d(TAG,"Index: "+mIndex+" Time: "+mBufferInfo.presentationTimeUs+" size: "+mBufferInfo.size); mBuffer = mBuffers[mIndex]; mBuffer.Position(0); break; } else if (mIndex == (int)MediaCodec.InfoOutputBuffersChanged) { mBuffers = mMediaCodec.GetOutputBuffers(); } else if (mIndex == (int)MediaCodec.InfoOutputFormatChanged) { mMediaFormat = mMediaCodec.GetOutputFormat(mIndex); Log.i(TAG, mMediaFormat.ToString()); } else if (mIndex == (int)MediaCodec.InfoTryAgainLater) { Log.v(TAG, "No buffer available..."); //return 0; } else { Log.e(TAG, "Message: " + mIndex); //return 0; } } } if (mClosed) { throw new IOException("This InputStream was closed"); } min = length < mBufferInfo.Size - mBuffer.Position() ? length : mBufferInfo.Size - mBuffer.Position(); mBuffer.Get(buffer, offset, min); if (mBuffer.Position() >= mBufferInfo.Size) { mMediaCodec.ReleaseOutputBuffer(mIndex, false); mBuffer = null; } } catch (RuntimeException e) { e.PrintStackTrace(); } return(min); }
public TrackFull ReadTrack(int id, string path) { using (File file = File.Create(new File.LocalFileAbstraction(path))) { MediaFormat mf = IdentifyFormat(file); if (mf == MediaFormat.Unknown) { return(null); } Tag tag = file.Tag; return(new TrackFull { Id = id, TrackNumber = tag.Track, FileName = Path.GetFileName(path), Title = tag.Title, Artist = tag.FirstPerformer, Year = tag.Year, Album = tag.Album, AlbumArtist = tag.FirstAlbumArtist, Genre = tag.FirstGenre, Length = (long)Math.Round(file.Properties.Duration.TotalSeconds), MediaFormat = mf, Bitrate = file.Properties.AudioBitrate }); } }
/// <summary> /// Configures the MediaCodec. /// </summary> /// <param name="format">The <see cref="MediaFormat"/> for properties of media data to decode or encode.</param> /// <param name="encoder">The value indicating whether the codec works as an encoder or a decoder.</param> /// <param name="codecType">The value indicating whether the codec uses hardware acceleration.</param> /// <exception cref="ArgumentNullException"><paramref name="format"/> is null.</exception> /// <exception cref="ArgumentException"> /// <paramref name="codecType"/> is invalid.<br/> /// -or-<br/> /// <paramref name="format"/> is neither audio type nor video type. /// </exception> /// <exception cref="NotSupportedException">The mime type of the format is not supported.</exception> /// <see cref="SupportedAudioCodecs"/> /// <see cref="SupportedVideoCodecs"/> /// <since_tizen> 3 </since_tizen> public void Configure(MediaFormat format, bool encoder, MediaCodecTypes codecType) { ValidateNotDisposed(); if (format == null) { throw new ArgumentNullException(nameof(format)); } if (codecType != MediaCodecTypes.Hardware && codecType != MediaCodecTypes.Software) { throw new ArgumentException("codecType is invalid."); } if (format.Type == MediaFormatType.Audio) { ConfigureAudio((AudioMediaFormat)format, encoder, codecType); } else if (format.Type == MediaFormatType.Video) { ConfigureVideo((VideoMediaFormat)format, encoder, codecType); } else { throw new ArgumentException("Only video and audio formats are allowed."); } }
internal static async Task <IResponse> PutResponseAsync(this HttpClient client, string path, MediaFormat mediaFormat) { try { using (var request = Helpers.HttpRequestHelper.CreateRequest(HttpMethod.Put, path)) { using (var response = await client.ExecuteRequestAsync(request, CancellationToken.None)) { return(await response.PrepareResponseAsync()); } } } catch (Exception ex) { if (ex is OperationCanceledException) { return(ResponseFactory.Exception(ex)); } return(ResponseFactory.Exception(ex, new List <string> { StaticResources.ExecutionFailureMessage, ex.Message })); } }
//@Override //@SuppressLint({ "InlinedApi", "NewApi" }) protected override void encodeWithMediaCodec() { int bufferSize = AudioRecord.GetMinBufferSize(mQuality.samplingRate, ChannelIn.Mono, Encoding.Pcm16bit) * 2; ((AACLATMPacketizer)mPacketizer).setSamplingRate(mQuality.samplingRate); mAudioRecord = new AudioRecord(Android.Media.AudioSource.Mic, mQuality.samplingRate, Android.Media.ChannelIn.Mono, Android.Media.Encoding.Pcm16bit, bufferSize); mMediaCodec = MediaCodec.CreateEncoderByType("audio/mp4a-latm"); MediaFormat format = new MediaFormat(); format.SetString(MediaFormat.KeyMime, "audio/mp4a-latm"); format.SetInteger(MediaFormat.KeyBitRate, mQuality.bitRate); format.SetInteger(MediaFormat.KeyChannelCount, 1); format.SetInteger(MediaFormat.KeySampleRate, mQuality.samplingRate); format.SetInteger(MediaFormat.KeyAacProfile, (int)MediaCodecInfo.CodecProfileLevel.AACObjectLC); format.SetInteger(MediaFormat.KeyMaxInputSize, bufferSize); mMediaCodec.Configure(format, null, null, MediaCodecConfigFlags.Encode); mAudioRecord.StartRecording(); mMediaCodec.Start(); MediaCodecInputStream inputStream = new MediaCodecInputStream(mMediaCodec); Java.Nio.ByteBuffer[] inputBuffers = mMediaCodec.GetInputBuffers(); mThread = new Thread(this); mThread.Start(); // The packetizer encapsulates this stream in an RTP stream and send it over the network mPacketizer.setInputStream(inputStream); mPacketizer.start(); mStreaming = true; }
protected override void ExtractMediaMetadata(MediaFormat format) { var audioChannels = format.GetInteger(MediaFormat.KeyChannelCount); var audioSampleRate = format.GetInteger(MediaFormat.KeySampleRate); MediaMetadata = new MediaCodecAudioMetadata(audioChannels, audioSampleRate, MediaDuration); }
public Movie(string title, int ageLimit, MediaFormat format, DateTime year) { this.Title = title; this.AgeLimit = ageLimit; this.ProductMediaFormat = format; this.Year = year; }
protected override void OnDraw(Canvas canvas) { if (rtspCancel == null) { rtspClientStart(); } if (codec == null && (h264 || h265)) { codec = MediaCodec.CreateDecoderByType(h265 ? MediaFormat.MimetypeVideoHevc : MediaFormat.MimetypeVideoAvc); callbacks = new CallBacks(this); codec.SetCallback(callbacks); var mediafmt = MediaFormat.CreateVideoFormat(h265 ? MediaFormat.MimetypeVideoHevc : MediaFormat.MimetypeVideoAvc, 1920, 1080); codec.Configure(mediafmt, videoView.Holder.Surface, null, MediaCodecConfigFlags.None); codec.Start(); } base.OnDraw(canvas); }
public bool setup(DecoderCallback callback_obj, int width, int height) //format_hint is aviFileContent { callbackThread = new HandlerThread("H264DecoderHandler"); callbackThread.Start(); handler = new Handler(callbackThread.Looper); mDecoder = MediaCodec.CreateDecoderByType(MIME); mCallbackObj = callback_obj; myCallback = new MyCallback(mDecoder, mCallbackObj); mDecoder.SetCallback(myCallback, handler); //mOutputFormat = mDecoder.GetOutputFormat(); // option B inputFormat = MediaFormat.CreateVideoFormat(MIME, width, height); inputFormat.SetInteger(MediaFormat.KeyMaxInputSize, width * height); inputFormat.SetInteger("durationUs", 63446722); //inputFormat.SetInteger(MediaFormat.KeyColorFormat, (int)MediaCodecCapabilities.Formatyuv420semiplanar); //inputFormat.SetInteger(MediaFormat.KeyIFrameInterval, 60); try { mDecoder.Configure(inputFormat, null, null, 0 /* Decoder */); } catch (Exception ex) { throw ex; } Console.WriteLine("before mDecoder.Start()"); mDecoder.Start(); Console.WriteLine("after mDecoder.Start()"); return(true); }
/** * Edits a video file, saving the contents to a new file. This involves decoding and * re-encoding, not to mention conversions between YUV and RGB, and so may be lossy. * <p> * If we recognize the decoded format we can do this in Java code using the ByteBuffer[] * output, but it's not practical to support all OEM formats. By using a SurfaceTexture * for output and a Surface for input, we can avoid issues with obscure formats and can * use a fragment shader to do transformations. */ private VideoChunks editVideoFile(VideoChunks inputData) { if (AppSettings.Logging.SendToConsole) { Log.Debug(TAG, "editVideoFile " + mWidth + "x" + mHeight); } VideoChunks outputData = new VideoChunks(); MediaCodec decoder = null; MediaCodec encoder = null; InputSurface inputSurface = null; OutputSurface outputSurface = null; try { MediaFormat inputFormat = inputData.getMediaFormat(); // Create an encoder format that matches the input format. (Might be able to just // re-use the format used to generate the video, since we want it to be the same.) MediaFormat outputFormat = MediaFormat.CreateVideoFormat(MIME_TYPE, mWidth, mHeight); outputFormat.SetInteger(MediaFormat.KeyColorFormat, (int)MediaCodecInfo.CodecCapabilities.COLORFormatSurface); outputFormat.SetInteger(MediaFormat.KeyBitRate, inputFormat.GetInteger(MediaFormat.KeyBitRate)); outputFormat.SetInteger(MediaFormat.KeyFrameRate, inputFormat.GetInteger(MediaFormat.KeyFrameRate)); outputFormat.SetInteger(MediaFormat.KeyIFrameInterval, inputFormat.GetInteger(MediaFormat.KeyIFrameInterval)); outputData.setMediaFormat(outputFormat); encoder = MediaCodec.CreateEncoderByType(MIME_TYPE); encoder.Configure(outputFormat, null, null, MediaCodecConfigFlags.Encode); inputSurface = new InputSurface(encoder.CreateInputSurface()); inputSurface.MakeCurrent(); encoder.Start(); // OutputSurface uses the EGL context created by InputSurface. decoder = MediaCodec.CreateDecoderByType(MIME_TYPE); outputSurface = new OutputSurface(); outputSurface.ChangeFragmentShader(FRAGMENT_SHADER); decoder.Configure(inputFormat, outputSurface.Surface, null, 0); decoder.Start(); editVideoData(inputData, decoder, outputSurface, inputSurface, encoder, outputData); } finally { if (AppSettings.Logging.SendToConsole) { Log.Debug(TAG, "shutting down encoder, decoder"); } if (outputSurface != null) { outputSurface.Release(); } if (inputSurface != null) { inputSurface.Release(); } if (encoder != null) { encoder.Stop(); encoder.Release(); } if (decoder != null) { decoder.Stop(); decoder.Release(); } } return(outputData); }
public void LoadContent <T>(string assetName, string assetPath) where T : class { if (this.IsInitialized) { MediaFormat assetFormat = (MediaFormat)Enum.Parse(typeof(MediaFormat), typeof(T).Name); if (this.media.ContainsKey(assetFormat)) { try { this.media[assetFormat].Add(new MediaElement(assetName, assetPath, this.Content.Load <T>(assetPath))); } catch (ArgumentException) { // Don't throw if the assets are the same if (string.Compare(this.media[assetFormat][assetName].Location, assetPath, StringComparison.CurrentCultureIgnoreCase) != 0) { throw; } } catch (ContentLoadException) { this.media[assetFormat].Add(new MediaElement(assetName, assetPath, this.media[MediaFormat.Texture2D]["ContentLoadError"].Asset)); } } else { throw new ContentLoadException("Error, content of type: " + typeof(T).Name + " is not supported!"); } } }
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()); }
public void UnloadContent(string assetName, MediaFormat assetFormat) { if (this.media.ContainsKey(assetFormat)) { this.media[assetFormat].Remove(this.media[assetFormat][assetName]); } }
public bool Initialize() { _initialized = false; if (!StopDecoder()) { return(_initialized); } _mediaFormat = GetMediaFormat(_mimeType, _sampleRate, _channels); _mediaCodec = MediaCodec.CreateDecoderByType(_mimeType); _mediaCodec.Configure( format: _mediaFormat, surface: null, crypto: null, flags: MediaCodecConfigFlags.None); _audioTrack = GetAudioTrack(); _audioTrack.Play(); _mediaCodec.Start(); _encoderThread = GetEncoderThread(); _encoderThread.Start(); _decoderThread = GetDecoderThread(); _decoderThread.Start(); _initialized = true; return(_initialized); }
private long getLong(MediaFormat mediaFormat, string key) { if (mediaFormat.ContainsKey(key)) { return mediaFormat.GetLong(key); } return -1; }
/** * The code profile, Sample rate, channel Count is used to * produce the AAC Codec SpecificData. * Android 4.4.2/frameworks/av/media/libstagefright/avc_utils.cpp refer * to the portion of the code written. * * MPEG-4 Audio refer : http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config * * @param audioProfile is MPEG-4 Audio Object Types * @param sampleRate * @param channelConfig * @return MediaFormat */ private MediaFormat makeAACCodecSpecificData(int audioProfile, int sampleRate, int channelConfig) { MediaFormat format = new MediaFormat(); format.setString(MediaFormat.KEY_MIME, "audio/mp4a-latm"); format.setInteger(MediaFormat.KEY_SAMPLE_RATE, sampleRate); format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, channelConfig); int samplingFreq[] = {
public Game(string title, int ageLimit, MediaFormat format, GameSystemEnum gameSystem, DateTime date) { this.Title = title; this.AgeLimit = ageLimit; this.ProductMediaFormat = format; this.System = gameSystem; this.Year = date; }
private int getInt(MediaFormat mediaFormat, string key, int defaultValue) { if (mediaFormat.ContainsKey(key)) { return mediaFormat.GetInteger(key); } return defaultValue; }
protected override void ExtractMediaMetadata(MediaFormat format) { var videoWidth = format.GetInteger(MediaFormat.KeyWidth); var videoHeight = format.GetInteger(MediaFormat.KeyHeight); Logger.Verbose(string.Format("Video size: ({0}x{1})", videoWidth, videoHeight)); MediaMetadata = new MediaCodecVideoMetadata(videoWidth, videoHeight, MediaDuration); }
public Guid CreateMediaItem(string name, string title, MediaType type, MediaFormat format, string alt) { MediaItem newMediaItem = new MediaItem(); newMediaItem.Name = name; newMediaItem.Title = title; newMediaItem.Type = type; newMediaItem.Format = format; newMediaItem.AlternativeText = alt; Repository.Add(newMediaItem); return newMediaItem.ID; }
private static string BuildAudioPropertyString(MediaFormat format) { return format.ChannelCount == MediaFormat.NoValue || format.SampleRate == MediaFormat.NoValue ? "" : format.ChannelCount + "ch, " + format.SampleRate + "Hz"; }
private static string BuildBitrateString(MediaFormat format) { return format.Bitrate == MediaFormat.NoValue ? "" : String.Format(Locale.Us, "%.2fMbit", format.Bitrate/1000000f); }
private static string BuildLanguageString(MediaFormat format) { return TextUtils.IsEmpty(format.Language) || "und".Equals(format.Language) ? "" : format.Language; }
private static string BuildResolutionString(MediaFormat format) { return format.Width == MediaFormat.NoValue || format.Height == MediaFormat.NoValue ? "" : format.Width + "x" + format.Height; }
private bool LoadInfo() { if (stream == null) return false; format = MediaFormat.Unknown; width = -1; height = -1; stream.Position = 0; try { int b1 = stream.ReadByte() & 0xff; int b2 = stream.ReadByte() & 0xff; if ((b1 == 0x43 || b1 == 0x46) && b2 == 0x57) return CheckSwf(b1 == 0x43); if (b1 == 0x47 && b2 == 0x49) return CheckGif(); else if (b1 == 0x89 && b2 == 0x50) return CheckPng(); else if (b1 == 0xff && b2 == 0xd8) return CheckJpeg(); else if (b1 == 0x42 && b2 == 0x4d) return CheckBmp(); else return false; } catch (IOException) { return false; } }
private static string BuildTrackName(MediaFormat format) { if (format.Adaptive) { return "auto"; } string trackName; if (MimeTypes.IsVideo(format.MimeType)) { trackName = JoinWithSeparator(JoinWithSeparator(BuildResolutionString(format), BuildBitrateString(format)), BuildTrackIdString(format)); } else if (MimeTypes.IsAudio(format.MimeType)) { trackName = JoinWithSeparator(JoinWithSeparator(JoinWithSeparator(BuildLanguageString(format), BuildAudioPropertyString(format)), BuildBitrateString(format)), BuildTrackIdString(format)); } else { trackName = JoinWithSeparator(JoinWithSeparator(BuildLanguageString(format), BuildBitrateString(format)), BuildTrackIdString(format)); } return trackName.Length == 0 ? "unknown" : trackName; }
private bool CheckBmp() { byte[] a = new byte[44]; if (stream.Read(a, 0, 44) != 44) return false; width = getLWORD(a, 16); height = getLWORD(a, 20); if (width < 1 || height < 1) return false; format = MediaFormat.BMP; return true; }
private bool CheckGif() { byte[] GIF_MAGIC_87A = new byte[] { 0x46, 0x38, 0x37, 0x61 }; byte[] GIF_MAGIC_89A = {0x46, 0x38, 0x39, 0x61}; byte[] a = new byte[11]; // 4 from the GIF signature + 7 from the global header if (stream.Read(a, 0, 11) != 11) return false; if ((!isSame(a, 0, GIF_MAGIC_89A, 0, 4)) && (!isSame(a, 0, GIF_MAGIC_87A, 0, 4))) return false; format = MediaFormat.GIF; width = getBYTE(a, 4); height = getBYTE(a, 6); int flags = a[8] & 0xff; // skip global color palette if ((flags & 0x80) != 0) { int tableSize = (1 << ((flags & 7) + 1)) * 3; stream.Position += tableSize; } int blockType; do { blockType = stream.ReadByte(); switch(blockType) { case 0x21: // extension int extensionType = stream.ReadByte(); int n3; do { n3 = stream.ReadByte(); if (n3 > 0) stream.Position += n3; else if (n3 == -1) return false; } while (n3 > 0); break; case 0x3b: // end of file break; default: return false; } } while (blockType != 0x3b); return true; }
private bool CheckJpeg() { byte[] data = new byte[12]; while (true) { if (stream.Read(data, 0, 4) != 4) return false; int marker = getWORD(data, 0); int size = getWORD(data, 2); if ((marker & 0xff00) != 0xff00) return false; // not a valid marker if (marker >= 0xffc0 && marker <= 0xffcf && marker != 0xffc4 && marker != 0xffc8) { if (stream.Read(data, 0, 6) != 6) return false; format = MediaFormat.JPEG; width = getWORD(data, 3); height = getWORD(data, 1); return true; } else stream.Position += size - 2; } }
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(MediaFormat obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; }
private bool CheckPng() { byte[] PNG_MAGIC = new byte[] {0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a}; byte[] buff = new byte[27]; if (stream.Read(buff, 0, 27) != 27) return false; if (!isSame(buff, 0, PNG_MAGIC, 0, 6)) return false; format = MediaFormat.PNG; width = getRLWORD(buff, 14); height = getRLWORD(buff, 18); return true; }
private bool CheckSwf(bool is_comp) { this.format = MediaFormat.SWF; this.reader = new BinaryReader(this.stream); if (is_comp) { int size = -1; this.reader.BaseStream.Position = 4; // Skip head size = Convert.ToInt32(this.reader.ReadUInt32()); // Read swf head byte[] uncompressed = new byte[size]; this.reader.BaseStream.Position = 0; this.reader.Read(uncompressed, 0, 8); // Read compressed data byte[] compressed = this.reader.ReadBytes(size); this.stream.Close(); // Close the old stream // Uncompress Inflater zipInflator = new Inflater(); zipInflator.SetInput(compressed); zipInflator.Inflate(uncompressed, 8, size - 8); // Setup new uncompressed reader this.reader = new BinaryReader(new MemoryStream(uncompressed)); this.reader.BaseStream.Position = 0; } // Skip header signature/version etc etc this.reader.BaseStream.Position = 8; // Read rect uint bits = ReadUBits(5); ReadSBits(bits); // Read xmin this.width = ReadSBits(bits) / 20; // Read xmax ReadSBits(bits); // Read ymin this.height = ReadSBits(bits) / 20; // Read ymax return true; }
private static string BuildTrackIdString(MediaFormat format) { return format.TrackId == null ? "" : String.Format(Locale.Us, " (%d)", format.TrackId); }
public string Output(string output, MediaFormat outputFormat) { if(string.IsNullOrWhiteSpace(output)) throw new ArgumentNullException("output"); return string.Format("{0} {1} {2}", this.ToString(), outputFormat.Command(), output.EncloseQMarks()); }