title: Merging multiple video files into a single mpeg-ts file "on the fly"
body: <p>First of all, sorry for my poor English. I am writting video streaming server in C++. I have multiple mpeg2-ts files (movies and advertisements) which I need to stream via HTTP as one single TS-FILE. The problem is that every mpeg-ts file has its own timestamps (PCR, PTS, DTS). And, as I understand, to make a continuous streaming flow, every new PCR (PTS, DTS) value should continue from the last PCR (PTS, DTS) value. </p>
  
  <p>Here is a picture for better understanding of what I am saying about: <a href="https://i.stack.imgur.com/vL1m6.png" rel="nofollow noreferrer">http://i.stack.imgur.com/vL1m6.png</a> (I can't include my picture directly in the message. Sorry)</p>
  
  <p>I need to replace pcr`1, pcr`2, pcr`3 timestamps with the new ones. For example, I sent ts-packet containing the pcr3 timestamp and after a few more ts packets (not containing any value of PCR) I want to insert my advertisement. And my question is: how do I calculate the new values for pcr`1, pcr`2, pcr`3 and so on?</p>
  
  <p>Is it correct to calculate the bitrate of the current video and then divide the amount of bits that the program have sent since the last PCR timestamp (in our case, it's pcr3) by this bitrate? I mean the following: (new timestamp) = (previous timestamp) + (the amount of bits) / (bitrate). Or is there a more efficient way to do it?</p>
  
  <p>As for PTS and DTS timestamps, I read <a href="https://stackoverflow.com/a/8285267/1233871">here</a> that these timestamps can be non-linear. Is it will be correct to calculate it relative to the last original PCR that I received? I mean: </p>
  
  <pre><code>pts_new = (original_pts - last_original_pcr) + pcr_new. 
  dts_new = (original_dts - last_original_pcr) + pcr_new. 
  
  (original_pts - last_original_pcr) is the difference between pts and pcr values
  pcr_new is the last modified pcr value
  </code></pre>
  
  <p>My program can read and edit these timestamps in mpeg-ts stream. Fortunately, there's a lot of literature on how to do it. But how do I calculate the new values for these timestamps?</p>
  
  <p>I have just started to learn the specification of mpeg2-ts, and please correct my mistakes if I am wrong in something.
  Thanks in advance. Hope you understood me.</p>