static void Main(string[] args) { using (var db = new SchoolContext()) { var std = new Standard() { StandardName = "國小" }; std.Students.Add(new Student() { StudentName = "Will", Weight = 30, Height = 170, DateOfBirth = DateTime.Now }); std.Students.Add(new Student() { StudentName = "Will 2", Weight = 50, Height = 170, DateOfBirth = DateTime.Now }); db.Standards.Add(std); db.SaveChanges(); foreach (var item in db.Students) { Console.WriteLine(item.StudentName + "\t" + item.Standard.StandardName); } } }
private void Add() { var standard = new Standard(); standard.ClassName = ClassName; standard.SectionName = SectionName; standard.FullName = ClassName + " " + SectionName; try { SchoolContext.Standards.Add(standard); } catch (Exception ex) { MessageBox.Show(ex.Message); } try { SchoolContext.SaveChanges(); } catch (Exception ex) { MessageBox.Show(ex.Message); MessageBox.Show(ex.InnerException.Message); } }
public ActionResult MvcView() { var view = new Standard {ViewData = {Model = "red"}}; view.PushContext(new WebPageContext(), new StringWriter()); view.Execute(); var result = view.Output.ToString(); view.PopContext(); return Content(result); }
public ActionResult Create(Standard standard) { if (ModelState.IsValid) { db.Standards.Add(standard); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.Header_Id = new SelectList(db.Headers, "Id", "Header1", standard.Header_Id); return View(standard); }
public void Update(EstateType type, double area, double price) { Standard s = this.Find(type); if (s != null) { s = new Standard(); s.Area = area; s.Price = price; s.Type = type; this.standardList.Add(s); } else { s.Area = area; s.Price = price; } }
/// <summary> /// Returns the best formatted string representation of a byte value /// </summary> /// <param name="bytes">number of bytes</param> /// <param name="st"></param> /// <param name="customFormat">Defines a custom numerical format for the conversion. /// If this parameters is null or empty the default format will be used 0.00</param> /// <returns>formatted string</returns> public static string ToString(long bytes, Standard st, string customFormat) { if(bytes == 0) return "0"; if (string.IsNullOrEmpty(customFormat)) customFormat = "0.00"; string result; bool isNegative = bytes < 0; bytes = Math.Abs(bytes); if(st == Standard.Si) { if(bytes < Mb) result = BytesToKb(bytes, customFormat); else if(bytes < Gb) result = BytesToMb(bytes, customFormat); else if(bytes < Tb) result = BytesToGb(bytes, customFormat); else if(bytes < Pb) result = BytesToTb(bytes, customFormat); else result = BytesToPb(bytes, customFormat); } else { if(bytes < MiB) result = BytesToKib(bytes, customFormat); else if(bytes < GiB) result = BytesToMib(bytes, customFormat); else if(bytes < TiB) result = BytesToGib(bytes, customFormat); else if(bytes < PiB) result = BytesToTib(bytes, customFormat); else result = BytesToPib(bytes, customFormat); } return isNegative ? ("-" + result) : (result); }
void ucStandardList1_SelectedStandardItemChanged(Standard.StandardItem sItem) { if (sItem == null) { tabInfo.SelectedTabPage = tpEmpty; return; } Standard.Helper.StandardHelper.InitItemDetial(sItem); switch (sItem.Type) { case Standard.enumItemType.Standard: case Standard.enumItemType.FeatureDataset: ucFeatureDataset1.StandardItem = sItem; tabInfo.SelectedTabPage = tpFeatureDataset; return; case Standard.enumItemType.FeatureClass: ucFeatureClassInfo1.FeatrueClassInfo = sItem.Details as FeatureClassInfo; tabInfo.SelectedTabPage = tpClassInfo; return; } }
private static void UpdateOBISCodeInfo(GXStandardObisCodeCollection codes, GXDLMSObject it, Standard standard) { GXStandardObisCode[] list = codes.Find(it.LogicalName, it.ObjectType, standard); GXStandardObisCode code = list[0]; if (string.IsNullOrEmpty(it.Description)) { it.Description = code.Description; if (standard == Standard.SaudiArabia) { it.Description = it.Description.Replace("U(", "V("); } } //Update data type from DLMS standard. if (standard != Standard.DLMS) { GXStandardObisCode d = list[list.Length - 1]; code.DataType = d.DataType; } //If string is used string datatype = code.DataType; if (datatype == null) { datatype = ""; } if (string.IsNullOrEmpty(code.UIDataType)) { if (datatype.Contains("10")) { code.UIDataType = "10"; } //If date time is used. else if (datatype.Contains("25") || datatype.Contains("26")) { code.UIDataType = "25"; } //Time stamps of the billing periods objects (first scheme if there are two) else if (datatype.Contains("9")) { if ((GXStandardObisCodeCollection.EqualsMask("0.0-64.96.7.10-14.255", it.LogicalName) || //Time stamps of the billing periods objects (second scheme) GXStandardObisCodeCollection.EqualsMask("0.0-64.0.1.5.0-99,255", it.LogicalName) || //Time of power failure GXStandardObisCodeCollection.EqualsMask("0.0-64.0.1.2.0-99,255", it.LogicalName) || //Time stamps of the billing periods objects (first scheme if there are two) GXStandardObisCodeCollection.EqualsMask("1.0-64.0.1.2.0-99,255", it.LogicalName) || //Time stamps of the billing periods objects (second scheme) GXStandardObisCodeCollection.EqualsMask("1.0-64.0.1.5.0-99,255", it.LogicalName) || //Time expired since last end of billing period GXStandardObisCodeCollection.EqualsMask("1.0-64.0.9.0.255", it.LogicalName) || //Time of last reset GXStandardObisCodeCollection.EqualsMask("1.0-64.0.9.6.255", it.LogicalName) || //Date of last reset GXStandardObisCodeCollection.EqualsMask("1.0-64.0.9.7.255", it.LogicalName) || //Time expired since last end of billing period (Second billing period scheme) GXStandardObisCodeCollection.EqualsMask("1.0-64.0.9.13.255", it.LogicalName) || //Time of last reset (Second billing period scheme) GXStandardObisCodeCollection.EqualsMask("1.0-64.0.9.14.255", it.LogicalName) || //Date of last reset (Second billing period scheme) GXStandardObisCodeCollection.EqualsMask("1.0-64.0.9.15.255", it.LogicalName))) { code.UIDataType = "25"; } //Local time else if (GXStandardObisCodeCollection.EqualsMask("1.0-64.0.9.1.255", it.LogicalName)) { code.UIDataType = "27"; } //Local date else if (GXStandardObisCodeCollection.EqualsMask("1.0-64.0.9.2.255", it.LogicalName)) { code.UIDataType = "26"; } //Active firmware identifier else if (GXStandardObisCodeCollection.EqualsMask("1.0.0.2.0.255", it.LogicalName)) { code.UIDataType = "10"; } } //Unix time else if (it.ObjectType == ObjectType.Data && GXStandardObisCodeCollection.EqualsMask("0.0.1.1.0.255", it.LogicalName)) { code.UIDataType = "25"; } } if (code.DataType != "*" && !string.IsNullOrEmpty(code.DataType) && !code.DataType.Contains(",")) { DataType type = (DataType)int.Parse(code.DataType); switch (it.ObjectType) { case ObjectType.Data: case ObjectType.Register: case ObjectType.RegisterActivation: case ObjectType.ExtendedRegister: it.SetDataType(2, type); break; default: break; } } if (!string.IsNullOrEmpty(code.UIDataType)) { DataType uiType = (DataType)int.Parse(code.UIDataType); switch (it.ObjectType) { case ObjectType.Data: case ObjectType.Register: case ObjectType.RegisterActivation: case ObjectType.ExtendedRegister: it.SetUIDataType(2, uiType); break; default: break; } } }
/// <summary> /// Get country spesific OBIS codes. /// </summary> /// <param name="standard">Used standard.</param> /// <returns>Collection for special OBIC codes.</returns> public static GXObisCode[] GetObjects(Standard standard) { List <GXObisCode> codes = new List <GXObisCode>(); #if !WINDOWS_UWP string[] rows; #if __MOBILE__ if (standard == Standard.Italy) { rows = Resources.Italy.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); } else if (standard == Standard.India) { rows = Resources.India.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); } else if (standard == Standard.SaudiArabia) { rows = Resources.SaudiArabia.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); } else { return(new GXObisCode[0]); } #else if (standard == Standard.Italy) { rows = Gurux.DLMS.Properties.Resources.Italy.Split(new string[] { Environment.NewLine, "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries); } else if (standard == Standard.India) { rows = Gurux.DLMS.Properties.Resources.India.Split(new string[] { Environment.NewLine, "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries); } else if (standard == Standard.SaudiArabia) { rows = Gurux.DLMS.Properties.Resources.SaudiArabia.Split(new string[] { Environment.NewLine, "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries); } else { return(new GXObisCode[0]); } #endif //!__MOBILE__ foreach (string it in rows) { if (!it.StartsWith("#")) { string[] items = it.Split(new char[] { ';' }); ObjectType ot = (ObjectType)int.Parse(items[0]); string ln = GXCommon.ToLogicalName(GXCommon.LogicalNameToBytes(items[1])); int version = int.Parse(items[2]); string desc = items[3]; GXObisCode code = new GXObisCode(ln, ot, desc); if (items.Length > 4) { code.UIDataType = items[4]; } code.Version = version; codes.Add(code); } } #endif return(codes.ToArray()); }
public void Update(Standard standard) { _validator.ValidateAndThrow(standard, ruleSet: nameof(IStandardLogic.Create)); _datastore.Update(standard); }
void UpdateData(DataTable dt) { Standard standard = Standard.DLMS; if (target.Parent != null && target.Parent.Parent is GXDLMSClient) { standard = ((GXDLMSClient)target.Parent.Parent).Standard; } List <object> rows = GXDLMSCompactData.GetData(target.TemplateDescription, target.Buffer, standard == Standard.Italy); if (structures) { List <object[]> data = new List <object[]>(); foreach (List <object> r in rows) { List <object> row = new List <object>(); int index = 0; foreach (var it in target.CaptureObjects) { //If COSEM object is selected. //Only few meters are supporting this. if (it.Value.AttributeIndex == 0 && r[index] is List <object> ) { //Values must be update to the list because there might be Register Scaler //and it expects that scaler is read before value is updated. GXDLMSObject obj = GXDLMSClient.CreateObject(it.Key.ObjectType); byte i2 = 1; Dictionary <byte, object> list = new Dictionary <byte, object>(); foreach (object v in (r[index] as object[])) { list.Add(i2, v); ++i2; } //Update values first. for (byte i = 0; i != (obj as IGXDLMSBase).GetAttributeCount(); ++i) { ValueEventArgs ve = new ValueEventArgs(obj, i, 0, null); ve.Value = list[i]; (obj as IGXDLMSBase).SetValue(null, ve); } //Show values. for (byte i = 0; i != (obj as IGXDLMSBase).GetAttributeCount(); ++i) { row.Add(GetValue(obj.GetValues()[i])); } } else { row.Add(GetValue(r[index])); } ++index; } data.Add(row.ToArray()); } for (int pos = dt.Rows.Count; pos < data.Count; ++pos) { object[] row = data[pos]; dt.LoadDataRow(row, true); } } else { for (int pos = dt.Rows.Count; pos < rows.Count; ++pos) { List <object> row = (List <object>)rows[pos]; if (row != null) { for (int col = 0; col != row.Count; ++col) { if (row[col] is byte[]) { if (pos < target.CaptureObjects.Count && target.CaptureObjects[col].Key.GetUIDataType(target.CaptureObjects[col].Value.AttributeIndex) == DataType.DateTime) { row[col] = GXDLMSClient.ChangeType(row[col] as byte[], DataType.DateTime); } else { row[col] = GXDLMSTranslator.ToHex((byte[])row[col], true); } } else if (row[col] is Object[]) { row[col] = GXDLMSTranslator.ValueToXml(row[col]); } else if (row[col] is List <Object> ) { row[col] = GXDLMSTranslator.ValueToXml(row[col]); } else if (col < target.CaptureObjects.Count) { GXDLMSAttributeSettings att = target.CaptureObjects[col].Key.Attributes.Find(target.CaptureObjects[col].Value.AttributeIndex); if (att != null && att.Values != null) { if (att.Type == DataType.BitString && row[col] is string) { string str = (string)row[col]; if (str.Length != 0 && (str[0] == '0' || str[0] == '1')) { StringBuilder sb = new StringBuilder(); int pos2 = 0; foreach (char it in str) { if (it == '1') { if (sb.Length != 0) { sb.Append(','); } sb.Append(att.Values[pos2].UIValue); } ++pos2; if (pos2 == att.Values.Count) { break; } } row[col] = sb.ToString(); } } else { foreach (GXObisValueItem it in att.Values) { if (IsNumber(row[col]) && it.Value == Convert.ToInt32(row[col])) { row[col] = it.UIValue; break; } } } } } } if (dt.Columns.Count != 0) { try { dt.LoadDataRow(row.ToArray(), true); } catch (Exception) { //It's OK if this fails. } } } } } }
/// <summary> /// Returns the best formatted string representation of a byte value /// </summary> /// <param name="bytes">number of bytes</param> /// <param name="st"></param> /// <returns>formatted string</returns> private static string ToString(long bytes, Standard st = Standard.Iec) { return ToString(bytes, st, null); }
/// <summary> /// Returns a hash code for this instance, which is suitable for use in hashing algorithms and data structures like a hash table. /// </summary> /// <returns>A hash code for the current object.</returns> public override int GetHashCode() { return(HashCode.Combine(m_day.GetHashCode(), m_secondsOfDay.GetHashCode(), Standard.GetHashCode())); }
protected Step(Standard standard, string name) { Standard = standard; Name = name; ExecutionTime = new Duration(0); }
/// <summary> /// Returns the best formatted string representation of a byte value /// </summary> /// <param name="bytes">number of bytes</param> /// <param name="st"></param> /// <param name="customFormat">Defines a custom numerical format for the conversion. /// If this parameters is null or empty the default format will be used 0.00</param> /// <returns>formatted string</returns> public static string ToString(long bytes, Standard st, string customFormat) { if (bytes == 0) { return("0"); } if (string.IsNullOrEmpty(customFormat)) { customFormat = "0.00"; } string result; bool isNegative = bytes < 0; bytes = Math.Abs(bytes); if (st == Standard.Si) { if (bytes < Mb) { result = BytesToKb(bytes, customFormat); } else if (bytes < Gb) { result = BytesToMb(bytes, customFormat); } else if (bytes < Tb) { result = BytesToGb(bytes, customFormat); } else if (bytes < Pb) { result = BytesToTb(bytes, customFormat); } else { result = BytesToPb(bytes, customFormat); } } else { if (bytes < MiB) { result = BytesToKib(bytes, customFormat); } else if (bytes < GiB) { result = BytesToMib(bytes, customFormat); } else if (bytes < TiB) { result = BytesToGib(bytes, customFormat); } else if (bytes < PiB) { result = BytesToTib(bytes, customFormat); } else { result = BytesToPib(bytes, customFormat); } } return(isNegative ? ("-" + result) : (result)); }
public bool Transcode(TranscodeInfo info, MediaPortal.Core.Transcoding.VideoFormat format, MediaPortal.Core.Transcoding.Quality quality, Standard standard) { if (!Supports(format)) return false; string ext = System.IO.Path.GetExtension(info.file); if (ext.ToLowerInvariant() != ".ts" && ext.ToLowerInvariant() != ".mpg") { Log.Info("TSReader2MP4: wrong file format"); return false; } try { graphBuilder = (IGraphBuilder)new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); Log.Info("TSReader2MP4: add filesource"); TsReader reader = new TsReader(); tsreaderSource = (IBaseFilter)reader; IBaseFilter filter = (IBaseFilter)tsreaderSource; graphBuilder.AddFilter(filter, "TSReader Source"); IFileSourceFilter fileSource = (IFileSourceFilter)tsreaderSource; Log.Info("TSReader2MP4: load file:{0}", info.file); int hr = fileSource.Load(info.file, null); //add audio/video codecs string strVideoCodec = ""; string strH264VideoCodec = ""; string strAudioCodec = ""; string strAACAudioCodec = ""; using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings()) { strVideoCodec = xmlreader.GetValueAsString("mytv", "videocodec", ""); strAudioCodec = xmlreader.GetValueAsString("mytv", "audiocodec", ""); strAACAudioCodec = xmlreader.GetValueAsString("mytv", "aacaudiocodec", ""); strH264VideoCodec = xmlreader.GetValueAsString("mytv", "h264videocodec", ""); } //Find the type of decoder required for the output video & audio pins on TSReader. Log.Info("TSReader2MP4: find tsreader compatible audio/video decoders"); IPin pinOut0, pinOut1; IPin pinIn0, pinIn1; pinOut0 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 0); //audio pinOut1 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 1); //video if (pinOut0 == null || pinOut1 == null) { Log.Error("TSReader2MP4: FAILED: unable to get output pins of tsreader"); Cleanup(); return false; } bool usingAAC = false; IEnumMediaTypes enumMediaTypes; hr = pinOut0.EnumMediaTypes(out enumMediaTypes); while (true) { AMMediaType[] mediaTypes = new AMMediaType[1]; int typesFetched; hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched); if (hr != 0 || typesFetched == 0) break; if (mediaTypes[0].majorType == MediaType.Audio && mediaTypes[0].subType == MediaSubType.LATMAAC) { Log.Info("TSReader2MP4: found LATM AAC audio out pin on tsreader"); usingAAC = true; } } bool usingH264 = false; hr = pinOut1.EnumMediaTypes(out enumMediaTypes); while (true) { AMMediaType[] mediaTypes = new AMMediaType[1]; int typesFetched; hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched); if (hr != 0 || typesFetched == 0) break; if (mediaTypes[0].majorType == MediaType.Video && mediaTypes[0].subType == AVC1) { Log.Info("TSReader2MP4: found H.264 video out pin on tsreader"); usingH264 = true; } } //Add the type of decoder required for the output video & audio pins on TSReader. Log.Info("TSReader2MP4: add audio/video decoders to graph"); if (usingH264 == false) { Log.Info("TSReader2MP4: add mpeg2 video decoder:{0}", strVideoCodec); VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec); if (VideoCodec == null) { Log.Error("TSReader2MP4: unable to add mpeg2 video decoder"); Cleanup(); return false; } } else { Log.Info("TSReader2MP4: add h264 video codec:{0}", strH264VideoCodec); VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strH264VideoCodec); if (VideoCodec == null) { Log.Error("TSReader2MP4: FAILED:unable to add h264 video codec"); Cleanup(); return false; } } if (usingAAC == false) { Log.Info("TSReader2MP4: add mpeg2 audio codec:{0}", strAudioCodec); AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec); if (AudioCodec == null) { Log.Error("TSReader2MP4: FAILED:unable to add mpeg2 audio codec"); Cleanup(); return false; } } else { Log.Info("TSReader2MP4: add aac audio codec:{0}", strAACAudioCodec); AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAACAudioCodec); if (AudioCodec == null) { Log.Error("TSReader2MP4: FAILED:unable to add aac audio codec"); Cleanup(); return false; } } Log.Info("TSReader2MP4: connect tsreader->audio/video decoders"); //connect output #0 (audio) of tsreader->audio decoder input pin 0 //connect output #1 (video) of tsreader->video decoder input pin 0 pinIn0 = DsFindPin.ByDirection(AudioCodec, PinDirection.Input, 0); //audio pinIn1 = DsFindPin.ByDirection(VideoCodec, PinDirection.Input, 0); //video if (pinIn0 == null || pinIn1 == null) { Log.Error("TSReader2MP4: FAILED: unable to get pins of video/audio codecs"); Cleanup(); return false; } hr = graphBuilder.Connect(pinOut0, pinIn0); if (hr != 0) { Log.Error("TSReader2MP4: FAILED: unable to connect audio pins :0x{0:X}", hr); Cleanup(); return false; } hr = graphBuilder.Connect(pinOut1, pinIn1); if (hr != 0) { Log.Error("TSReader2MP4: FAILED: unable to connect video pins :0x{0:X}", hr); Cleanup(); return false; } //add encoders, muxer & filewriter if (!AddCodecs(graphBuilder, info)) return false; //setup graph controls mediaControl = graphBuilder as IMediaControl; mediaSeeking = tsreaderSource as IMediaSeeking; mediaEvt = graphBuilder as IMediaEventEx; mediaPos = graphBuilder as IMediaPosition; //get file duration Log.Info("TSReader2MP4: Get duration of recording"); long lTime = 5 * 60 * 60; lTime *= 10000000; long pStop = 0; hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); if (hr == 0) { long lStreamPos; mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position m_dDuration = lStreamPos; lTime = 0; mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); } double duration = m_dDuration / 10000000d; Log.Info("TSReader2MP4: recording duration: {0}", MediaPortal.Util.Utils.SecondsToHMSString((int)duration)); //run the graph to initialize the filters to be sure hr = mediaControl.Run(); if (hr != 0) { Log.Error("TSReader2MP4: FAILED: unable to start graph :0x{0:X}", hr); Cleanup(); return false; } int maxCount = 20; while (true) { long lCurrent; mediaSeeking.GetCurrentPosition(out lCurrent); double dpos = (double)lCurrent; dpos /= 10000000d; System.Threading.Thread.Sleep(100); if (dpos >= 2.0d) break; maxCount--; if (maxCount <= 0) break; } mediaControl.Stop(); FilterState state; mediaControl.GetState(500, out state); GC.Collect(); GC.Collect(); GC.Collect(); GC.WaitForPendingFinalizers(); graphBuilder.RemoveFilter(mp4Muxer); graphBuilder.RemoveFilter(h264Encoder); graphBuilder.RemoveFilter(aacEncoder); graphBuilder.RemoveFilter((IBaseFilter)fileWriterFilter); if (!AddCodecs(graphBuilder, info)) return false; //Set Encoder quality & Muxer settings if (!EncoderSet(graphBuilder, info)) return false; //start transcoding - run the graph Log.Info("TSReader2MP4: start transcoding"); //setup flow control //need to leverage CBAsePin, CPullPin & IAsyncReader methods. IAsyncReader synchVideo = null; mediaSample = VideoCodec as IMediaSample; hr = synchVideo.SyncReadAligned(mediaSample); //So we only parse decoder output whent the encoders are ready. hr = mediaControl.Run(); if (hr != 0) { Log.Error("TSReader2MP4: FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return false; } } catch (Exception ex) { Log.Error("TSReader2MP4: Unable create graph: {0}", ex.Message); Cleanup(); return false; } return true; }
public bool UpdateStandardValueAsIFormCollection(IFormCollection fc, string UserID) { int StandardID = Convert.ToInt32(fc["StandardID"]); string RecordID = fc["ID"]; List <StandardConfigModel> Configs = new StandardConfigModel().SelectStandardConfigs(StandardID); //StandardModel model = new StandardModel().SelectSingleStandard(StandardID); AutomationStandardsContext db = new AutomationStandardsContext(); //List<StandardConfigModel> Configs = new List<StandardConfigModel>(); List <StandardConfig> dbConfigs = db.StandardConfig.Where(x => x.StandardID == StandardID).ToList(); foreach (var c in dbConfigs) { StandardConfigModel scm = new StandardConfigModel(); scm.SQLDataType = db.StandardDataType.Where(x => x.DataTypeID == c.DataTypeID).First().SQLDataType; scm.FieldName = c.FieldName; Configs.Add(scm); } Standard model = db.Standard.Where(x => x.StandardID == StandardID).FirstOrDefault(); //if (model.NotifiyOwner) //{ // NotifyStandardOwner("UPDATE", fc, Configs, model, UserID); //} SetStandardVersionValue(model.StandardID); string SQL = "UPDATE " + model.DBTableName + " SET "; SQL += " ModifiedOn = '" + DateTime.Now + "', "; SQL += " ModifiedBy = '" + UserID + "', "; foreach (var formKey in fc.Keys) //AllKeys) { List <StandardConfigModel> foundConfig = Configs.Where(c => c.FieldName == formKey).ToList(); if (foundConfig.Count > 0) { StandardConfigModel config = foundConfig.First(); string value; if (string.IsNullOrEmpty(fc[config.FieldName])) { value = ""; } else { if (config.AllowMultiSelect) { value = ";" + fc[config.FieldName]; //.Replace(",", ";") + ";"; value = value.Replace(",", ";") + ";"; } else { value = fc[config.FieldName]; } } SQL += " " + config.FieldName + " = CAST('" + value + "' AS " + config.SQLDataType + ") , "; } } SQL += " Enabled = CAST('" + fc["Enabled"] + "' AS BIT) , "; SQL += " SortOrder = " + fc["SortOrder"] + " "; SQL += " WHERE ID = " + RecordID; bool Result = ExecuteSql(SQL); return(Result); }
private bool AddWmAsfWriter(string fileName, Quality quality, Standard standard) { //add asf file writer IPin pinOut0, pinOut1; IPin pinIn0, pinIn1; Log.Info("TSReader2WMV: add WM ASF Writer to graph"); string monikerAsfWriter = @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{7C23220E-55BB-11D3-8B16-00C04FB6BD3D}"; fileWriterbase = Marshal.BindToMoniker(monikerAsfWriter) as IBaseFilter; if (fileWriterbase == null) { Log.Error("TSReader2WMV:FAILED:Unable to create ASF WM Writer"); Cleanup(); return false; } int hr = graphBuilder.AddFilter(fileWriterbase, "WM ASF Writer"); if (hr != 0) { Log.Error("TSReader2WMV:FAILED:Add ASF WM Writer to filtergraph :0x{0:X}", hr); Cleanup(); return false; } IFileSinkFilter2 fileWriterFilter = fileWriterbase as IFileSinkFilter2; if (fileWriterFilter == null) { Log.Error("DVR2XVID:FAILED:Add unable to get IFileSinkFilter for filewriter"); Cleanup(); return false; } hr = fileWriterFilter.SetFileName(fileName, null); hr = fileWriterFilter.SetMode(AMFileSinkFlags.OverWrite); Log.Info("TSReader2WMV: connect audio/video codecs outputs -> ASF WM Writer"); //connect output #0 of videocodec->asf writer pin 1 //connect output #0 of audiocodec->asf writer pin 0 pinOut0 = DsFindPin.ByDirection((IBaseFilter)AudioCodec, PinDirection.Output, 0); pinOut1 = DsFindPin.ByDirection((IBaseFilter)VideoCodec, PinDirection.Output, 0); if (pinOut0 == null || pinOut1 == null) { Log.Error("TSReader2WMV:FAILED:unable to get outpins of video codec"); Cleanup(); return false; } pinIn0 = DsFindPin.ByDirection(fileWriterbase, PinDirection.Input, 0); if (pinIn0 == null) { Log.Error("TSReader2WMV:FAILED:unable to get pins of asf wm writer"); Cleanup(); return false; } hr = graphBuilder.Connect(pinOut0, pinIn0); if (hr != 0) { Log.Error("TSReader2WMV:FAILED:unable to connect audio pins :0x{0:X}", hr); Cleanup(); return false; } pinIn1 = DsFindPin.ByDirection(fileWriterbase, PinDirection.Input, 1); if (pinIn1 == null) { Log.Error("TSReader2WMV:FAILED:unable to get pins of asf wm writer"); Cleanup(); return false; } hr = graphBuilder.Connect(pinOut1, pinIn1); if (hr != 0) { Log.Error("TSReader2WMV:FAILED:unable to connect video pins :0x{0:X}", hr); Cleanup(); return false; } IConfigAsfWriter config = fileWriterbase as IConfigAsfWriter; IWMProfileManager profileManager = null; IWMProfileManager2 profileManager2 = null; IWMProfile profile = null; hr = WMLib.WMCreateProfileManager(out profileManager); string strprofileType = ""; switch (quality) { case Quality.HiDef: //hr = WMLib.WMCreateProfileManager(out profileManager); if (standard == Standard.Film) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHiDef-FILM.prx"); } if (standard == Standard.NTSC) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHiDef-NTSC.prx"); } if (standard == Standard.PAL) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHiDef-PAL.prx"); } Log.Info("TSReader2WMV: set WMV HiDef quality profile {0}", strprofileType); break; case Quality.VeryHigh: if (standard == Standard.Film) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPVeryHigh-FILM.prx"); } if (standard == Standard.NTSC) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPVeryHigh-NTSC.prx"); } if (standard == Standard.PAL) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPVeryHigh-PAL.prx"); } Log.Info("TSReader2WMV: set WMV Very High quality profile {0}", strprofileType); break; case Quality.High: if (standard == Standard.Film) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHigh-FILM.prx"); } if (standard == Standard.NTSC) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHigh-NTSC.prx"); } if (standard == Standard.PAL) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHigh-PAL.prx"); } Log.Info("TSReader2WMV: set WMV High quality profile {0}", strprofileType); break; case Quality.Medium: if (standard == Standard.Film) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPMedium-FILM.prx"); } if (standard == Standard.NTSC) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPMedium-NTSC.prx"); } if (standard == Standard.PAL) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPMedium-PAL.prx"); } Log.Info("TSReader2WMV: set WMV Medium quality profile {0}", strprofileType); break; case Quality.Low: if (standard == Standard.Film) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPLow-FILM.prx"); } if (standard == Standard.NTSC) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPLow-NTSC.prx"); } if (standard == Standard.PAL) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPLow-PAL.prx"); } Log.Info("TSReader2WMV: set WMV Low quality profile {0}", strprofileType); break; case Quality.Portable: if (standard == Standard.Film) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPPortable-FILM.prx"); } if (standard == Standard.NTSC) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPPortable-NTSC.prx"); } if (standard == Standard.PAL) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPPortable-PAL.prx"); } Log.Info("TSReader2WMV: set WMV Portable quality profile {0}", strprofileType); break; case Quality.Custom: //load custom profile string customBitrate = ""; //Adjust the parameters to suit the custom settings the user has selected. switch (bitrate) { case 0: customBitrate = "100Kbs"; break; case 1: customBitrate = "256Kbs"; break; case 2: customBitrate = "384Kbs"; break; case 3: customBitrate = "768Kbs"; break; case 4: customBitrate = "1536Kbs"; break; case 5: customBitrate = "3072Kbs"; break; case 6: customBitrate = "5376Kbs"; break; } Log.Info("TSReader2WMV: custom bitrate = {0}", customBitrate); //TODO: get fps values & frame size //TODO: adjust settings required //Call the SetCutomPorfile method to load the custom profile, adjust it's params from user settings & then save it. //SetCutomProfile(videoBitrate, audioBitrate, videoHeight, videoWidth, videoFps); //based on user inputs //We then reload it after as per other quality settings / profiles. strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPCustom.prx"); Log.Info("TSReader2WMV: set WMV Custom quality profile {0}", strprofileType); break; } //Loads profile from the above quality selection. using (StreamReader prx = new StreamReader(strprofileType)) { String profileContents = prx.ReadToEnd(); profileManager2 = profileManager as IWMProfileManager2; hr = profileManager2.LoadProfileByData(profileContents, out profile); } if (hr != 0) { Log.Info("TSReader2WMV: get WMV profile - FAILED! {0}", hr); Cleanup(); return false; } Log.Info("TSReader2WMV: load profile - SUCCESS!"); //configures the WM ASF Writer to the chosen profile hr = config.ConfigureFilterUsingProfile(profile); if (hr != 0) { Log.Info("TSReader2WMV: configure profile - FAILED! {0}", hr); Cleanup(); return false; } Log.Info("TSReader2WMV: configure profile - SUCCESS!"); //TODO: Add DB recording information into WMV. //Release resorces if (profile != null) { Marshal.ReleaseComObject(profile); profile = null; } if (profileManager != null) { Marshal.ReleaseComObject(profileManager); profileManager = null; } return true; }
public bool Transcode(TranscodeInfo info, VideoFormat format, Quality quality, Standard standard) { try { if (!Supports(format)) return false; string ext = System.IO.Path.GetExtension(info.file); if (ext.ToLower() != ".ts" && ext.ToLower() != ".mpg") { Log.Info("TSReader2WMV: wrong file format"); return false; } Log.Info("TSReader2WMV: create graph"); graphBuilder = (IGraphBuilder)new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); Log.Info("TSReader2WMV: add filesource"); TsReader reader = new TsReader(); tsreaderSource = (IBaseFilter)reader; //ITSReader ireader = (ITSReader)reader; //ireader.SetTsReaderCallback(this); //ireader.SetRequestAudioChangeCallback(this); IBaseFilter filter = (IBaseFilter)tsreaderSource; graphBuilder.AddFilter(filter, "TSReader Source"); IFileSourceFilter fileSource = (IFileSourceFilter)tsreaderSource; Log.Info("TSReader2WMV: load file:{0}", info.file); int hr = fileSource.Load(info.file, null); //add audio/video codecs string strVideoCodec = ""; string strH264VideoCodec = ""; string strAudioCodec = ""; string strAACAudioCodec = ""; using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings()) { strVideoCodec = xmlreader.GetValueAsString("mytv", "videocodec", ""); strAudioCodec = xmlreader.GetValueAsString("mytv", "audiocodec", ""); strAACAudioCodec = xmlreader.GetValueAsString("mytv", "aacaudiocodec", ""); strH264VideoCodec = xmlreader.GetValueAsString("mytv", "h264videocodec", ""); } //Find the type of decoder required for the output video & audio pins on TSReader. Log.Info("TSReader2WMV: find tsreader compatible audio/video decoders"); IPin pinOut0, pinOut1; IPin pinIn0, pinIn1; pinOut0 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 0); //audio pinOut1 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 1); //video if (pinOut0 == null || pinOut1 == null) { Log.Error("TSReader2WMV: FAILED: unable to get output pins of tsreader"); Cleanup(); return false; } bool usingAAC = false; IEnumMediaTypes enumMediaTypes; hr = pinOut0.EnumMediaTypes(out enumMediaTypes); while (true) { AMMediaType[] mediaTypes = new AMMediaType[1]; int typesFetched; hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched); if (hr != 0 || typesFetched == 0) break; if (mediaTypes[0].majorType == MediaType.Audio && mediaTypes[0].subType == MediaSubType.LATMAAC) { Log.Info("TSReader2WMV: found LATM AAC audio out pin on tsreader"); usingAAC = true; } } bool usingH264 = false; hr = pinOut1.EnumMediaTypes(out enumMediaTypes); while (true) { AMMediaType[] mediaTypes = new AMMediaType[1]; int typesFetched; hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched); if (hr != 0 || typesFetched == 0) break; if (mediaTypes[0].majorType == MediaType.Video && mediaTypes[0].subType == AVC1) { Log.Info("TSReader2WMV: found H.264 video out pin on tsreader"); usingH264 = true; } } //Add the type of decoder required for the output video & audio pins on TSReader. Log.Info("TSReader2WMV: add audio/video decoders to graph"); if (usingH264 == false) { Log.Info("TSReader2WMV: add mpeg2 video decoder:{0}", strVideoCodec); VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec); if (VideoCodec == null) { Log.Error("TSReader2WMV: unable to add mpeg2 video decoder"); Cleanup(); return false; } } else { Log.Info("TSReader2WMV: add h264 video codec:{0}", strH264VideoCodec); VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strH264VideoCodec); if (VideoCodec == null) { Log.Error("TSReader2WMV: FAILED:unable to add h264 video codec"); Cleanup(); return false; } } if (usingAAC == false) { Log.Info("TSReader2WMV: add mpeg2 audio codec:{0}", strAudioCodec); AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec); if (AudioCodec == null) { Log.Error("TSReader2WMV: FAILED:unable to add mpeg2 audio codec"); Cleanup(); return false; } } else { Log.Info("TSReader2WMV: add aac audio codec:{0}", strAACAudioCodec); AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAACAudioCodec); if (AudioCodec == null) { Log.Error("TSReader2WMV: FAILED:unable to add aac audio codec"); Cleanup(); return false; } } Log.Info("TSReader2WMV: connect tsreader->audio/video decoders"); //connect output #0 (audio) of tsreader->audio decoder input pin 0 //connect output #1 (video) of tsreader->video decoder input pin 0 pinIn0 = DsFindPin.ByDirection(AudioCodec, PinDirection.Input, 0); //audio pinIn1 = DsFindPin.ByDirection(VideoCodec, PinDirection.Input, 0); //video if (pinIn0 == null || pinIn1 == null) { Log.Error("TSReader2WMV: FAILED: unable to get pins of video/audio codecs"); Cleanup(); return false; } hr = graphBuilder.Connect(pinOut0, pinIn0); if (hr != 0) { Log.Error("TSReader2WMV: FAILED: unable to connect audio pins :0x{0:X}", hr); Cleanup(); return false; } hr = graphBuilder.Connect(pinOut1, pinIn1); if (hr != 0) { Log.Error("TSReader2WMV: FAILED: unable to connect video pins :0x{0:X}", hr); Cleanup(); return false; } string outputFilename = System.IO.Path.ChangeExtension(info.file, ".wmv"); if (!AddWmAsfWriter(outputFilename, quality, standard)) return false; Log.Info("TSReader2WMV: start pre-run"); mediaControl = graphBuilder as IMediaControl; mediaSeeking = tsreaderSource as IMediaSeeking; mediaEvt = graphBuilder as IMediaEventEx; mediaPos = graphBuilder as IMediaPosition; //get file duration long lTime = 5 * 60 * 60; lTime *= 10000000; long pStop = 0; hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); if (hr == 0) { long lStreamPos; mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position m_dDuration = lStreamPos; lTime = 0; mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); } double duration = m_dDuration / 10000000d; Log.Info("TSReader2WMV: movie duration:{0}", Util.Utils.SecondsToHMSString((int)duration)); hr = mediaControl.Run(); if (hr != 0) { Log.Error("TSReader2WMV: FAILED: unable to start graph :0x{0:X}", hr); Cleanup(); return false; } int maxCount = 20; while (true) { long lCurrent; mediaSeeking.GetCurrentPosition(out lCurrent); double dpos = (double)lCurrent; dpos /= 10000000d; System.Threading.Thread.Sleep(100); if (dpos >= 2.0d) break; maxCount--; if (maxCount <= 0) break; } Log.Info("TSReader2WMV: pre-run done"); Log.Info("TSReader2WMV: Get duration of movie"); mediaControl.Stop(); FilterState state; mediaControl.GetState(500, out state); GC.Collect(); GC.Collect(); GC.Collect(); GC.WaitForPendingFinalizers(); Log.Info("TSReader2WMV: reconnect mpeg2 video codec->ASF WM Writer"); graphBuilder.RemoveFilter(fileWriterbase); if (!AddWmAsfWriter(outputFilename, quality, standard)) return false; Log.Info("TSReader2WMV: Start transcoding"); hr = mediaControl.Run(); if (hr != 0) { Log.Error("TSReader2WMV:FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return false; } } catch (Exception e) { // TODO: Handle exceptions. Log.Error("unable to transcode file:{0} message:{1}", info.file, e.Message); return false; } return true; }
public bool Transcode(TranscodeInfo info, VideoFormat format, Quality quality, Standard standard) { try { if (!Supports(format)) return false; string ext = System.IO.Path.GetExtension(info.file); if (ext.ToLowerInvariant() != ".dvr-ms" && ext.ToLowerInvariant() != ".sbe") { Log.Info("DVRMS2WMV: wrong file format"); return false; } Log.Info("DVRMS2WMV: create graph"); graphBuilder = (IGraphBuilder)new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); Log.Info("DVRMS2WMV: add streambuffersource"); bufferSource = (IStreamBufferSource)new StreamBufferSource(); IBaseFilter filter = (IBaseFilter)bufferSource; graphBuilder.AddFilter(filter, "SBE SOURCE"); Log.Info("DVRMS2WMV: load file:{0}", info.file); IFileSourceFilter fileSource = (IFileSourceFilter)bufferSource; int hr = fileSource.Load(info.file, null); //add mpeg2 audio/video codecs string strVideoCodec = ""; string strAudioCodec = ""; using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings()) { strVideoCodec = xmlreader.GetValueAsString("mytv", "videocodec", "MPC - MPEG-2 Video Decoder (Gabest)"); strAudioCodec = xmlreader.GetValueAsString("mytv", "audiocodec", "MPC - MPA Decoder Filter"); } Log.Info("DVRMS2WMV: add mpeg2 video codec:{0}", strVideoCodec); Mpeg2VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:Add mpeg2 video to filtergraph :0x{0:X}", hr); Cleanup(); return false; } Log.Info("DVRMS2WMV: add mpeg2 audio codec:{0}", strAudioCodec); Mpeg2AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec); if (Mpeg2AudioCodec == null) { Log.Error("DVRMS2WMV:FAILED:unable to add mpeg2 audio codec"); Cleanup(); return false; } Log.Info("DVRMS2WMV: connect streambufer source->mpeg audio/video decoders"); //connect output #0 of streambuffer source->mpeg2 audio codec pin 1 //connect output #1 of streambuffer source->mpeg2 video codec pin 1 IPin pinOut0, pinOut1; IPin pinIn0, pinIn1; pinOut0 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 0); //audio pinOut1 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 1); //video if (pinOut0 == null || pinOut1 == null) { Log.Error("DVRMS2WMV:FAILED:unable to get pins of source"); Cleanup(); return false; } pinIn0 = DsFindPin.ByDirection(Mpeg2VideoCodec, PinDirection.Input, 0); //video pinIn1 = DsFindPin.ByDirection(Mpeg2AudioCodec, PinDirection.Input, 0); //audio if (pinIn0 == null || pinIn1 == null) { Log.Error("DVRMS2WMV:FAILED:unable to get pins of mpeg2 video/audio codec"); Cleanup(); return false; } hr = graphBuilder.Connect(pinOut0, pinIn1); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to connect audio pins :0x{0:X}", hr); Cleanup(); return false; } hr = graphBuilder.Connect(pinOut1, pinIn0); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to connect video pins :0x{0:X}", hr); Cleanup(); return false; } string outputFilename = System.IO.Path.ChangeExtension(info.file, ".wmv"); if (!AddWmAsfWriter(outputFilename, quality, standard)) return false; Log.Info("DVRMS2WMV: start pre-run"); mediaControl = graphBuilder as IMediaControl; mediaSeeking = bufferSource as IStreamBufferMediaSeeking; mediaEvt = graphBuilder as IMediaEventEx; mediaPos = graphBuilder as IMediaPosition; //get file duration long lTime = 5 * 60 * 60; lTime *= 10000000; long pStop = 0; hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); if (hr == 0) { long lStreamPos; mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position m_dDuration = lStreamPos; lTime = 0; mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); } double duration = m_dDuration / 10000000d; Log.Info("DVRMS2WMV: movie duration:{0}", Util.Utils.SecondsToHMSString((int)duration)); hr = mediaControl.Run(); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return false; } int maxCount = 20; while (true) { long lCurrent; mediaSeeking.GetCurrentPosition(out lCurrent); double dpos = (double)lCurrent; dpos /= 10000000d; System.Threading.Thread.Sleep(100); if (dpos >= 2.0d) break; maxCount--; if (maxCount <= 0) break; } Log.Info("DVRMS2WMV: pre-run done"); Log.Info("DVRMS2WMV: Get duration of movie"); mediaControl.Stop(); FilterState state; mediaControl.GetState(500, out state); GC.Collect(); GC.Collect(); GC.Collect(); GC.WaitForPendingFinalizers(); Log.Info("DVRMS2WMV: reconnect mpeg2 video codec->ASF WM Writer"); graphBuilder.RemoveFilter(fileWriterbase); if (!AddWmAsfWriter(outputFilename, quality, standard)) return false; Log.Info("DVRMS2WMV: Start transcoding"); hr = mediaControl.Run(); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return false; } } catch (Exception e) { // TODO: Handle exceptions. Log.Error("unable to transcode file:{0} message:{1}", info.file, e.Message); return false; } return true; }
public void UpdateStandard(Standard standard) { _standardRepository.Update(standard); }
public bool Transcode(TranscodeInfo info, VideoFormat format, Quality quality, Standard standard) { try { if (!Supports(format)) { return(false); } string ext = System.IO.Path.GetExtension(info.file); if (ext.ToLowerInvariant() != ".ts" && ext.ToLowerInvariant() != ".mpg") { Log.Info("TSReader2WMV: wrong file format"); return(false); } Log.Info("TSReader2WMV: create graph"); graphBuilder = (IGraphBuilder) new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); Log.Info("TSReader2WMV: add filesource"); TsReader reader = new TsReader(); tsreaderSource = (IBaseFilter)reader; //ITSReader ireader = (ITSReader)reader; //ireader.SetTsReaderCallback(this); //ireader.SetRequestAudioChangeCallback(this); IBaseFilter filter = (IBaseFilter)tsreaderSource; graphBuilder.AddFilter(filter, "TSReader Source"); IFileSourceFilter fileSource = (IFileSourceFilter)tsreaderSource; Log.Info("TSReader2WMV: load file:{0}", info.file); int hr = fileSource.Load(info.file, null); //add audio/video codecs string strVideoCodec = ""; string strH264VideoCodec = ""; string strAudioCodec = ""; string strAACAudioCodec = ""; using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings()) { strVideoCodec = xmlreader.GetValueAsString("mytv", "videocodec", ""); strAudioCodec = xmlreader.GetValueAsString("mytv", "audiocodec", ""); strAACAudioCodec = xmlreader.GetValueAsString("mytv", "aacaudiocodec", ""); strH264VideoCodec = xmlreader.GetValueAsString("mytv", "h264videocodec", ""); } //Find the type of decoder required for the output video & audio pins on TSReader. Log.Info("TSReader2WMV: find tsreader compatible audio/video decoders"); IPin pinOut0, pinOut1; IPin pinIn0, pinIn1; pinOut0 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 0); //audio pinOut1 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 1); //video if (pinOut0 == null || pinOut1 == null) { Log.Error("TSReader2WMV: FAILED: unable to get output pins of tsreader"); Cleanup(); return(false); } bool usingAAC = false; IEnumMediaTypes enumMediaTypes; hr = pinOut0.EnumMediaTypes(out enumMediaTypes); while (true) { AMMediaType[] mediaTypes = new AMMediaType[1]; int typesFetched; hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched); if (hr != 0 || typesFetched == 0) { break; } if (mediaTypes[0].majorType == MediaType.Audio && mediaTypes[0].subType == MediaSubType.LATMAAC) { Log.Info("TSReader2WMV: found LATM AAC audio out pin on tsreader"); usingAAC = true; } } bool usingH264 = false; hr = pinOut1.EnumMediaTypes(out enumMediaTypes); while (true) { AMMediaType[] mediaTypes = new AMMediaType[1]; int typesFetched; hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched); if (hr != 0 || typesFetched == 0) { break; } if (mediaTypes[0].majorType == MediaType.Video && mediaTypes[0].subType == AVC1) { Log.Info("TSReader2WMV: found H.264 video out pin on tsreader"); usingH264 = true; } } //Add the type of decoder required for the output video & audio pins on TSReader. Log.Info("TSReader2WMV: add audio/video decoders to graph"); if (usingH264 == false) { Log.Info("TSReader2WMV: add mpeg2 video decoder:{0}", strVideoCodec); VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec); if (VideoCodec == null) { Log.Error("TSReader2WMV: unable to add mpeg2 video decoder"); Cleanup(); return(false); } } else { Log.Info("TSReader2WMV: add h264 video codec:{0}", strH264VideoCodec); VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strH264VideoCodec); if (VideoCodec == null) { Log.Error("TSReader2WMV: FAILED:unable to add h264 video codec"); Cleanup(); return(false); } } if (usingAAC == false) { Log.Info("TSReader2WMV: add mpeg2 audio codec:{0}", strAudioCodec); AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec); if (AudioCodec == null) { Log.Error("TSReader2WMV: FAILED:unable to add mpeg2 audio codec"); Cleanup(); return(false); } } else { Log.Info("TSReader2WMV: add aac audio codec:{0}", strAACAudioCodec); AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAACAudioCodec); if (AudioCodec == null) { Log.Error("TSReader2WMV: FAILED:unable to add aac audio codec"); Cleanup(); return(false); } } Log.Info("TSReader2WMV: connect tsreader->audio/video decoders"); //connect output #0 (audio) of tsreader->audio decoder input pin 0 //connect output #1 (video) of tsreader->video decoder input pin 0 pinIn0 = DsFindPin.ByDirection(AudioCodec, PinDirection.Input, 0); //audio pinIn1 = DsFindPin.ByDirection(VideoCodec, PinDirection.Input, 0); //video if (pinIn0 == null || pinIn1 == null) { Log.Error("TSReader2WMV: FAILED: unable to get pins of video/audio codecs"); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut0, pinIn0); if (hr != 0) { Log.Error("TSReader2WMV: FAILED: unable to connect audio pins :0x{0:X}", hr); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut1, pinIn1); if (hr != 0) { Log.Error("TSReader2WMV: FAILED: unable to connect video pins :0x{0:X}", hr); Cleanup(); return(false); } string outputFilename = System.IO.Path.ChangeExtension(info.file, ".wmv"); if (!AddWmAsfWriter(outputFilename, quality, standard)) { return(false); } Log.Info("TSReader2WMV: start pre-run"); mediaControl = graphBuilder as IMediaControl; mediaSeeking = tsreaderSource as IMediaSeeking; mediaEvt = graphBuilder as IMediaEventEx; mediaPos = graphBuilder as IMediaPosition; //get file duration long lTime = 5 * 60 * 60; lTime *= 10000000; long pStop = 0; hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); if (hr == 0) { long lStreamPos; mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position m_dDuration = lStreamPos; lTime = 0; mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); } double duration = m_dDuration / 10000000d; Log.Info("TSReader2WMV: movie duration:{0}", Util.Utils.SecondsToHMSString((int)duration)); hr = mediaControl.Run(); if (hr != 0) { Log.Error("TSReader2WMV: FAILED: unable to start graph :0x{0:X}", hr); Cleanup(); return(false); } int maxCount = 20; while (true) { long lCurrent; mediaSeeking.GetCurrentPosition(out lCurrent); double dpos = (double)lCurrent; dpos /= 10000000d; System.Threading.Thread.Sleep(100); if (dpos >= 2.0d) { break; } maxCount--; if (maxCount <= 0) { break; } } Log.Info("TSReader2WMV: pre-run done"); Log.Info("TSReader2WMV: Get duration of movie"); mediaControl.Stop(); FilterState state; mediaControl.GetState(500, out state); GC.Collect(); GC.Collect(); GC.Collect(); GC.WaitForPendingFinalizers(); Log.Info("TSReader2WMV: reconnect mpeg2 video codec->ASF WM Writer"); graphBuilder.RemoveFilter(fileWriterbase); if (!AddWmAsfWriter(outputFilename, quality, standard)) { return(false); } Log.Info("TSReader2WMV: Start transcoding"); hr = mediaControl.Run(); if (hr != 0) { Log.Error("TSReader2WMV:FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return(false); } } catch (Exception e) { // TODO: Handle exceptions. Log.Error("unable to transcode file:{0} message:{1}", info.file, e.Message); return(false); } return(true); }
static Cards() { // Fetch all cards. var cardLoader = new CardLoader(); Card[] cards = cardLoader.Load(); //string json = File.ReadAllText(CardLoader.Path + @"SabberStone\HSProtoSim\Loader\Data\cardData.json"); //string json = File.ReadAllText(Environment.CurrentDirectory + @"\cardData.json"); //var cards = JsonConvert.DeserializeObject<IEnumerable<Card>>(Resources.cardDataJson); //File.WriteAllText(CardLoader.Path + @"SabberStone\HSProtoSim\Loader\Data\cardDataJson.txt", JsonConvert.SerializeObject(cards, Formatting.Indented)); // Set as card definitions Data = new CardContainer(); Data.Load(cards); //Log.Debug("Standard:"); //Enum.GetValues(typeof(CardClass)).Cast<CardClass>().ToList().ForEach(heroClass => for (int i = 0; i < HeroClasses.Length; i++) { CardClass heroClass = HeroClasses[i]; Standard.Add(heroClass, All.Where(c => c.Collectible && (c.Class == heroClass || c.Class == CardClass.NEUTRAL && c.MultiClassGroup == 0 || c.MultiClassGroup == 1 && (c.Class == CardClass.NEUTRAL || c.Class == CardClass.HUNTER || c.Class == CardClass.PALADIN || c.Class == CardClass.WARRIOR) || c.MultiClassGroup == 2 && (c.Class == CardClass.NEUTRAL || c.Class == CardClass.DRUID || c.Class == CardClass.ROGUE || c.Class == CardClass.SHAMAN) || c.MultiClassGroup == 3 && (c.Class == CardClass.NEUTRAL || c.Class == CardClass.MAGE || c.Class == CardClass.PRIEST || c.Class == CardClass.WARLOCK)) && c.Type != CardType.HERO && StandardSets.Contains(c.Set)).ToList().AsReadOnly()); //Log.Debug($"-> [{heroClass}] - {Standard[heroClass].Count} cards."); //}); } //Log.Debug("AllStandard:"); AllStandard = All.Where(c => c.Collectible && c.Type != CardType.HERO && StandardSets.Contains(c.Set)).ToList().AsReadOnly(); //Log.Debug("Wild:"); Enum.GetValues(typeof(CardClass)).Cast <CardClass>().ToList().ForEach(heroClass => { Wild.Add(heroClass, All.Where(c => c.Collectible && (c.Class == heroClass || c.Class == CardClass.NEUTRAL && c.MultiClassGroup == 0 || c.MultiClassGroup == 1 && (c.Class == CardClass.NEUTRAL || c.Class == CardClass.HUNTER || c.Class == CardClass.PALADIN || c.Class == CardClass.WARRIOR) || c.MultiClassGroup == 2 && (c.Class == CardClass.NEUTRAL || c.Class == CardClass.DRUID || c.Class == CardClass.ROGUE || c.Class == CardClass.SHAMAN) || c.MultiClassGroup == 3 && (c.Class == CardClass.NEUTRAL || c.Class == CardClass.MAGE || c.Class == CardClass.PRIEST || c.Class == CardClass.WARLOCK)) && c.Type != CardType.HERO).ToList().AsReadOnly()); //Log.Debug($"-> [{heroClass}] - {Wild[heroClass].Count} cards."); }); //Log.Debug("AllWild:"); AllWild = All.Where(c => c.Collectible && c.Type != CardType.HERO).ToList().AsReadOnly(); StandardCostMinionCards = AllStandard.Where(c => c.Type == CardType.MINION).GroupBy(c => c.Cost).ToDictionary(g => g.Key, g => g.ToList()); WildCostMinionCards = AllWild.Where(c => c.Type == CardType.MINION).GroupBy(c => c.Cost).ToDictionary(g => g.Key, g => g.ToList()); // Temporary fix for Lotus Assassin Data.Cards["CFM_634"].Stealth = true; Data.Cards["CFM_634"].Tags.Add(GameTag.STEALTH, 1); // Basic Totems BasicTotems = new[] { FromId("NEW1_009"), // Healing Totem FromId("CS2_050"), // Searing Totem FromId("CS2_051"), // Stoneclaw Totem FromId("CS2_052") // Wraith of Air Totem }; }
public bool Transcode(TranscodeInfo info, VideoFormat format, Quality quality, Standard standard) { try { if (!Supports(format)) { return(false); } string ext = System.IO.Path.GetExtension(info.file); if (ext.ToLowerInvariant() != ".dvr-ms" && ext.ToLowerInvariant() != ".sbe") { Log.Info("DVRMS2WMV: wrong file format"); return(false); } Log.Info("DVRMS2WMV: create graph"); graphBuilder = (IGraphBuilder) new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); Log.Info("DVRMS2WMV: add streambuffersource"); bufferSource = (IStreamBufferSource) new StreamBufferSource(); IBaseFilter filter = (IBaseFilter)bufferSource; graphBuilder.AddFilter(filter, "SBE SOURCE"); Log.Info("DVRMS2WMV: load file:{0}", info.file); IFileSourceFilter fileSource = (IFileSourceFilter)bufferSource; int hr = fileSource.Load(info.file, null); //add mpeg2 audio/video codecs string strVideoCodec = ""; string strAudioCodec = ""; using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings()) { strVideoCodec = xmlreader.GetValueAsString("mytv", "videocodec", "MPC - MPEG-2 Video Decoder (Gabest)"); strAudioCodec = xmlreader.GetValueAsString("mytv", "audiocodec", "MPC - MPA Decoder Filter"); } Log.Info("DVRMS2WMV: add mpeg2 video codec:{0}", strVideoCodec); Mpeg2VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:Add mpeg2 video to filtergraph :0x{0:X}", hr); Cleanup(); return(false); } Log.Info("DVRMS2WMV: add mpeg2 audio codec:{0}", strAudioCodec); Mpeg2AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec); if (Mpeg2AudioCodec == null) { Log.Error("DVRMS2WMV:FAILED:unable to add mpeg2 audio codec"); Cleanup(); return(false); } Log.Info("DVRMS2WMV: connect streambufer source->mpeg audio/video decoders"); //connect output #0 of streambuffer source->mpeg2 audio codec pin 1 //connect output #1 of streambuffer source->mpeg2 video codec pin 1 IPin pinOut0, pinOut1; IPin pinIn0, pinIn1; pinOut0 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 0); //audio pinOut1 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 1); //video if (pinOut0 == null || pinOut1 == null) { Log.Error("DVRMS2WMV:FAILED:unable to get pins of source"); Cleanup(); return(false); } pinIn0 = DsFindPin.ByDirection(Mpeg2VideoCodec, PinDirection.Input, 0); //video pinIn1 = DsFindPin.ByDirection(Mpeg2AudioCodec, PinDirection.Input, 0); //audio if (pinIn0 == null || pinIn1 == null) { Log.Error("DVRMS2WMV:FAILED:unable to get pins of mpeg2 video/audio codec"); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut0, pinIn1); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to connect audio pins :0x{0:X}", hr); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut1, pinIn0); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to connect video pins :0x{0:X}", hr); Cleanup(); return(false); } string outputFilename = System.IO.Path.ChangeExtension(info.file, ".wmv"); if (!AddWmAsfWriter(outputFilename, quality, standard)) { return(false); } Log.Info("DVRMS2WMV: start pre-run"); mediaControl = graphBuilder as IMediaControl; mediaSeeking = bufferSource as IStreamBufferMediaSeeking; mediaEvt = graphBuilder as IMediaEventEx; mediaPos = graphBuilder as IMediaPosition; //get file duration long lTime = 5 * 60 * 60; lTime *= 10000000; long pStop = 0; hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); if (hr == 0) { long lStreamPos; mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position m_dDuration = lStreamPos; lTime = 0; mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); } double duration = m_dDuration / 10000000d; Log.Info("DVRMS2WMV: movie duration:{0}", Util.Utils.SecondsToHMSString((int)duration)); hr = mediaControl.Run(); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return(false); } int maxCount = 20; while (true) { long lCurrent; mediaSeeking.GetCurrentPosition(out lCurrent); double dpos = (double)lCurrent; dpos /= 10000000d; System.Threading.Thread.Sleep(100); if (dpos >= 2.0d) { break; } maxCount--; if (maxCount <= 0) { break; } } Log.Info("DVRMS2WMV: pre-run done"); Log.Info("DVRMS2WMV: Get duration of movie"); mediaControl.Stop(); FilterState state; mediaControl.GetState(500, out state); GC.Collect(); GC.Collect(); GC.Collect(); GC.WaitForPendingFinalizers(); Log.Info("DVRMS2WMV: reconnect mpeg2 video codec->ASF WM Writer"); graphBuilder.RemoveFilter(fileWriterbase); if (!AddWmAsfWriter(outputFilename, quality, standard)) { return(false); } Log.Info("DVRMS2WMV: Start transcoding"); hr = mediaControl.Run(); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return(false); } } catch (Exception e) { // TODO: Handle exceptions. Log.Error("unable to transcode file:{0} message:{1}", info.file, e.Message); return(false); } return(true); }
public ActionResult Edit(Standard standard) { if (ModelState.IsValid) { db.Entry(standard).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.Header_Id = new SelectList(db.Headers, "Id", "Header1", standard.Header_Id); return View(standard); }
private bool AddWmAsfWriter(string fileName, Quality quality, Standard standard) { //add asf file writer IPin pinOut0, pinOut1; IPin pinIn0, pinIn1; Log.Info("DVRMS2WMV: add WM ASF Writer to graph"); string monikerAsfWriter = @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{7C23220E-55BB-11D3-8B16-00C04FB6BD3D}"; fileWriterbase = Marshal.BindToMoniker(monikerAsfWriter) as IBaseFilter; if (fileWriterbase == null) { Log.Error("DVRMS2WMV:FAILED:Unable to create ASF WM Writer"); Cleanup(); return(false); } int hr = graphBuilder.AddFilter(fileWriterbase, "WM ASF Writer"); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:Add ASF WM Writer to filtergraph :0x{0:X}", hr); Cleanup(); return(false); } IFileSinkFilter2 fileWriterFilter = fileWriterbase as IFileSinkFilter2; if (fileWriterFilter == null) { Log.Error("DVR2XVID:FAILED:Add unable to get IFileSinkFilter for filewriter"); Cleanup(); return(false); } hr = fileWriterFilter.SetFileName(fileName, null); hr = fileWriterFilter.SetMode(AMFileSinkFlags.OverWrite); Log.Info("DVRMS2WMV: connect audio/video codecs outputs -> ASF WM Writer"); //connect output #0 of videocodec->asf writer pin 1 //connect output #0 of audiocodec->asf writer pin 0 pinOut0 = DsFindPin.ByDirection((IBaseFilter)Mpeg2AudioCodec, PinDirection.Output, 0); pinOut1 = DsFindPin.ByDirection((IBaseFilter)Mpeg2VideoCodec, PinDirection.Output, 0); if (pinOut0 == null || pinOut1 == null) { Log.Error("DVRMS2WMV:FAILED:unable to get outpins of video codec"); Cleanup(); return(false); } pinIn0 = DsFindPin.ByDirection(fileWriterbase, PinDirection.Input, 0); if (pinIn0 == null) { Log.Error("DVRMS2WMV:FAILED:unable to get pins of asf wm writer"); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut0, pinIn0); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to connect audio pins :0x{0:X}", hr); Cleanup(); return(false); } pinIn1 = DsFindPin.ByDirection(fileWriterbase, PinDirection.Input, 1); if (pinIn1 == null) { Log.Error("DVRMS2WMV:FAILED:unable to get pins of asf wm writer"); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut1, pinIn1); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to connect video pins :0x{0:X}", hr); Cleanup(); return(false); } IConfigAsfWriter config = fileWriterbase as IConfigAsfWriter; IWMProfileManager profileManager = null; IWMProfileManager2 profileManager2 = null; IWMProfile profile = null; hr = WMLib.WMCreateProfileManager(out profileManager); string strprofileType = ""; switch (quality) { case Quality.HiDef: //hr = WMLib.WMCreateProfileManager(out profileManager); if (standard == Standard.Film) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHiDef-FILM.prx"); } if (standard == Standard.NTSC) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHiDef-NTSC.prx"); } if (standard == Standard.PAL) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHiDef-PAL.prx"); } Log.Info("DVRMS2WMV: set WMV HiDef quality profile {0}", strprofileType); break; case Quality.VeryHigh: if (standard == Standard.Film) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPVeryHigh-FILM.prx"); } if (standard == Standard.NTSC) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPVeryHigh-NTSC.prx"); } if (standard == Standard.PAL) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPVeryHigh-PAL.prx"); } Log.Info("DVRMS2WMV: set WMV Very High quality profile {0}", strprofileType); break; case Quality.High: if (standard == Standard.Film) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHigh-FILM.prx"); } if (standard == Standard.NTSC) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHigh-NTSC.prx"); } if (standard == Standard.PAL) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHigh-PAL.prx"); } Log.Info("DVRMS2WMV: set WMV High quality profile {0}", strprofileType); break; case Quality.Medium: if (standard == Standard.Film) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPMedium-FILM.prx"); } if (standard == Standard.NTSC) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPMedium-NTSC.prx"); } if (standard == Standard.PAL) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPMedium-PAL.prx"); } Log.Info("DVRMS2WMV: set WMV Medium quality profile {0}", strprofileType); break; case Quality.Low: if (standard == Standard.Film) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPLow-FILM.prx"); } if (standard == Standard.NTSC) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPLow-NTSC.prx"); } if (standard == Standard.PAL) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPLow-PAL.prx"); } Log.Info("DVRMS2WMV: set WMV Low quality profile {0}", strprofileType); break; case Quality.Portable: if (standard == Standard.Film) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPPortable-FILM.prx"); } if (standard == Standard.NTSC) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPPortable-NTSC.prx"); } if (standard == Standard.PAL) { strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPPortable-PAL.prx"); } Log.Info("DVRMS2WMV: set WMV Portable quality profile {0}", strprofileType); break; case Quality.Custom: //load custom profile string customBitrate = ""; //Adjust the parameters to suit the custom settings the user has selected. switch (bitrate) { case 0: customBitrate = "100Kbs"; break; case 1: customBitrate = "256Kbs"; break; case 2: customBitrate = "384Kbs"; break; case 3: customBitrate = "768Kbs"; break; case 4: customBitrate = "1536Kbs"; break; case 5: customBitrate = "3072Kbs"; break; case 6: customBitrate = "5376Kbs"; break; } Log.Info("DVRMS2WMV: custom bitrate = {0}", customBitrate); //TODO: get fps values & frame size //TODO: adjust settings required //Call the SetCutomPorfile method to load the custom profile, adjust it's params from user settings & then save it. //SetCutomProfile(videoBitrate, audioBitrate, videoHeight, videoWidth, videoFps); //based on user inputs //We then reload it after as per other quality settings / profiles. strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPCustom.prx"); Log.Info("DVRMS2WMV: set WMV Custom quality profile {0}", strprofileType); break; } //Loads profile from the above quality selection. using (StreamReader prx = new StreamReader(strprofileType)) { String profileContents = prx.ReadToEnd(); profileManager2 = profileManager as IWMProfileManager2; hr = profileManager2.LoadProfileByData(profileContents, out profile); if (hr != 0) { Log.Info("DVRMS2WMV: get WMV profile - FAILED! {0}", hr); Cleanup(); return(false); } } Log.Info("DVRMS2WMV: load profile - SUCCESS!"); //configures the WM ASF Writer to the chosen profile hr = config.ConfigureFilterUsingProfile(profile); if (hr != 0) { Log.Info("DVRMS2WMV: configure profile - FAILED! {0}", hr); Cleanup(); return(false); } Log.Info("DVRMS2WMV: configure profile - SUCCESS!"); //TODO: Add DB recording information into WMV. //Release resorces if (profile != null) { Marshal.ReleaseComObject(profile); profile = null; } if (profileManager != null) { Marshal.ReleaseComObject(profileManager); profileManager = null; } return(true); }
public static StandardEntity ToStandardEntity(this Standard standard) => new StandardEntity(standard.name, standard.pollutant, standard.limit, standard.percent);
public void addStandard(Standard Standard) { _standardRepository.Insert(Standard); }
public Standard Create(Standard standard) { _validator.ValidateAndThrow(standard, ruleSet: nameof(IStandardLogic.Create)); return(_datastore.Create(standard)); }
public void updateStandard(Standard Standard) { _standardRepository.Update(Standard); }
public void AddStandard() { mStandard = new Standard(); Debug.Log("Standard transmission detected"); }
/// <summary> /// 作用:保存标准 /// 作者:汪建龙 /// 编写时间:2017年3月6日17:08:54 /// </summary> /// <param name="standard"></param> /// <returns></returns> public int Save(Standard standard) { Db.Standards.Add(standard); Db.SaveChanges(); return(standard.ID); }
/// <summary> /// Import server settings and COSEM objects from GXDLMSDirector trace. /// </summary> /// <param name="server">Server where settings are updated.</param> /// <param name="data">GXDLMSDirector trace in byte array.</param> public static void Import(GXDLMSServer server, byte[] data, Standard standard) { GXDLMSTranslator translator = new GXDLMSTranslator(TranslatorOutputType.StandardXml); translator.CompletePdu = true; translator.PduOnly = true; translator.OmitXmlNameSpace = translator.OmitXmlDeclaration = true; XmlDocument doc = new XmlDocument(); List <ValueEventArgs> targets = new List <ValueEventArgs>(); GXDLMSSettings settings = new GXDLMSSettings(true, InterfaceType.HDLC); GXByteBuffer pdu = new GXByteBuffer(); GXByteBuffer bb = new GXByteBuffer(data); server.InterfaceType = GXDLMSTranslator.GetDlmsFraming(bb); bool lastBlock = true; GXByteBuffer val = new DLMS.GXByteBuffer(); GXDLMSConverter converter = new GXDLMSConverter(standard); while (translator.FindNextFrame(bb, pdu, server.InterfaceType)) { String xml = translator.MessageToXml(bb); if (xml != "") { doc.LoadXml(xml.Replace("&", "&")); foreach (XmlNode node in doc.ChildNodes[doc.ChildNodes.Count - 1].ChildNodes) { string name = doc.ChildNodes[doc.ChildNodes.Count - 1].Name; if (name == "Ua" || name == "aarq" || name == "aare") { break; } else if (name == "get-request") { server.UseLogicalNameReferencing = true; GetLN(settings.Objects, targets, node.ChildNodes); } else if (name == "readRequest") { List <short> items = GetSN(node.ChildNodes); server.UseLogicalNameReferencing = false; foreach (short it in items) { GXSNInfo i = GXDLMSSNCommandHandler.FindSNObject(settings.Objects, Convert.ToUInt16((it) & 0xFFFF)); targets.Add(new ValueEventArgs(i.Item, i.Index, 0, null)); } } else if (name == "readResponse" || name == "get-response") { if (targets != null) { List <string> items; if (server.UseLogicalNameReferencing) { items = GetLNValues(doc.ChildNodes[doc.ChildNodes.Count - 1].ChildNodes); } else { items = GetSNValues(doc.ChildNodes[doc.ChildNodes.Count - 1].ChildNodes); } int pos = 0; foreach (string it in items) { if ("other-reason".Equals(it) || "read-write-denied".Equals(it) || "scope-of-access-violated".Equals(it) || "object-unavailable".Equals(it) || "object-class-inconsistent".Equals(it)) { ValueEventArgs ve = targets[pos]; ve.Target.SetAccess(ve.Index, AccessMode.NoAccess); continue; } try { if (server.UseLogicalNameReferencing) { lastBlock = IsLastBlock(doc.ChildNodes[doc.ChildNodes.Count - 1].ChildNodes); } val.Set(translator.XmlToData(it)); if (lastBlock) { if (settings.Objects.Count == 0) { GXDLMSClient c = new GXDLMSClient(); c.UseLogicalNameReferencing = server.UseLogicalNameReferencing; settings.Objects = c.ParseObjects(val, true); //Update OBIS code description. converter.UpdateOBISCodeInformation(settings.Objects); } else if (targets.Count != 0) { ValueEventArgs ve = targets[pos]; GXDataInfo info = new GXDataInfo(); ve.Value = GXCommon.GetData(server.Settings, val, info); if (ve.Value is byte[] && ve.Target != null) { DataType tp = ve.Target.GetUIDataType(ve.Index); if (tp != DataType.None) { ve.Value = GXDLMSClient.ChangeType((byte[])ve.Value, tp, false); ve.Target.SetDataType(ve.Index, DataType.OctetString); } } if (ve.Target is IGXDLMSBase) { ((IGXDLMSBase)ve.Target).SetValue(settings, ve); } } val.Clear(); } } catch (Exception) { ValueEventArgs ve = targets[pos]; ve.Target.SetAccess(ve.Index, AccessMode.NoAccess); } ++pos; } if (lastBlock) { targets.Clear(); break; } } } } } } server.Items.Clear(); server.Items.AddRange(settings.Objects); }
public void TestConstructor() { IGame game = new Standard <Classical>(); AssertGame(game, 0, 20, 0, true, Outcome.Game); }
/// <summary> /// Constructor. /// </summary> public GXDLMSConverter(Standard standard) { Standard = standard; }
public void TestGame() { // Set a new standard game of classical chess. IGame game = new Standard <Classical>(); // Load game data var gameData = TestClassical.GameOfChessData; // Initialize assertion metrics int loop = 0; int score = 0; bool player = true; int moves = 0; Outcome outcome = Outcome.Game; int counter = 0; // Play the game Assert.All(gameData, tuple => { // Assert conditions AssertGame(game, score, game.AvailableMoves().Count, moves, player, outcome); // Get move data var move = tuple.Item1; var numberOfPieces = tuple.Item4; var captured = tuple.Item3; // Process move Assert.True(game.ProcessMove(move)); // Post-move assertions Assert.Equal(32, game.Position.Count + game.CapturedPieces.Count); Assert.Equal(numberOfPieces, game.Position.Count); // Update assertion metrics switch (captured) { case Pawn p: score += (captured.Color ? -1 : +1) * 1; break; case Knight n: case Bishop b: score += (captured.Color ? -1 : +1) * 3; break; case Rook r: score += (captured.Color ? -1 : +1) * 5; break; case Queen q: score += (captured.Color ? -1 : +1) * 9; break; default: break; } player = !player; if (!player) { moves++; } if (game.AvailableMoves().Count == 0) { outcome = Outcome.Checkmate; } else { outcome = Outcome.Game; } loop++; if (loop == 5 || loop == 19 || loop == 25) { outcome = Outcome.Checked; } }); // Post-game assertions AssertGame(game, -17, 0, 17, true, outcome); Assert.Equal(Outcome.Checkmate, outcome); // Assert game.Moves Assert.Equal((int)moves, game.Moves.Count); Assert.All(game.Moves, moves => { // Every player played each move Assert.Equal(2, moves.Count); Assert.All(moves, move => { // Assert every move var moveEntry = game.MoveEntries.ElementAt(counter); Assert.Equal(moveEntry.Move, move); Assert.Equal(player, moveEntry.Position[move.FromSquare].Color); // Update assertion metrics counter++; player = !player; }); }); }
public void AddStandard(Standard standard) { _standardRepository.Insert(standard); }
//order approving, focusingonSelf, {subject} public void AddStandard(float weight, bool approving, params object[] values) { Standard s = new Standard(); s.weight = weight; s.approving = approving; if(values.Length < 1) { Debug.Log ("Missing parameter in AddStandard"); return; } s.focusingOnSelf = (bool)values[0]; if(values[0].Equals(AppDef.FocusingOnOther)) { if(values.Length < 1) { Debug.Log ("Missing parameter \"subject\" in AddStandard"); return; } else { s.subject = (GameObject)values[1]; } } standards.Add (s); }
public void RemoveStandard(Standard standard) { _standardRepository.Delete(standard); }
/// <summary> /// changes the type of paper /// </summary> /// <param name="s">Papersize to set to</param> public static void SetType(Standard s) { type = s; switch (s) { case Standard.A4: bleedWidth = 216; bleedHeight = 303; unsafeHeight = 297; unsafeWidth = 210; safeHeight = 282; safeWidth = 187; paperWidth = 297; paperHeight = 420; break; default: break; } }
/// <summary> /// Returns the best formatted string representation of a byte value /// </summary> /// <param name="bytes">number of bytes</param> /// <param name="st"></param> /// <returns>formatted string</returns> private static string ToString(long bytes, Standard st = Standard.Iec) { return(ToString(bytes, st, null)); }
public ObjRef(Guid guid, Standard standardObjRef) { Guid = guid; StandardObjRef = standardObjRef; }
float weight = 0.5f; //default #endregion Fields #region Methods public override void OnInspectorGUI() { //Add new goals Goal gl = new Goal(); GUILayout.Label("Goals", EditorStyles.boldLabel); EditorGUILayout.BeginHorizontal(); pleased = EditorGUILayout.Toggle("Pleased", pleased); gl.pleased = pleased; conseqForSelf = EditorGUILayout.Toggle("ConsequenceForSelf", conseqForSelf, GUILayout.ExpandWidth(true)); gl.consequenceForSelf = conseqForSelf; if(conseqForSelf == false) { desirable = EditorGUILayout.Toggle("DesirableForOther", desirable, GUILayout.ExpandWidth(true)); gl.desirableForOther = desirable; } else { prospectRel = EditorGUILayout.Toggle("ProspectRelevant", prospectRel, GUILayout.ExpandWidth(true)); gl.prospectRelevant = prospectRel; gl.confirmed = AppDef.Unconfirmed; } EditorGUILayout.EndHorizontal(); weight = EditorGUILayout.Slider ("weight", weight, 0f, 1f, GUILayout.ExpandWidth(true)); gl.weight = weight; if(GUILayout.Button("Add Goal", GUILayout.ExpandWidth(false))) appraisal.goals.Add(gl); if(appraisal.goals.Count > 0) { EditorGUILayout.Separator(); GUI.contentColor = Color.yellow; GUILayout.Label("Current goals", EditorStyles.boldLabel); checkAllGoals = EditorGUILayout.Toggle("Check all", checkAllGoals); } foreach(Goal g in appraisal.goals) { EditorGUILayout.BeginHorizontal(); g.selected= EditorGUILayout.Toggle(g.selected, GUILayout.ExpandWidth(false)); if(g.pleased) GUILayout.Label ("Pleased"); else GUILayout.Label ("Displeased"); if(g.consequenceForSelf) { GUILayout.Label ("ConsequenceForSelf"); if(g.prospectRelevant) { GUILayout.Label ("ProspectRelevant"); if(g.confirmed == AppDef.Confirmed) GUILayout.Label ("Confirmed"); else if(g.confirmed == AppDef.Disconfirmed) GUILayout.Label ("Disconfirmed"); else GUILayout.Label ("Unconfirmed"); } else GUILayout.Label ("ProspectIrrelevant"); } else { GUILayout.Label ("ConsequenceForOther"); if(g.desirableForOther) GUILayout.Label ("Desirable"); else GUILayout.Label ("Unesirable"); } GUILayout.Label ("weight: " + g.weight); EditorGUILayout.EndHorizontal (); } if(checkAllGoals) foreach(Goal g in appraisal.goals) g.selected = true; if(appraisal.goals.Count > 0) { EditorGUILayout.Separator(); if(GUILayout.Button("RemoveChecked", GUILayout.ExpandWidth(false))) { int i = 0; while(i < appraisal.goals.Count) { if(appraisal.goals[i].selected){ appraisal.goals.Remove(appraisal.goals[i]); } else i++; } } } EditorGUILayout.Separator(); EditorGUILayout.Separator(); GUI.contentColor = Color.white; GUILayout.Label("Standards", EditorStyles.boldLabel); Standard st = new Standard(); EditorGUILayout.BeginHorizontal(); approving = EditorGUILayout.Toggle("Approving", approving); st.approving = approving; focOnSelf = EditorGUILayout.Toggle("Focusing on Self", focOnSelf, GUILayout.ExpandWidth(true)); st.focusingOnSelf = focOnSelf; EditorGUILayout.EndHorizontal(); weight = EditorGUILayout.Slider ("weight", weight, 0f, 1f, GUILayout.ExpandWidth(true)); st.weight = weight; if(GUILayout.Button("Add Standard", GUILayout.ExpandWidth(false))) appraisal.standards.Add(st); if(appraisal.standards.Count > 0) { EditorGUILayout.Separator(); GUI.contentColor = Color.yellow; GUILayout.Label("Current standards", EditorStyles.boldLabel); checkAllStandards = EditorGUILayout.Toggle("Check all", checkAllStandards); } foreach(Standard s in appraisal.standards) { EditorGUILayout.BeginHorizontal(); s.selected= EditorGUILayout.Toggle(s.selected, GUILayout.ExpandWidth(false)); if(s.approving) GUILayout.Label ("Approving"); else GUILayout.Label ("Disapproving"); if(s.focusingOnSelf) GUILayout.Label ("FocusingOnSelf"); else GUILayout.Label ("FocusingOnOther"); GUILayout.Label ("weight: " + s.weight); EditorGUILayout.EndHorizontal (); } if(checkAllStandards) foreach(Standard s in appraisal.standards) s.selected = true; if(appraisal.standards.Count > 0) { EditorGUILayout.Separator(); if(GUILayout.Button("RemoveChecked", GUILayout.ExpandWidth(false))) { int i = 0; while(i < appraisal.standards.Count) { if(appraisal.standards[i].selected){ appraisal.standards.Remove(appraisal.standards[i]); } else i++; } } } EditorGUILayout.Separator(); EditorGUILayout.Separator(); GUI.contentColor = Color.white; GUILayout.Label("Attitudes", EditorStyles.boldLabel); Attitude at = new Attitude(); EditorGUILayout.BeginHorizontal(); liking = EditorGUILayout.Toggle("Liking", liking); at.liking = liking; EditorGUILayout.EndHorizontal(); weight = EditorGUILayout.Slider ("weight", weight, 0f, 1f, GUILayout.ExpandWidth(true)); at.weight = weight; if(GUILayout.Button("Add Attitude", GUILayout.ExpandWidth(false))) appraisal.attitudes.Add(at); EditorGUILayout.Separator(); if(appraisal.attitudes.Count > 0) { EditorGUILayout.Separator(); GUI.contentColor = Color.yellow; GUILayout.Label("Current attitudes", EditorStyles.boldLabel); checkAllAttitudes = EditorGUILayout.Toggle("Check all", checkAllAttitudes); } foreach(Attitude a in appraisal.attitudes) { EditorGUILayout.BeginHorizontal(); a.selected= EditorGUILayout.Toggle(a.selected, GUILayout.ExpandWidth(false)); if(a.liking) GUILayout.Label ("Liking"); else GUILayout.Label ("Disliking"); GUILayout.Label ("weight: " + a.weight); EditorGUILayout.EndHorizontal (); } if(checkAllAttitudes) foreach(Attitude a in appraisal.attitudes) a.selected = true; GUI.contentColor = Color.white; if(appraisal.attitudes.Count > 0) { EditorGUILayout.Separator(); if(GUILayout.Button("RemoveChecked", GUILayout.ExpandWidth(false))) { int i = 0; while(i < appraisal.attitudes.Count) { if(appraisal.attitudes[i].selected){ appraisal.attitudes.Remove(appraisal.attitudes[i]); } else i++; } } } EditorUtility.SetDirty (target); }
public bool Transcode(TranscodeInfo info, MediaPortal.Core.Transcoding.VideoFormat format, MediaPortal.Core.Transcoding.Quality quality, Standard standard) { if (!Supports(format)) { return(false); } string ext = System.IO.Path.GetExtension(info.file); if (ext.ToLower() != ".dvr-ms" && ext.ToLower() != ".sbe") { Log.Info("DVRMS2DIVX: wrong file format"); return(false); } //disable xvid status window while encoding /* try * { * using (RegistryKey subkey = Registry.CurrentUser.OpenSubKey(@"Software\GNU\XviD", true)) * { * if (subkey != null) * { * Int32 uivalue = 0; * subkey.SetValue("display_status", (Int32)uivalue); * subkey.SetValue("debug", (Int32)uivalue); * subkey.SetValue("bitrate", (Int32)bitrate); * * uivalue = 1; * subkey.SetValue("interlacing", (Int32)uivalue); * } * } * } * catch (Exception) * { * }*/ //Type comtype = null; //object comobj = null; try { graphBuilder = (IGraphBuilder) new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); Log.Info("DVRMS2DIVX: add filesource"); bufferSource = (IStreamBufferSource) new StreamBufferSource(); IBaseFilter filter = (IBaseFilter)bufferSource; graphBuilder.AddFilter(filter, "SBE SOURCE"); IFileSourceFilter fileSource = (IFileSourceFilter)bufferSource; Log.Info("DVRMS2DIVX: load file:{0}", info.file); int hr = fileSource.Load(info.file, null); /*string strDemuxerMoniker = @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{AFB6C280-2C41-11D3-8A60-0000F81E0E4A}"; * * mpegDemuxer = Marshal.BindToMoniker(strDemuxerMoniker) as IBaseFilter; * if (mpegDemuxer == null) * { * Log.Error("DVRMS2DIVX:FAILED:unable to add mpeg2 demuxer"); * Cleanup(); * return false; * } * hr = graphBuilder.AddFilter(mpegDemuxer, "MPEG-2 Demultiplexer"); * if (hr != 0) * { * Log.Error("DVRMS2DIVX:FAILED:Add mpeg2 demuxer to filtergraph :0x{0:X}", hr); * Cleanup(); * return false; * }*/ //add mpeg2 audio/video codecs string strVideoCodecMoniker = @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{39F498AF-1A09-4275-B193-673B0BA3D478}"; string strAudioCodec = "MPC - MPA Decoder Filter"; Log.Info("DVRMS2DIVX: add MPV mpeg2 video decoder"); Mpeg2VideoCodec = Marshal.BindToMoniker(strVideoCodecMoniker) as IBaseFilter; if (Mpeg2VideoCodec == null) { Log.Error("DVRMS2DIVX:FAILED:unable to add MPV mpeg2 video decoder"); Cleanup(); return(false); } hr = graphBuilder.AddFilter(Mpeg2VideoCodec, "MPC - MPEG-2 Video Decoder (Gabest)"); if (hr != 0) { Log.Error("DVRMS2DIVX:FAILED:Add MPV mpeg2 video to filtergraph :0x{0:X}", hr); Cleanup(); return(false); } Log.Info("DVRMS2DIVX: add MPA mpeg2 audio codec:{0}", strAudioCodec); Mpeg2AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec); if (Mpeg2AudioCodec == null) { Log.Error("DVRMS2DIVX:FAILED:unable to add MPV mpeg2 audio codec"); Cleanup(); return(false); } //connect output #0 of streambuffer source->mpeg2 audio codec pin 1 //connect output #1 of streambuffer source->mpeg2 video codec pin 1 Log.Info("DVRMS2DIVX: connect streambufer source->mpeg audio/video decoders"); IPin pinOut0, pinOut1; IPin pinIn0, pinIn1; pinOut0 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 0); //audio pinOut1 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 1); //video if (pinOut0 == null || pinOut1 == null) { Log.Error("DVRMS2DIVX:FAILED:unable to get pins of source"); Cleanup(); return(false); } pinIn0 = DsFindPin.ByDirection(Mpeg2VideoCodec, PinDirection.Input, 0); //video pinIn1 = DsFindPin.ByDirection(Mpeg2AudioCodec, PinDirection.Input, 0); //audio if (pinIn0 == null || pinIn1 == null) { Log.Error("DVRMS2DIVX:FAILED:unable to get pins of mpeg2 video/audio codec"); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut0, pinIn1); if (hr != 0) { Log.Error("DVRMS2DIVX:FAILED:unable to connect audio pins :0x{0:X}", hr); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut1, pinIn0); if (hr != 0) { Log.Error("DVRMS2DIVX:FAILED:unable to connect video pins :0x{0:X}", hr); Cleanup(); return(false); } if (!AddCodecs(graphBuilder, info)) { return(false); } // hr=(graphBuilder as IMediaFilter).SetSyncSource(null); // if (hr!=0) // Log.Error("DVRMS2DIVX:FAILED:to SetSyncSource :0x{0:X}",hr); mediaControl = graphBuilder as IMediaControl; mediaSeeking = bufferSource as IStreamBufferMediaSeeking; mediaEvt = graphBuilder as IMediaEventEx; mediaPos = graphBuilder as IMediaPosition; //get file duration Log.Info("DVRMS2DIVX: Get duration of movie"); long lTime = 5 * 60 * 60; lTime *= 10000000; long pStop = 0; hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); if (hr == 0) { long lStreamPos; mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position m_dDuration = lStreamPos; lTime = 0; mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); } double duration = m_dDuration / 10000000d; Log.Info("DVRMS2DIVX: movie duration:{0}", MediaPortal.Util.Utils.SecondsToHMSString((int)duration)); // hr=(graphBuilder as IMediaFilter).SetSyncSource(null); // if (hr!=0) // Log.Error("DVRMS2DIVX:FAILED:to SetSyncSource :0x{0:X}",hr); hr = mediaControl.Run(); if (hr != 0) { Log.Error("DVRMS2DIVX:FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return(false); } int maxCount = 20; while (true) { long lCurrent; mediaSeeking.GetCurrentPosition(out lCurrent); double dpos = (double)lCurrent; dpos /= 10000000d; System.Threading.Thread.Sleep(100); if (dpos >= 2.0d) { break; } maxCount--; if (maxCount <= 0) { break; } } mediaControl.Stop(); FilterState state; mediaControl.GetState(500, out state); GC.Collect(); GC.Collect(); GC.Collect(); GC.WaitForPendingFinalizers(); graphBuilder.RemoveFilter(aviMuxer); graphBuilder.RemoveFilter(divxCodec); graphBuilder.RemoveFilter(mp3Codec); graphBuilder.RemoveFilter((IBaseFilter)fileWriterFilter); if (!AddCodecs(graphBuilder, info)) { return(false); } // hr=(graphBuilder as IMediaFilter).SetSyncSource(null); // if (hr!=0) // Log.Error("DVRMS2DIVX:FAILED:to SetSyncSource :0x{0:X}",hr); Log.Info("DVRMS2DIVX: start transcoding"); hr = mediaControl.Run(); if (hr != 0) { Log.Error("DVRMS2DIVX:FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return(false); } } catch (Exception ex) { Log.Error("DVRMS2DIVX:Unable create graph: {0}", ex.Message); Cleanup(); return(false); } return(true); }
private OperationReturn LoadScoreItem(SessionInfo session, ScoreItem parent, string scoreID) { OperationReturn optReturn = new OperationReturn(); optReturn.Result = true; optReturn.Code = 0; try { string rentToken = session.RentInfo.Token; ScoreSheet scoreSheet = parent.ScoreSheet; if (scoreSheet == null) { optReturn.Result = false; optReturn.Code = Defines.RET_OBJECT_NULL; optReturn.Message = string.Format("ScoreSheet is null"); return(optReturn); } string temp1 = string.Empty; string temp2 = string.Empty; if (!string.IsNullOrWhiteSpace(scoreID)) { temp1 = string.Format(",T3109.C005 AS NA"); temp2 = string.Format(" LEFT JOIN T_31_009_{0} T3109 ON T3102.C002=T3109.C002", rentToken); } string strSql; DataSet objDataSet; switch (session.DBType) { case 2: strSql = string.Format( "SELECT T3102.*{4} FROM T_31_002_{0} T3102{5} WHERE T3102.C003 = {1} AND T3102.C004 = {2}{3} ", rentToken, scoreSheet.ID, parent.ID, scoreID, temp1, temp2); optReturn = MssqlOperation.GetDataSet(session.DBConnectionString, strSql); if (!optReturn.Result) { return(optReturn); } objDataSet = optReturn.Data as DataSet; break; case 3: strSql = string.Format( "SELECT T3102.*{4} FROM T_31_002_{0} T3102{5} WHERE T3102.C003 = {1} AND T3102.C004 = {2}{3} ", rentToken, scoreSheet.ID, parent.ID, scoreID, temp1, temp2); optReturn = OracleOperation.GetDataSet(session.DBConnectionString, strSql); if (!optReturn.Result) { return(optReturn); } objDataSet = optReturn.Data as DataSet; break; default: optReturn.Result = false; optReturn.Code = Defines.RET_PARAM_INVALID; optReturn.Message = string.Format("DBType invalid"); return(optReturn); } if (objDataSet == null || objDataSet.Tables.Count <= 0) { optReturn.Result = false; optReturn.Code = Defines.RET_OBJECT_NULL; optReturn.Message = string.Format("DataSet is null or DataTables empty"); return(optReturn); } List <ScoreItem> listItems = new List <ScoreItem>(); for (int i = 0; i < objDataSet.Tables[0].Rows.Count; i++) { DataRow dr = objDataSet.Tables[0].Rows[i]; ScoreItem scoreItem; bool isStandard = dr["C009"].ToString() == "Y"; if (isStandard) { Standard standard = null; StandardType standardType = (StandardType)Convert.ToInt32(dr["C015"]); switch (standardType) { case StandardType.Numeric: NumericStandard numericStandard = new NumericStandard(); numericStandard.Type = ScoreObjectType.NumericStandard; numericStandard.MaxValue = Convert.ToDouble(dr["C027"]); numericStandard.MinValue = Convert.ToDouble(dr["C028"]); numericStandard.DefaultValue = string.IsNullOrWhiteSpace(dr["C029"].ToString()) ? 0 : Convert.ToDouble(dr["C029"]); numericStandard.ScoreClassic = StandardClassic.TextBox; standard = numericStandard; break; case StandardType.YesNo: YesNoStandard yesNoStandard = new YesNoStandard(); yesNoStandard.Type = ScoreObjectType.YesNoStandard; if (string.IsNullOrWhiteSpace(dr["C029"].ToString())) { yesNoStandard.DefaultValue = false; } else { if (Convert.ToDouble(dr["C029"]) == 1.0) { yesNoStandard.DefaultValue = true; } else { yesNoStandard.DefaultValue = false; } } yesNoStandard.ReverseDisplay = dr["C104"].ToString() == "1"; yesNoStandard.ScoreClassic = StandardClassic.YesNo; standard = yesNoStandard; break; case StandardType.Slider: SliderStandard sliderStandard = new SliderStandard(); sliderStandard.Type = ScoreObjectType.SliderStandard; sliderStandard.MinValue = Convert.ToDouble(dr["C023"]); sliderStandard.MaxValue = Convert.ToDouble(dr["C024"]); sliderStandard.Interval = Convert.ToDouble(dr["C026"]); sliderStandard.DefaultValue = string.IsNullOrWhiteSpace(dr["C029"].ToString()) ? 0 : Convert.ToDouble(dr["C029"]); sliderStandard.ScoreClassic = StandardClassic.Slider; standard = sliderStandard; break; case StandardType.Item: ItemStandard itemStandard = new ItemStandard(); itemStandard.Type = ScoreObjectType.ItemStandard; itemStandard.ScoreClassic = StandardClassic.DropDownList; itemStandard.DefaultIndex = string.IsNullOrWhiteSpace(dr["C029"].ToString())?0: Convert.ToInt32(dr["C029"]); standard = itemStandard; break; } if (standard == null) { optReturn.Result = false; optReturn.Code = Defines.RET_OBJECT_NULL; optReturn.Message = string.Format("Standard is null"); return(optReturn); } standard.PointSystem = Convert.ToDouble(dr["C018"]); standard.StandardType = standardType; standard.IsAutoStandard = dr["C101"].ToString() == "Y"; if (!string.IsNullOrWhiteSpace(scoreID)) { if (string.IsNullOrWhiteSpace(dr["NA"].ToString())) { standard.IsNA = false; } else { standard.IsNA = dr["NA"].ToString() == "Y" ? true : false; } } string strStaID = dr["C102"].ToString(); long staID; if (long.TryParse(strStaID, out staID)) { standard.StatisticalID = staID; } scoreItem = standard; } else { ScoreGroup scoreGroup = new ScoreGroup(); scoreGroup.Type = ScoreObjectType.ScoreGroup; scoreGroup.IsAvg = dr["C016"].ToString() == "Y"; scoreItem = scoreGroup; } scoreItem.ScoreSheet = parent.ScoreSheet; scoreItem.Parent = parent; scoreItem.ItemID = Convert.ToInt32(dr["C001"]); scoreItem.ID = Convert.ToInt64(dr["C002"]); scoreItem.OrderID = Convert.ToInt32(dr["C005"]); scoreItem.Title = dr["C006"].ToString(); scoreItem.Description = dr["C007"].ToString(); scoreItem.TotalScore = Convert.ToDouble(dr["C008"]); scoreItem.IsAbortScore = dr["C010"].ToString() == "Y"; scoreItem.ControlFlag = dr["C011"].ToString() == "Y" ? 1 : 0; scoreItem.IsKeyItem = dr["C012"].ToString() == "Y"; scoreItem.IsAllowNA = dr["C013"].ToString() == "Y"; scoreItem.IsJumpItem = dr["C014"].ToString() == "Y"; scoreItem.IsAddtionItem = dr["C017"].ToString() == "Y"; scoreItem.UsePointSystem = dr["C019"].ToString() == "Y"; scoreItem.ScoreType = dr["C020"].ToString() == "F" ? ScoreType.YesNo : dr["C020"].ToString() == "P" ? ScoreType.Pecentage : ScoreType.Numeric; scoreItem.Tip = dr["C022"].ToString(); scoreItem.AllowModifyScore = dr["C103"].ToString() == "Y"; #region 子项 //如果是 ScoreGroup 加载子项 if (!isStandard) { ScoreGroup scoreGroup = scoreItem as ScoreGroup; optReturn = LoadScoreItem(session, scoreGroup, scoreID); if (!optReturn.Result) { return(optReturn); } List <ScoreItem> subItems = optReturn.Data as List <ScoreItem>; if (subItems == null) { optReturn.Result = false; optReturn.Code = Defines.RET_OBJECT_NULL; optReturn.Message = string.Format("ListItems is null"); return(optReturn); } for (int j = 0; j < subItems.Count; j++) { ScoreItem subItem = subItems[j]; scoreGroup.Items.Add(subItem); } scoreGroup.Items = scoreGroup.Items.OrderBy(j => j.OrderID).ToList(); } //如果是多值型评分标准,加载评分标准子项 ItemStandard temp = scoreItem as ItemStandard; if (temp != null) { optReturn = LoadStandardItem(session, temp); if (!optReturn.Result) { return(optReturn); } List <StandardItem> valueItems = optReturn.Data as List <StandardItem>; if (valueItems == null) { optReturn.Result = false; optReturn.Code = Defines.RET_OBJECT_NULL; optReturn.Message = string.Format("ValueItems is null"); return(optReturn); } for (int j = 0; j < valueItems.Count; j++) { StandardItem valueItem = valueItems[j]; temp.ValueItems.Add(valueItem); } temp.ValueItems = temp.ValueItems.OrderBy(j => j.OrderID).ToList(); } #endregion #region 备注 OperationReturn commentReturn; commentReturn = LoadComment(session, scoreItem); if (!commentReturn.Result) { return(commentReturn); } List <Comment> listComments = commentReturn.Data as List <Comment>; if (listComments == null) { optReturn.Result = false; optReturn.Code = Defines.RET_OBJECT_NULL; optReturn.Message = string.Format("listComments is null"); return(optReturn); } for (int j = 0; j < listComments.Count; j++) { Comment comment = listComments[j]; scoreItem.Comments.Add(comment); } scoreItem.Comments = scoreItem.Comments.OrderBy(j => j.OrderID).ToList(); #endregion #region 样式 OperationReturn styleReturn; styleReturn = LoadVisualStyle(session, scoreItem, "T"); if (!styleReturn.Result) { if (styleReturn.Code != Defines.RET_NOT_EXIST) { return(styleReturn); } scoreItem.TitleStyle = null; } else { VisualStyle style = styleReturn.Data as VisualStyle; if (style != null) { style.ScoreSheet = scoreSheet; scoreItem.TitleStyle = style; } } styleReturn = LoadVisualStyle(session, scoreItem, "P"); if (!styleReturn.Result) { if (styleReturn.Code != Defines.RET_NOT_EXIST) { return(styleReturn); } scoreItem.PanelStyle = null; } else { VisualStyle style = styleReturn.Data as VisualStyle; if (style != null) { style.ScoreSheet = scoreSheet; scoreItem.PanelStyle = style; } } #endregion listItems.Add(scoreItem); } optReturn.Data = listItems; } catch (Exception ex) { optReturn.Result = false; optReturn.Code = Defines.RET_FAIL; optReturn.Message = ex.Message; } return(optReturn); }
public bool Transcode(TranscodeInfo info, MediaPortal.Core.Transcoding.VideoFormat format, MediaPortal.Core.Transcoding.Quality quality, Standard standard) { if (!Supports(format)) return false; string ext = System.IO.Path.GetExtension(info.file); if (ext.ToLower() != ".dvr-ms" && ext.ToLower() != ".sbe") { Log.Info("DVRMS2DIVX: wrong file format"); return false; } //disable xvid status window while encoding /* try { using (RegistryKey subkey = Registry.CurrentUser.OpenSubKey(@"Software\GNU\XviD", true)) { if (subkey != null) { Int32 uivalue = 0; subkey.SetValue("display_status", (Int32)uivalue); subkey.SetValue("debug", (Int32)uivalue); subkey.SetValue("bitrate", (Int32)bitrate); uivalue = 1; subkey.SetValue("interlacing", (Int32)uivalue); } } } catch (Exception) { }*/ //Type comtype = null; //object comobj = null; try { graphBuilder = (IGraphBuilder)new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); Log.Info("DVRMS2DIVX: add filesource"); bufferSource = (IStreamBufferSource)new StreamBufferSource(); IBaseFilter filter = (IBaseFilter)bufferSource; graphBuilder.AddFilter(filter, "SBE SOURCE"); IFileSourceFilter fileSource = (IFileSourceFilter)bufferSource; Log.Info("DVRMS2DIVX: load file:{0}", info.file); int hr = fileSource.Load(info.file, null); /*string strDemuxerMoniker = @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{AFB6C280-2C41-11D3-8A60-0000F81E0E4A}"; mpegDemuxer = Marshal.BindToMoniker(strDemuxerMoniker) as IBaseFilter; if (mpegDemuxer == null) { Log.Error("DVRMS2DIVX:FAILED:unable to add mpeg2 demuxer"); Cleanup(); return false; } hr = graphBuilder.AddFilter(mpegDemuxer, "MPEG-2 Demultiplexer"); if (hr != 0) { Log.Error("DVRMS2DIVX:FAILED:Add mpeg2 demuxer to filtergraph :0x{0:X}", hr); Cleanup(); return false; }*/ //add mpeg2 audio/video codecs string strVideoCodecMoniker = @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{39F498AF-1A09-4275-B193-673B0BA3D478}"; string strAudioCodec = "MPC - MPA Decoder Filter"; Log.Info("DVRMS2DIVX: add MPV mpeg2 video decoder"); Mpeg2VideoCodec = Marshal.BindToMoniker(strVideoCodecMoniker) as IBaseFilter; if (Mpeg2VideoCodec == null) { Log.Error("DVRMS2DIVX:FAILED:unable to add MPV mpeg2 video decoder"); Cleanup(); return false; } hr = graphBuilder.AddFilter(Mpeg2VideoCodec, "MPC - MPEG-2 Video Decoder (Gabest)"); if (hr != 0) { Log.Error("DVRMS2DIVX:FAILED:Add MPV mpeg2 video to filtergraph :0x{0:X}", hr); Cleanup(); return false; } Log.Info("DVRMS2DIVX: add MPA mpeg2 audio codec:{0}", strAudioCodec); Mpeg2AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec); if (Mpeg2AudioCodec == null) { Log.Error("DVRMS2DIVX:FAILED:unable to add MPV mpeg2 audio codec"); Cleanup(); return false; } //connect output #0 of streambuffer source->mpeg2 audio codec pin 1 //connect output #1 of streambuffer source->mpeg2 video codec pin 1 Log.Info("DVRMS2DIVX: connect streambufer source->mpeg audio/video decoders"); IPin pinOut0, pinOut1; IPin pinIn0, pinIn1; pinOut0 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 0); //audio pinOut1 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 1); //video if (pinOut0 == null || pinOut1 == null) { Log.Error("DVRMS2DIVX:FAILED:unable to get pins of source"); Cleanup(); return false; } pinIn0 = DsFindPin.ByDirection(Mpeg2VideoCodec, PinDirection.Input, 0); //video pinIn1 = DsFindPin.ByDirection(Mpeg2AudioCodec, PinDirection.Input, 0); //audio if (pinIn0 == null || pinIn1 == null) { Log.Error("DVRMS2DIVX:FAILED:unable to get pins of mpeg2 video/audio codec"); Cleanup(); return false; } hr = graphBuilder.Connect(pinOut0, pinIn1); if (hr != 0) { Log.Error("DVRMS2DIVX:FAILED:unable to connect audio pins :0x{0:X}", hr); Cleanup(); return false; } hr = graphBuilder.Connect(pinOut1, pinIn0); if (hr != 0) { Log.Error("DVRMS2DIVX:FAILED:unable to connect video pins :0x{0:X}", hr); Cleanup(); return false; } if (!AddCodecs(graphBuilder, info)) return false; // hr=(graphBuilder as IMediaFilter).SetSyncSource(null); // if (hr!=0) // Log.Error("DVRMS2DIVX:FAILED:to SetSyncSource :0x{0:X}",hr); mediaControl = graphBuilder as IMediaControl; mediaSeeking = bufferSource as IStreamBufferMediaSeeking; mediaEvt = graphBuilder as IMediaEventEx; mediaPos = graphBuilder as IMediaPosition; //get file duration Log.Info("DVRMS2DIVX: Get duration of movie"); long lTime = 5 * 60 * 60; lTime *= 10000000; long pStop = 0; hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); if (hr == 0) { long lStreamPos; mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position m_dDuration = lStreamPos; lTime = 0; mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); } double duration = m_dDuration / 10000000d; Log.Info("DVRMS2DIVX: movie duration:{0}", MediaPortal.Util.Utils.SecondsToHMSString((int)duration)); // hr=(graphBuilder as IMediaFilter).SetSyncSource(null); // if (hr!=0) // Log.Error("DVRMS2DIVX:FAILED:to SetSyncSource :0x{0:X}",hr); hr = mediaControl.Run(); if (hr != 0) { Log.Error("DVRMS2DIVX:FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return false; } int maxCount = 20; while (true) { long lCurrent; mediaSeeking.GetCurrentPosition(out lCurrent); double dpos = (double)lCurrent; dpos /= 10000000d; System.Threading.Thread.Sleep(100); if (dpos >= 2.0d) break; maxCount--; if (maxCount <= 0) break; } mediaControl.Stop(); FilterState state; mediaControl.GetState(500, out state); GC.Collect(); GC.Collect(); GC.Collect(); GC.WaitForPendingFinalizers(); graphBuilder.RemoveFilter(aviMuxer); graphBuilder.RemoveFilter(divxCodec); graphBuilder.RemoveFilter(mp3Codec); graphBuilder.RemoveFilter((IBaseFilter)fileWriterFilter); if (!AddCodecs(graphBuilder, info)) return false; // hr=(graphBuilder as IMediaFilter).SetSyncSource(null); // if (hr!=0) // Log.Error("DVRMS2DIVX:FAILED:to SetSyncSource :0x{0:X}",hr); Log.Info("DVRMS2DIVX: start transcoding"); hr = mediaControl.Run(); if (hr != 0) { Log.Error("DVRMS2DIVX:FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return false; } } catch (Exception ex) { Log.Error("DVRMS2DIVX:Unable create graph: {0}", ex.Message); Cleanup(); return false; } return true; }
public bool Transcode(TranscodeInfo info, MediaPortal.Core.Transcoding.VideoFormat format, MediaPortal.Core.Transcoding.Quality quality, Standard standard) { if (!Supports(format)) return false; string ext = System.IO.Path.GetExtension(info.file); if (ext.ToLower() != ".dvr-ms" && ext.ToLower() != ".sbe") return false; //Type comtype = null; //object comobj = null; try { Log.Info("DVR2MPG: create graph"); graphBuilder = (IGraphBuilder)new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); Log.Info("DVR2MPG: add streambuffersource"); bufferSource = (IStreamBufferSource)new StreamBufferSource(); IBaseFilter filter = (IBaseFilter)bufferSource; graphBuilder.AddFilter(filter, "SBE SOURCE"); Log.Info("DVR2MPG: load file:{0}", info.file); IFileSourceFilter fileSource = (IFileSourceFilter)bufferSource; int hr = fileSource.Load(info.file, null); Log.Info("DVR2MPG: Add Cyberlink MPEG2 multiplexer to graph"); string monikerPowerDvdMuxer = @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{7F2BBEAF-E11C-4D39-90E8-938FB5A86045}"; powerDvdMuxer = Marshal.BindToMoniker(monikerPowerDvdMuxer) as IBaseFilter; if (powerDvdMuxer == null) { Log.Warn("DVR2MPG: FAILED:Unable to create Cyberlink MPEG Muxer (PowerDVD)"); Cleanup(); return false; } hr = graphBuilder.AddFilter(powerDvdMuxer, "PDR MPEG Muxer"); if (hr != 0) { Log.Warn("DVR2MPG: FAILED:Add Cyberlink MPEG Muxer to filtergraph :0x{0:X}", hr); Cleanup(); return false; } //add filewriter Log.Info("DVR2MPG: Add FileWriter to graph"); string monikerFileWrite = @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{3E8868CB-5FE8-402C-AA90-CB1AC6AE3240}"; IBaseFilter fileWriterbase = Marshal.BindToMoniker(monikerFileWrite) as IBaseFilter; if (fileWriterbase == null) { Log.Warn("DVR2MPG: FAILED:Unable to create FileWriter"); Cleanup(); return false; } fileWriterFilter = fileWriterbase as IFileSinkFilter; if (fileWriterFilter == null) { Log.Warn("DVR2MPG: FAILED:Add unable to get IFileSinkFilter for filewriter"); Cleanup(); return false; } hr = graphBuilder.AddFilter(fileWriterbase, "FileWriter"); if (hr != 0) { Log.Warn("DVR2MPG: FAILED:Add FileWriter to filtergraph :0x{0:X}", hr); Cleanup(); return false; } //connect output #0 of streambuffer source->powerdvd audio in //connect output #1 of streambuffer source->powerdvd video in Log.Info("DVR2MPG: connect streambuffer->multiplexer"); IPin pinOut0, pinOut1; IPin pinIn0, pinIn1; pinOut0 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 0); pinOut1 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 1); pinIn0 = DsFindPin.ByDirection(powerDvdMuxer, PinDirection.Input, 0); pinIn1 = DsFindPin.ByDirection(powerDvdMuxer, PinDirection.Input, 1); if (pinOut0 == null || pinOut1 == null || pinIn0 == null || pinIn1 == null) { Log.Warn("DVR2MPG: FAILED:unable to get pins of muxer&source"); Cleanup(); return false; } bool usingAc3 = false; AMMediaType amAudio = new AMMediaType(); amAudio.majorType = MediaType.Audio; amAudio.subType = MediaSubType.Mpeg2Audio; hr = pinOut0.Connect(pinIn1, amAudio); if (hr != 0) { amAudio.subType = MediaSubType.DolbyAC3; hr = pinOut0.Connect(pinIn1, amAudio); usingAc3 = true; } if (hr != 0) { Log.Warn("DVR2MPG: FAILED: unable to connect audio pins: 0x{0:X}", hr); Cleanup(); return false; } if (usingAc3) Log.Info("DVR2MPG: using AC3 audio"); else Log.Info("DVR2MPG: using MPEG audio"); AMMediaType amVideo = new AMMediaType(); amVideo.majorType = MediaType.Video; amVideo.subType = MediaSubType.Mpeg2Video; hr = pinOut1.Connect(pinIn0, amVideo); if (hr != 0) { Log.Warn("DVR2MPG: FAILED: unable to connect video pins: 0x{0:X}", hr); Cleanup(); return false; } //connect output of powerdvd muxer->input of filewriter Log.Info("DVR2MPG: connect multiplexer->filewriter"); IPin pinOut, pinIn; pinOut = DsFindPin.ByDirection(powerDvdMuxer, PinDirection.Output, 0); if (pinOut == null) { Log.Warn("DVR2MPG: FAILED:cannot get output pin of Cyberlink MPEG muxer :0x{0:X}", hr); Cleanup(); return false; } pinIn = DsFindPin.ByDirection(fileWriterbase, PinDirection.Input, 0); if (pinIn == null) { Log.Warn("DVR2MPG: FAILED:cannot get input pin of Filewriter :0x{0:X}", hr); Cleanup(); return false; } AMMediaType mt = new AMMediaType(); hr = pinOut.Connect(pinIn, mt); if (hr != 0) { Log.Warn("DVR2MPG: FAILED:connect muxer->filewriter :0x{0:X}", hr); Cleanup(); return false; } //set output filename string outputFileName = System.IO.Path.ChangeExtension(info.file, ".mpg"); Log.Info("DVR2MPG: set output file to :{0}", outputFileName); mt.majorType = MediaType.Stream; mt.subType = MediaSubTypeEx.MPEG2; hr = fileWriterFilter.SetFileName(outputFileName, mt); if (hr != 0) { Log.Warn("DVR2MPG: FAILED:unable to set filename for filewriter :0x{0:X}", hr); Cleanup(); return false; } mediaControl = graphBuilder as IMediaControl; mediaSeeking = graphBuilder as IMediaSeeking; mediaEvt = graphBuilder as IMediaEventEx; Log.Info("DVR2MPG: start transcoding"); hr = mediaControl.Run(); if (hr != 0) { Log.Warn("DVR2MPG: FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return false; } } catch (Exception ex) { Log.Error("DVR2MPG: Unable create graph: {0}", ex.Message); Cleanup(); return false; } return true; }
/// <summary> /// Get view for COSEM object. /// </summary> /// <param name="views">List of available views.</param> /// <param name="target">Selected COSEM object.</param> /// <param name="standard">Used standard.</param> /// <returns>Assigned view.</returns> public static IGXDLMSView GetView(Dictionary <Type, List <IGXDLMSView> > views, GXDLMSObject target, Standard standard) { List <IGXDLMSView> v = views[target.GetType()]; foreach (var it in v) { GXDLMSViewAttribute[] att = (GXDLMSViewAttribute[])it.GetType().GetCustomAttributes(typeof(GXDLMSViewAttribute), true); if (att.Length == 1 && Contains <byte>(att[0].Versions, (byte)target.Version) && Contains <Standard>(att[0].Standards, standard) && Contains <string>(att[0].LogicalNames, target.LogicalName)) { return(it); } } foreach (var it in v) { GXDLMSViewAttribute[] att = (GXDLMSViewAttribute[])it.GetType().GetCustomAttributes(typeof(GXDLMSViewAttribute), true); if (att.Length == 1 && Contains <byte>(att[0].Versions, (byte)target.Version) && Equals <Standard>(att[0].Standards, Standard.DLMS) && Contains <string>(att[0].LogicalNames, target.LogicalName)) { return(it); } } //Find default UI. foreach (var it in v) { GXDLMSViewAttribute[] att = (GXDLMSViewAttribute[])it.GetType().GetCustomAttributes(typeof(GXDLMSViewAttribute), true); if (att.Length == 1 && Contains <byte>(att[0].Versions, (byte)target.Version) && Equals <Standard>(att[0].Standards, Standard.DLMS) && Equals <string>(att[0].LogicalNames, null)) { return(it); } } return(v[0]); }